diff --git a/crates/registry-breg-client-node/__test__/additions.test.js b/crates/registry-breg-client-node/__test__/additions.test.js new file mode 100644 index 0000000000..b8d16ef376 --- /dev/null +++ b/crates/registry-breg-client-node/__test__/additions.test.js @@ -0,0 +1,64 @@ +'use strict'; +const assert = require('node:assert/strict'); +const http = require('node:http'); +const { createHash } = require('node:crypto'); +const { test } = require('node:test'); +const { BaseRegistryClient } = require('..'); + +test('additions preserve the submitted version and use exact binary exchanges', async () => { + const id = '00000000-0000-4000-8000-000000000001'; + const file = '00000000-0000-4000-8000-000000000002'; + const revision = `sha256:${'a'.repeat(64)}`; + const bytes = Buffer.from('support'); + const metadata = { id: 'additions', version: '1', revision, metadataVersion: '2', recordTypes: [], operations: [], actions: [], + proposals: {actions: [{actionId: 'correct', accessProfile: 'writer', operations: ['get'], readableInputs: [], readableContextFields: []}], + get: {method: 'GET', path: '/v1/proposals/{proposal_id}', accessProfiles: ['writer']}} }; + const document = {id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, revision: 2, state: 'submitted', effectDigest: revision, links: {}, + additions: {other: {id: 'other', maximumBytes: 64, maximumCount: 2, contentTypes: ['text/plain'], classification: 'restricted', items: [], + links: {add: {method: 'POST', path: `/v1/proposals/${id}/additions/other`, accessProfile: 'writer', operation: 'add', ifMatch: '"condition"'}}}}}; + const requests = []; + const server = http.createServer(async (request, response) => { + const chunks = []; for await (const chunk of request) chunks.push(chunk); + requests.push({method: request.method, url: request.url, headers: request.headers, body: Buffer.concat(chunks)}); + response.setHeader('traceparent', '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'); + response.setHeader('cache-control', 'no-store'); + if (request.url.includes(`/additions/${file}?`)) { + response.setHeader('content-type', 'text/plain'); response.setHeader('content-disposition', 'attachment'); + response.setHeader('x-content-type-options', 'nosniff'); response.setHeader('vary', 'authorization'); + return response.end(bytes); + } + if (request.method === 'POST') { + document.revision++; + document.additions.other.items.push({id: file, submissionVersion: 1, sha256: createHash('sha256').update(bytes).digest('hex'), + byteSize: bytes.length, contentType: 'text/plain', addedAt: '2026-11-27T00:00:00Z', verificationStatus: 'notRequired', + links: {download: {method: 'GET', path: `/v1/proposals/${id}/additions/${file}?submissionVersion=1`, accessProfile: 'writer', operation: 'download'}}}); + } + response.setHeader('content-type', 'application/json'); response.setHeader('vary', 'authorization, accept'); + response.end(JSON.stringify(request.url.includes('/registry?') ? metadata : document)); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + const client = new BaseRegistryClient({baseUrl: `http://127.0.0.1:${server.address().port}/tenant/`}); + assert.equal(typeof client.addProposalAddition, 'function'); + assert.equal(typeof client.downloadProposalAddition, 'function'); + const contract = await client.registryContract('writer'); + const prior = await client.getProposal(contract.selectProposalGet('writer'), id); + const before = requests.length; + await assert.rejects(client.addProposalAddition(prior, 'other', 'application/pdf', bytes, 'refused'), error => error.kind === 'invalid-request'); + assert.equal(requests.length, before); + const added = await client.addProposalAddition(prior, 'other', 'text/plain', bytes, 'addition-one'); + assert.equal(JSON.parse(added.documentJson).submissionVersion, 1); + assert.deepEqual((await client.downloadProposalAddition(added, file)).body, bytes); + const upload = requests[before]; + assert.equal(upload.method, 'POST'); assert.equal(upload.headers['if-match'], '"condition"'); + assert.equal(upload.headers['idempotency-key'], 'addition-one'); assert.deepEqual(upload.body, bytes); + assert.equal(upload.url, `/tenant/v1/proposals/${id}/additions/other?accessProfile=writer`); + const slot = document.additions.other; + slot.maximumCount = 1; + slot.items.push({...slot.items[0], id: '00000000-0000-4000-8000-000000000003', links: {}}); + slot.links.add.availability = {available: false, observedRevision: document.revision, reason: 'limit-reached', recovery: 'receipt-only'}; + const retained = await client.getProposal(contract.selectProposalGet('writer'), id); + assert.equal(JSON.parse(retained.documentJson).additions.other.items.length, 2); + assert.deepEqual((await client.downloadProposalAddition(retained, file)).body, bytes); + } finally { await new Promise(resolve => server.close(resolve)); } +}); diff --git a/crates/registry-breg-client-node/__test__/asks.test.js b/crates/registry-breg-client-node/__test__/asks.test.js new file mode 100644 index 0000000000..934976e112 --- /dev/null +++ b/crates/registry-breg-client-node/__test__/asks.test.js @@ -0,0 +1,55 @@ +'use strict'; +const assert = require('node:assert/strict'); +const http = require('node:http'); +const { test } = require('node:test'); +const { BaseRegistryClient } = require('..'); + +test('answers use the promoted ask link, exact body, ETag and caller key', async () => { + const id = '00000000-0000-4000-8000-000000000001'; + const ask = '00000000-0000-4000-8000-000000000007'; + const digest = `sha256:${'a'.repeat(64)}`; + const metadata = {id: 'asks', version: '1', revision: digest, metadataVersion: '2', recordTypes: [], operations: [], actions: [], + proposals: {actions: [{actionId: 'correct', accessProfile: 'author', operations: ['get', 'answer'], readableInputs: [], readableContextFields: []}], + get: {method: 'GET', path: '/v1/proposals/{proposal_id}', accessProfiles: ['author']}}}; + const document = {id, actionId: 'correct', actionRevision: digest, submissionVersion: 1, revision: 2, state: 'submitted', effectDigest: digest, links: {}, + asks: [{id: ask, text: 'Why?', wants: [{kind: 'answer'}], askedAt: '2026-11-27T00:00:00Z', state: 'open', links: { + answer: {method: 'POST', path: `/v1/proposals/${id}/asks/${ask}/answer`, accessProfile: 'author', operation: 'answer', ifMatch: '"condition"', availability: {available: true, observedRevision: 2}}}}]}; + const requests = []; + const server = http.createServer(async (request, response) => { + const chunks = []; for await (const chunk of request) chunks.push(chunk); + requests.push({method: request.method, url: request.url, headers: request.headers, body: Buffer.concat(chunks)}); + response.setHeader('traceparent', '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'); + response.setHeader('cache-control', 'no-store'); response.setHeader('content-type', 'application/json'); response.setHeader('vary', 'authorization, accept'); + if (request.method === 'POST') { + document.revision = 3; document.asks[0].state = 'answered'; + document.asks[0].answer = {...JSON.parse(requests.at(-1).body), additions: [], answeredAt: '2026-11-27T01:00:00Z'}; + document.asks[0].links.answer.availability = {available: false, observedRevision: 3, reason: 'ask-answered', recovery: 'receipt-only'}; + response.setHeader('etag', `"breg-v1-${'c'.repeat(64)}"`); + } + response.end(JSON.stringify(request.url.includes('/registry?') ? metadata : document)); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + const client = new BaseRegistryClient({baseUrl: `http://127.0.0.1:${server.address().port}/tenant/`}); + assert.equal(typeof client.answerProposalAsk, 'function'); + const contract = await client.registryContract('author'); + const prior = await client.getProposal(contract.selectProposalGet('author'), id); + const before = requests.length; + await assert.rejects(client.answerProposalAsk(prior, ask, {text: ' '}, 'invalid'), error => error.kind === 'invalid-request'); + assert.equal(requests.length, before); + document.asks[0].wants = []; + const withoutWants = await client.getProposal(contract.selectProposalGet('author'), id); + const beforeEmpty = requests.length; + for (const body of [{}, {additions: []}]) { + await assert.rejects(client.answerProposalAsk(withoutWants, ask, body, 'empty'), error => error.kind === 'invalid-request'); + } + assert.equal(requests.length, beforeEmpty); + document.asks[0].wants = [{kind: 'answer'}]; + const answered = await client.answerProposalAsk(prior, ask, {text: 'The explanation'}, 'answer-one'); + assert.equal(JSON.parse(answered.documentJson).asks[0].answer.text, 'The explanation'); + const wire = requests.at(-1); + assert.equal(wire.url, `/tenant/v1/proposals/${id}/asks/${ask}/answer?accessProfile=author`); + assert.equal(wire.headers['if-match'], '"condition"'); assert.equal(wire.headers['idempotency-key'], 'answer-one'); + assert.deepEqual(JSON.parse(wire.body), {text: 'The explanation'}); + } finally { await new Promise(resolve => server.close(resolve)); } +}); diff --git a/crates/registry-breg-client-node/__test__/binding.test.js b/crates/registry-breg-client-node/__test__/binding.test.js index 317236862b..ac25c2c8e8 100644 --- a/crates/registry-breg-client-node/__test__/binding.test.js +++ b/crates/registry-breg-client-node/__test__/binding.test.js @@ -294,6 +294,7 @@ test('a write boundary refusal uses the core problem projection without detail l }); }); + test('unknown problem codes fall back to HTTP status semantics', async () => { const client = new BaseRegistryClient({ baseUrl }); for (const [recordId, status] of UNKNOWN_PROBLEM_STATUSES) { diff --git a/crates/registry-breg-client-node/__test__/facade.test-d.ts b/crates/registry-breg-client-node/__test__/facade.test-d.ts index 9dd5dd97a5..a695c74a4b 100644 --- a/crates/registry-breg-client-node/__test__/facade.test-d.ts +++ b/crates/registry-breg-client-node/__test__/facade.test-d.ts @@ -13,6 +13,7 @@ import { BRegRecoveredAction, BRegRecoveredCreate, BRegProposal, + BRegProposalDocument, BRegProposalGetBinding, BRegProposalCollection, BRegPreparedProposal, @@ -32,6 +33,18 @@ import { } from '..' declare const client: BaseRegistryClient +declare const additionProposal: BRegProposal +declare const additionDocument: BRegProposalDocument +const proposalStatus: import('..').BRegProposalStatus | undefined = additionDocument.status +void proposalStatus +// @ts-expect-error The served status vocabulary is closed. +const invalidProposalStatus: import('..').BRegProposalStatus = 'queued' +void invalidProposalStatus +client.addProposalAddition(additionProposal, 'other', 'text/plain', Buffer.from('support'), 'addition-one') +client.downloadProposalAddition(additionProposal, '00000000-0000-4000-8000-000000000002') +additionDocument.additions?.other?.items[0]?.addedAt.toUpperCase() +// @ts-expect-error Added file bytes use Buffer rather than a JSON string. +client.addProposalAddition(additionProposal, 'other', 'text/plain', 'support', 'addition-one') new BaseRegistryClient({ baseUrl: 'https://registry.example.test/', maximumResponseBytes: 8 * 1024 * 1024, diff --git a/crates/registry-breg-client-node/__test__/proposal-results.test.js b/crates/registry-breg-client-node/__test__/proposal-results.test.js index bf9b5a5058..1265150908 100644 --- a/crates/registry-breg-client-node/__test__/proposal-results.test.js +++ b/crates/registry-breg-client-node/__test__/proposal-results.test.js @@ -30,6 +30,7 @@ const statusDocument = state => { test('Proposal response boundaries preserve disclosure and exact Action revision bindings', async t => { let value = document(); let replyStatus = 200; + let replyContentType = 'application/json'; let downloadBytes; const requests = []; const wireRequests = []; @@ -46,7 +47,7 @@ test('Proposal response boundaries preserve disclosure and exact Action revision response.end(downloadBytes); return; } - response.writeHead(replyStatus, {'content-type': 'application/json', 'cache-control': 'no-store', 'vary': 'authorization, accept', + response.writeHead(replyStatus, {'content-type': replyContentType, 'cache-control': 'no-store', 'vary': 'authorization, accept', traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'}); response.end(JSON.stringify(request.url.startsWith('/v1/registry') ? metadata : value)); }); @@ -96,6 +97,45 @@ test('Proposal response boundaries preserve disclosure and exact Action revision } }); + await t.test('application refusals preserve Rebase and Revise recovery', async () => { + for (const [reason, recovery] of [['stale-revision', 'rebase'], ['invalid-input', 'revise']]) { + value = statusDocument('blocked'); + Object.assign(value.applicationStatus, {reason: 'application-refused', recovery}); + value.links.apply = {method: 'POST', path: `/v1/proposals/${id}/apply`, accessProfile: 'reader', operation: 'apply', ifMatch: '"blocked-condition"', + availability: {available: false, observedRevision: 8, reason, recovery}}; + const observed = JSON.parse((await client.getProposal(binding, id)).documentJson); + assert.deepEqual(observed.applicationStatus, value.applicationStatus); + assert.deepEqual(observed.links.apply.availability, value.links.apply.availability); + } + }); + + await t.test('Submit attachment problems preserve only their slot location', async () => { + value = document(); value.state = 'draft'; delete value.application; delete value.effectDigest; + value.links.submit = {method: 'POST', path: `/v1/proposals/${id}/submit`, accessProfile: 'reader', + operation: 'submit', ifMatch: '"attachment-condition"'}; + const draft = await client.getProposal(binding, id); + try { + for (const [code, status, detail] of [ + ['attachment.required', 422, 'The required attachment slot is empty.'], + ['attachment.verification-pending', 409, 'The attachment is awaiting verification. Refresh the Proposal before submitting.'], + ['attachment.verification-rejected', 422, 'The attachment was rejected by verification. Replace or remove the file before submitting.'], + ]) { + const attempt = client.prepareProposal(draft, 'submit', {}, `attachment-${code}`); + replyStatus = status; replyContentType = 'application/problem+json'; + value = {type: `https://id.registrystack.org/problems/registry-breg/${code.replaceAll('.', '/')}`, + title: status === 409 ? 'Conflict' : 'Unprocessable Entity', status, detail, code, + traceId: '4bf92f3577b34da6a3ce929d0e0e4736', fieldPath: '/attachments/support'}; + await assert.rejects(client.executeProposal(attempt), error => { + assert.equal(error.kind, 'problem'); assert.equal(error.code, code); + assert.equal(error.status, status); assert.equal(error.fieldPath, '/attachments/support'); + assert.equal(error.outcomeUnknown, false); return true; + }); + assert.equal(wireRequests.at(-1).method, 'POST'); + assert.match(wireRequests.at(-1).url, /\/submit\?accessProfile=reader$/); + } + } finally { replyStatus = 200; replyContentType = 'application/json'; } + }); + value = document(); value.application.resultLinks = []; assert.deepEqual(JSON.parse((await client.getProposal(binding, id)).documentJson).application.resultLinks, []); diff --git a/crates/registry-breg-client-node/__test__/proposals.test.js b/crates/registry-breg-client-node/__test__/proposals.test.js index 3bf8f9eebf..4d5a2a21b8 100644 --- a/crates/registry-breg-client-node/__test__/proposals.test.js +++ b/crates/registry-breg-client-node/__test__/proposals.test.js @@ -28,6 +28,45 @@ const proposal = {id, actionId: 'correct', actionRevision: revision, submissionV submit: {method: 'POST', path: `/v1/proposals/${id}/submit`, accessProfile: 'author', operation: 'submit', ifMatch: '"draft-condition"'}, }}; +test('Proposal status is a closed served value and application-pending requires refresh', async () => { + let document = proposal; + const server = http.createServer((request, response) => { + response.setHeader('content-type', 'application/json'); + response.setHeader('cache-control', 'no-store'); + response.setHeader('vary', 'authorization, accept'); + response.setHeader('traceparent', '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'); + response.end(JSON.stringify(request.url.includes('/registry') ? metadata : document)); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + const client = new BaseRegistryClient({baseUrl: `http://127.0.0.1:${server.address().port}/`}); + const binding = (await client.registryContract('author')).selectProposalGet('author'); + for (const [status, state, turn] of [ + ['draft', 'draft', 'party'], ['awaiting-party', 'submitted', 'party'], + ['in-review', 'submitted', 'official'], ['approved', 'submitted', 'official'], + ['processing', 'submitted', 'nobody'], ['applied', 'applied', 'nobody'], + ['rejected', 'rejected', 'nobody'], ['cancelled', 'cancelled', 'nobody'], + ]) { + document = {...proposal, state, status, turn, links: {self: proposal.links.self}}; + if (state === 'submitted') document.effectDigest = revision; + assert.equal(JSON.parse((await client.getProposal(binding, id)).documentJson).status, status); + } + document = {...proposal, state: 'submitted', status: 'approved', turn: 'official', effectDigest: revision, links: { + self: proposal.links.self, revise: {method: 'POST', path: `/v1/proposals/${id}/revise`, accessProfile: 'author', operation: 'revise', + ifMatch: '"condition"', availability: {available: false, observedRevision: 1, reason: 'application-pending', recovery: 'refresh'}}, + }}; + assert.equal(JSON.parse((await client.getProposal(binding, id)).documentJson).links.revise.availability.reason, 'application-pending'); + document.links.revise.availability.recovery = 'retry'; + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request'); + for (const status of ['unknown', null, false, 1]) { + document = {...proposal, status}; + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request'); + } + document = proposal; + assert.equal(JSON.parse((await client.getProposal(binding, id)).documentJson).status, undefined); + } finally { await new Promise(resolve => server.close(resolve)); } +}); + test('proposal object methods preserve exact bodies and refuse JSON strings before I/O', async () => { const requests = []; const server = http.createServer(async (request, response) => { diff --git a/crates/registry-breg-client-node/__test__/review-documents.test.js b/crates/registry-breg-client-node/__test__/review-documents.test.js index eb110995b8..ee23492e7a 100644 --- a/crates/registry-breg-client-node/__test__/review-documents.test.js +++ b/crates/registry-breg-client-node/__test__/review-documents.test.js @@ -53,12 +53,14 @@ test('review-only binding reads context and exact document without Proposal Get' const binding = contract.selectProposalReviewContext('reviewer', 'correct'); assert.ok(binding instanceof BRegProposalReviewBinding); const observed = (await client.readProposalReviewById(binding, id)).value; + assert.equal(new URL(requests.at(-1), 'http://local').searchParams.get('include'), 'answers'); const batch = await client.readProposalReviewContextBatch(binding, [id, concealedId]); assert.deepEqual(batch.value, [observed, null]); const batchUrl = new URL(requests.at(-1), 'http://local'); assert.equal(batchUrl.pathname, '/tenant/v1/proposals/review-context'); assert.equal(batchUrl.searchParams.get('ids'), `${id},${concealedId}`); assert.equal(batchUrl.searchParams.get('accessProfile'), 'reviewer'); + assert.equal(batchUrl.searchParams.has('include'), false); const beforeBatchRefusals = requests.length; for (const ids of [[], [id, id]]) { await assert.rejects(client.readProposalReviewContextBatch(binding, ids), error => error.kind === 'invalid-request'); diff --git a/crates/registry-breg-client-node/client.d.ts b/crates/registry-breg-client-node/client.d.ts index 0c321103b2..7b704e610e 100644 --- a/crates/registry-breg-client-node/client.d.ts +++ b/crates/registry-breg-client-node/client.d.ts @@ -1003,6 +1003,9 @@ export declare class BaseRegistryClient { executeRecoveredAction(binding: BRegActionBinding, recovered: BRegRecoveredAction): Promise> executeRecoveredProposalStart(binding: BRegActionBinding, recovered: BRegRecoveredAction): Promise downloadProposalAttachment(proposal: BRegProposal, slot: string): Promise + answerProposalAsk(proposal: BRegProposal, askId: string, body: BRegProposalAnswerRequest, key: string): Promise + downloadProposalAddition(proposal: BRegProposal, addition: string): Promise + addProposalAddition(proposal: BRegProposal, slot: string, contentType: string, bytes: Buffer, key: string): Promise readProposalReviewStatus(proposal: BRegProposal, request?: ReadRequestOptions): Promise> readProposalReviewStatusWithProgress(proposal: BRegProposal, request?: ReadRequestOptions): Promise> readProposalReviewContext(proposal: BRegProposal, request?: ReadRequestOptions): Promise> @@ -1049,7 +1052,7 @@ export declare class BaseRegistryClient { } export type BRegProposalTransition = 'edit' | 'submit' | 'revise' | 'rebase' | 'retry' | 'cancel' | 'apply' -export type BRegAvailabilityReason = 'pending-review' | 'review-rejected' | 'review-changes-requested' | 'review-ended' | 'stale-revision' | 'package-changed' | 'dependency-outage' | 'invalid-input' | 'already-applied' +export type BRegAvailabilityReason = 'pending-review' | 'review-rejected' | 'review-changes-requested' | 'review-ended' | 'stale-revision' | 'package-changed' | 'dependency-outage' | 'invalid-input' | 'already-applied' | 'limit-reached' | 'application-pending' | 'attachment-required' | 'attachment-pending' | 'ask-answered' | 'ask-closed' | 'ask-due-passed' export type BRegRecoveryHint = 'refresh' | 'revise' | 'retry' | 'rebase' | 'correct-input' | 'receipt-only' export type BRegAvailability = | { readonly available: true; readonly observedRevision: number } @@ -1061,6 +1064,16 @@ export interface BRegProposalAttachment { readonly links: Readonly & {readonly method: 'GET' | 'PATCH' | 'DELETE'}>>> readonly value?: {readonly submissionVersion: number; readonly sha256: string; readonly contentType: string; readonly byteSize: number; readonly uploadedAt?: string; readonly verificationStatus: 'notRequired' | 'pending' | 'approved' | 'rejected'} } +export interface BRegProposalAddition { + readonly id: string; readonly submissionVersion: number; readonly sha256: string; readonly byteSize: number + readonly contentType: string; readonly addedAt: string; readonly verificationStatus: 'notRequired' | 'pending' | 'approved' | 'rejected' + readonly links: Readonly>> +} +export interface BRegProposalAdditionSlot { + readonly id: string; readonly maximumBytes: number; readonly maximumCount: number + readonly contentTypes: ReadonlyArray; readonly classification: 'public' | 'internal' | 'restricted' + readonly items: ReadonlyArray; readonly links: Readonly>> +} export interface BRegProposalApplication { readonly applicationId: string; readonly submissionVersion: number; readonly effectDigest: string readonly appliedBy?: string; readonly appliedAt?: string @@ -1070,14 +1083,14 @@ export interface BRegProposalApplicationStatus { readonly state: 'awaiting-review' | 'pending' | 'applying' | 'blocked' | 'applied' | 'cancelled' | 'rejected' readonly mode: 'automatic' | 'manual' readonly reason?: 'package-changed' | 'dependency-outage' | 'lease-expired' | 'application-refused' | 'attempts-exhausted' - readonly recovery?: 'retry' | 'rebase' | 'correct-input' + readonly recovery?: 'retry' | 'rebase' | 'revise' | 'correct-input' readonly automaticRetry?: {readonly scheduled: boolean; readonly attempts: number; readonly maximumAttempts: number} } export interface BRegProposalReviewDocument { readonly id: string; readonly actionId: string; readonly actionRevision: string readonly submissionVersion: number; readonly revision: number; readonly effectDigest: string; readonly reviewable: boolean readonly subject: {readonly source: string; readonly subjectType: 'proposal'; readonly id: string; readonly version: string; readonly digest: string} - readonly context: {readonly reference: string; readonly contract?: {readonly id: string; readonly revision: string; readonly schemaDigest: string}; readonly fields?: Readonly>} + readonly context: {readonly reference: string; readonly contract?: {readonly id: string; readonly revision: string; readonly schemaDigest: string}; readonly fields?: Readonly>; readonly asks?: ReadonlyArray} readonly requestId?: string /** Present only on an explicit progress status read while the accepted request remains pending. */ readonly progressCode?: string @@ -1088,6 +1101,7 @@ export interface BRegProposalReviewDocument { } /** Who is expected to act next, derived by BReg. */ export type BRegProposalTurn = 'party' | 'official' | 'nobody' +export type BRegProposalStatus = 'draft' | 'awaiting-party' | 'in-review' | 'approved' | 'processing' | 'applied' | 'rejected' | 'cancelled' /** The review decision on one submission. The public reason is the only reviewer text BReg serves. */ export interface BRegProposalDecision { readonly status: 'approved' | 'rejected' | 'changes-requested' | 'answered'; readonly decidedAt: string; readonly publicReason?: string } /** Why the review authority refused to take a submission. BReg names only these codes and never the authority's own text. */ @@ -1099,7 +1113,7 @@ export interface BRegProposalSubmission { readonly decision?: BRegProposalDecision readonly handoffRefusal?: BRegProposalHandoffRefusal } -export interface BRegProposalDocument { readonly id: string; readonly actionId: string; readonly actionRevision: string; readonly submissionVersion: number; readonly revision: number; readonly state: 'draft' | 'submitted' | 'cancelled' | 'applied' | 'rejected'; readonly createdAt?: string; readonly turn?: BRegProposalTurn; readonly decision?: BRegProposalDecision; readonly handoffRefusal?: BRegProposalHandoffRefusal; readonly title?: string; readonly input?: JsonObject; readonly blockedReason?: 'package-changed'; readonly effectDigest?: string; readonly application?: BRegProposalApplication; readonly applicationStatus?: BRegProposalApplicationStatus; readonly links: Readonly>>; readonly attachments?: Readonly> } +export interface BRegProposalDocument { readonly id: string; readonly actionId: string; readonly actionRevision: string; readonly submissionVersion: number; readonly revision: number; readonly state: 'draft' | 'submitted' | 'cancelled' | 'applied' | 'rejected'; readonly createdAt?: string; readonly turn?: BRegProposalTurn; readonly status?: BRegProposalStatus; readonly decision?: BRegProposalDecision; readonly handoffRefusal?: BRegProposalHandoffRefusal; readonly title?: string; readonly input?: JsonObject; readonly blockedReason?: 'package-changed'; readonly effectDigest?: string; readonly application?: BRegProposalApplication; readonly applicationStatus?: BRegProposalApplicationStatus; readonly links: Readonly>>; readonly attachments?: Readonly>; readonly additions?: Readonly>; readonly asks?: ReadonlyArray } export declare class BRegProposal { private constructor(); private readonly __opaque: void; readonly responseEtag: string | null; readonly identifier: string; readonly actionIdentifier: string; readonly documentJson: string; readonly inputJson?: string | null } export declare class BRegProposalGetBinding { private constructor(); private readonly __opaque: void } export declare class BRegProposalReviewBinding { private constructor(); private readonly __opaque: void } @@ -1122,3 +1136,20 @@ export declare class BRegProposalCollection { private constructor(); private rea export interface BRegProposalPage { readonly items: ReadonlyArray; readonly nextCursor?: string } export declare class BRegPreparedProposal { private constructor(); private readonly __opaque: void; static fromBytes(bytes: Buffer): BRegPreparedProposal; toBytes(): Buffer } + +export type BRegProposalAskState = 'open' | 'answered' | 'expired' | 'closed' +export type BRegProposalAskWant = {readonly kind: 'answer'} | {readonly kind: 'document'} +export interface BRegProposalAnswerRequest {readonly text?: string; readonly additions?: ReadonlyArray} +export interface BRegProposalAskAnswer {readonly text?: string; readonly additions: ReadonlyArray; readonly answeredAt: string} +export interface BRegProposalAsk { + readonly id: string; readonly text: string; readonly wants: ReadonlyArray + readonly askedAt: string; readonly dueAt?: string; readonly state: BRegProposalAskState + readonly answer?: BRegProposalAskAnswer; readonly links: Readonly>> +} +export interface BRegProposalReviewAnswerDownload {readonly method: 'GET'; readonly operation: 'get-review-context'; readonly accessProfile: string; readonly path: string} +export interface BRegProposalReviewAnswerDocument { + readonly id: string; readonly sha256: string; readonly contentType: string; readonly byteSize: number + readonly verificationStatus: 'notRequired' | 'pending' | 'approved' | 'rejected'; readonly download?: BRegProposalReviewAnswerDownload +} +export interface BRegProposalReviewAnswer {readonly text?: string; readonly documents: ReadonlyArray; readonly answeredAt: string} +export interface BRegProposalReviewAsk extends Omit {readonly answer?: BRegProposalReviewAnswer} diff --git a/crates/registry-breg-client-node/client.js b/crates/registry-breg-client-node/client.js index d5fe4108a0..4382702991 100644 --- a/crates/registry-breg-client-node/client.js +++ b/crates/registry-breg-client-node/client.js @@ -303,6 +303,8 @@ for (const [method, jsonIndexes, requiredIndexes] of [ ['patchRecord', [3], [3]], ['batchRecords', [1], [1]], ['tombstoneRecord'], ['startProposal', [1], [1]], ['readProposal'], ['readProposalSubmission'], ['getProposal'], ['listProposals', [1], [1]], ['executeProposal'], ['listProposalsJson'], ['downloadProposalAttachment'], ['uploadProposalAttachment'], ['deleteProposalAttachment'], + ['answerProposalAsk'], + ['addProposalAddition'], ['downloadProposalAddition'], ['downloadRecordAttachment'], ['readProposalReviewStatus'], ['readProposalReviewStatusWithProgress'], ['readProposalReviewContext'], ['readProposalReviewContextBatch', [1], [1]], diff --git a/crates/registry-breg-client-node/index.d.ts b/crates/registry-breg-client-node/index.d.ts index 32cab7ca9f..909fb4158c 100644 --- a/crates/registry-breg-client-node/index.d.ts +++ b/crates/registry-breg-client-node/index.d.ts @@ -67,6 +67,9 @@ export declare class BaseRegistryClient { readProposalReviewStatusWithProgress(proposal: BRegProposal, cancellation?: ReadCancellation | undefined | null): Promise readProposalReviewContext(proposal: BRegProposal, cancellation?: ReadCancellation | undefined | null): Promise readProposalReviewContextBatch(binding: BRegProposalReviewBinding, ids: Array, cancellation?: ReadCancellation | undefined | null): Promise + answerProposalAsk(proposal: BRegProposal, askId: string, body: any, key: string): Promise + addProposalAddition(proposal: BRegProposal, slot: string, contentType: string, bytes: Buffer, key: string): Promise + downloadProposalAddition(proposal: BRegProposal, addition: string): Promise uploadProposalAttachment(proposal: BRegProposal, slot: string, contentType: string, bytes: Buffer, key: string): Promise deleteProposalAttachment(proposal: BRegProposal, slot: string, key: string): Promise listProposals(collection: BRegProposalCollection, query: any, cancellation?: ReadCancellation | undefined | null): Promise diff --git a/crates/registry-breg-client-node/src/lib.rs b/crates/registry-breg-client-node/src/lib.rs index 622c89ca0b..8ff30e6905 100644 --- a/crates/registry-breg-client-node/src/lib.rs +++ b/crates/registry-breg-client-node/src/lib.rs @@ -3546,6 +3546,66 @@ impl BaseRegistryClient { .await } + #[napi] + pub async fn answer_proposal_ask( + &self, + proposal: &Proposal, + ask_id: String, + body: Value, + key: String, + ) -> Result { + let body: registry_breg_client::BRegProposalAnswerRequest = serde_json::from_value(body) + .map_err(|_| binding_error("invalid-request", "Proposal answer must be exact JSON"))?; + let key = idempotency_key(key)?; + self.inner + .answer_proposal_ask(&proposal.inner, &ask_id, &body, &key) + .await + .map(|response| Proposal { + response_etag: response + .metadata + .etag() + .map(|etag| etag.as_str().to_owned()), + inner: response.value, + }) + .map_err(client_error) + } + + #[napi] + pub async fn add_proposal_addition( + &self, + proposal: &Proposal, + slot: String, + content_type: String, + bytes: Buffer, + key: String, + ) -> Result { + let key = idempotency_key(key)?; + self.inner + .add_proposal_addition(&proposal.inner, &slot, &content_type, &bytes, &key) + .await + .map(|response| Proposal { + response_etag: response + .metadata + .etag() + .map(|etag| etag.as_str().to_owned()), + inner: response.value, + }) + .map_err(client_error) + } + + #[napi] + pub async fn download_proposal_addition( + &self, + proposal: &Proposal, + addition: String, + ) -> Result { + self.inner + .download_proposal_addition(&proposal.inner, &addition) + .await + .map(raw_value) + .map_err(client_error) + } + #[napi] pub async fn upload_proposal_attachment( &self, diff --git a/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi b/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi index ddcc9cb065..7d37e72fd2 100644 --- a/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi +++ b/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi @@ -692,6 +692,9 @@ class BaseRegistryClient: ) -> dict[str, Any]: ... def execute_recovered_proposal_start(self, binding: BRegActionBinding, recovered: BRegRecoveredAction) -> BRegProposal: ... def download_proposal_attachment(self, proposal: BRegProposal, slot: str) -> dict[str, Any]: ... + def answer_proposal_ask(self, proposal: BRegProposal, ask_id: str, body: BRegProposalAnswerRequest, key: str) -> BRegProposal: ... + def download_proposal_addition(self, proposal: BRegProposal, addition: str) -> dict[str, Any]: ... + def add_proposal_addition(self, proposal: BRegProposal, slot: str, content_type: str, bytes: bytes, key: str) -> BRegProposal: ... def read_proposal_review_status(self, proposal: BRegProposal) -> dict[str, Any]: ... def read_proposal_review_status_with_progress(self, proposal: BRegProposal) -> BRegProposalReviewCompleteOutcome: ... def read_proposal_review_context(self, proposal: BRegProposal) -> dict[str, Any]: ... @@ -770,6 +773,7 @@ class PrivateKeyJwt: def bearer_token(self) -> str: ... BRegProposalTransition = Literal['edit', 'submit', 'revise', 'rebase', 'retry', 'cancel', 'apply'] +BRegProposalStatus = Literal['draft', 'awaiting-party', 'in-review', 'approved', 'processing', 'applied', 'rejected', 'cancelled'] class BRegProposal: @property def response_etag(self) -> str | None: @@ -795,3 +799,47 @@ class BRegPreparedProposal: @staticmethod def from_bytes(value: bytes) -> BRegPreparedProposal: ... def to_bytes(self) -> bytes: ... + +BRegProposalAskState = Literal['open', 'answered', 'expired', 'closed'] +class BRegProposalAskWant(TypedDict): + kind: Literal['answer', 'document'] +class BRegProposalAnswerRequest(TypedDict): + text: NotRequired[str] + additions: NotRequired[list[str]] +class BRegProposalAskAnswer(TypedDict): + text: NotRequired[str] + additions: list[str] + answeredAt: str +class BRegProposalAsk(TypedDict): + id: str + text: str + wants: list[BRegProposalAskWant] + askedAt: str + dueAt: NotRequired[str] + state: BRegProposalAskState + answer: NotRequired[BRegProposalAskAnswer] + links: dict[str, JsonValue] +class BRegProposalReviewAnswerDownload(TypedDict): + method: Literal['GET'] + operation: Literal['get-review-context'] + accessProfile: str + path: str +class BRegProposalReviewAnswerDocument(TypedDict): + id: str + sha256: str + contentType: str + byteSize: int + verificationStatus: Literal['notRequired', 'pending', 'approved', 'rejected'] + download: NotRequired[BRegProposalReviewAnswerDownload] +class BRegProposalReviewAnswer(TypedDict): + text: NotRequired[str] + documents: list[BRegProposalReviewAnswerDocument] + answeredAt: str +class BRegProposalReviewAsk(TypedDict): + id: str + text: str + wants: list[BRegProposalAskWant] + askedAt: str + dueAt: NotRequired[str] + state: BRegProposalAskState + answer: NotRequired[BRegProposalReviewAnswer] diff --git a/crates/registry-breg-client-py/src/lib.rs b/crates/registry-breg-client-py/src/lib.rs index 16557e651d..bd6e58d77d 100644 --- a/crates/registry-breg-client-py/src/lib.rs +++ b/crates/registry-breg-client-py/src/lib.rs @@ -3030,6 +3030,85 @@ impl BaseRegistryClient { .map_err(|error| sdk_error(py, error))?; complete_value(py, &response.value, &response.metadata) } + fn answer_proposal_ask( + &self, + py: Python<'_>, + proposal: PyRef<'_, Proposal>, + ask_id: &str, + body: &Bound<'_, PyAny>, + key: &str, + ) -> PyResult { + let proposal = proposal.inner.clone(); + let value = + python_to_json(body).map_err(|_| invalid(py, "Proposal answer must be exact JSON"))?; + let body: breg_client_sdk::BRegProposalAnswerRequest = serde_json::from_value(value) + .map_err(|_| invalid(py, "Proposal answer must be exact JSON"))?; + let key = BRegIdempotencyKey::parse(key).map_err(|error| invalid(py, error.to_string()))?; + let response = py + .detach(|| { + self.runtime.block_on( + self.inner + .answer_proposal_ask(&proposal, ask_id, &body, &key), + ) + }) + .map_err(|error| sdk_error(py, error))?; + Ok(Proposal { + response_etag: response + .metadata + .etag() + .map(|etag| etag.as_str().to_owned()), + inner: response.value, + }) + } + + fn add_proposal_addition( + &self, + py: Python<'_>, + proposal: PyRef<'_, Proposal>, + slot: &str, + content_type: &str, + bytes: &[u8], + key: &str, + ) -> PyResult { + let proposal = proposal.inner.clone(); + let bytes = bytes.to_vec(); + let key = BRegIdempotencyKey::parse(key).map_err(|error| invalid(py, error.to_string()))?; + let response = py + .detach(|| { + self.runtime.block_on(self.inner.add_proposal_addition( + &proposal, + slot, + content_type, + &bytes, + &key, + )) + }) + .map_err(|error| sdk_error(py, error))?; + Ok(Proposal { + response_etag: response + .metadata + .etag() + .map(|etag| etag.as_str().to_owned()), + inner: response.value, + }) + } + + fn download_proposal_addition<'py>( + &self, + py: Python<'py>, + proposal: PyRef<'_, Proposal>, + addition: &str, + ) -> PyResult> { + let proposal = proposal.inner.clone(); + let response = py + .detach(|| { + self.runtime + .block_on(self.inner.download_proposal_addition(&proposal, addition)) + }) + .map_err(|error| sdk_error(py, error))?; + raw_value(py, &response.value, &response.metadata) + } + fn upload_proposal_attachment( &self, py: Python<'_>, diff --git a/crates/registry-breg-client-py/tests/python/test_additions.py b/crates/registry-breg-client-py/tests/python/test_additions.py new file mode 100644 index 0000000000..f7d3e461fa --- /dev/null +++ b/crates/registry-breg-client-py/tests/python/test_additions.py @@ -0,0 +1,98 @@ +"""Supporting-file additions use the canonical Rust binary contract.""" +import hashlib +import json +import threading +import unittest +from http.server import BaseHTTPRequestHandler, HTTPServer +from bootstrap import ensure_built + +ensure_built() +from registry_breg_client import BaseRegistryClient, BaseRegistryClientError + + +class AdditionTests(unittest.TestCase): + def test_addition_and_download_keep_the_exact_submission(self): + proposal_id = '00000000-0000-4000-8000-000000000001' + addition_id = '00000000-0000-4000-8000-000000000002' + revision = 'sha256:' + 'a' * 64 + content = b'support' + requests = [] + metadata = {'id': 'additions', 'version': '1', 'revision': revision, 'metadataVersion': '2', + 'recordTypes': [], 'operations': [], 'actions': [], 'proposals': { + 'actions': [{'actionId': 'correct', 'accessProfile': 'writer', 'operations': ['get'], 'readableInputs': [], 'readableContextFields': []}], + 'get': {'method': 'GET', 'path': '/v1/proposals/{proposal_id}', 'accessProfiles': ['writer']}}} + document = {'id': proposal_id, 'actionId': 'correct', 'actionRevision': revision, 'submissionVersion': 1, + 'revision': 2, 'state': 'submitted', 'effectDigest': revision, 'links': {}, 'additions': {'other': { + 'id': 'other', 'maximumBytes': 64, 'maximumCount': 2, 'contentTypes': ['text/plain'], + 'classification': 'restricted', 'items': [], 'links': {'add': {'method': 'POST', + 'path': f'/v1/proposals/{proposal_id}/additions/other', 'accessProfile': 'writer', 'operation': 'add', 'ifMatch': '"condition"'}}}}} + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + requests.append(('GET', self.path, dict(self.headers), b'')) + if f'/additions/{addition_id}?' in self.path: + self.respond(content, 'text/plain', True) + else: + self.respond(json.dumps(metadata if '/registry?' in self.path else document).encode()) + + def do_POST(self): + body = self.rfile.read(int(self.headers['content-length'])) + requests.append(('POST', self.path, dict(self.headers), body)) + document['revision'] += 1 + document['additions']['other']['items'].append({'id': addition_id, 'submissionVersion': 1, + 'sha256': hashlib.sha256(content).hexdigest(), 'byteSize': len(content), 'contentType': 'text/plain', + 'addedAt': '2026-11-27T00:00:00Z', 'verificationStatus': 'notRequired', 'links': {'download': { + 'method': 'GET', 'path': f'/v1/proposals/{proposal_id}/additions/{addition_id}?submissionVersion=1', + 'accessProfile': 'writer', 'operation': 'download'}}}) + self.respond(json.dumps(document).encode()) + + def respond(self, payload, media='application/json', download=False): + self.send_response(200) + for key, value in [('content-type', media), ('cache-control', 'no-store'), ('content-length', str(len(payload))), + ('vary', 'authorization' if download else 'authorization, accept'), + ('traceparent', '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01')]: + self.send_header(key, value) + if download: + self.send_header('content-disposition', 'attachment') + self.send_header('x-content-type-options', 'nosniff') + self.end_headers() + self.wfile.write(payload) + + def log_message(self, *args): + return + + server = HTTPServer(('127.0.0.1', 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + client = BaseRegistryClient(f'http://127.0.0.1:{server.server_port}/tenant/') + self.assertTrue(hasattr(client, 'add_proposal_addition')) + self.assertTrue(hasattr(client, 'download_proposal_addition')) + contract = client.registry_contract('writer') + prior = client.get_proposal(contract.select_proposal_get('writer'), proposal_id) + before = len(requests) + with self.assertRaises(BaseRegistryClientError): + client.add_proposal_addition(prior, 'other', 'application/pdf', content, 'refused') + self.assertEqual(len(requests), before) + added = client.add_proposal_addition(prior, 'other', 'text/plain', content, 'addition-one') + self.assertEqual(added.document['submissionVersion'], 1) + self.assertEqual(client.download_proposal_addition(added, addition_id)['body'], content) + upload = requests[before] + self.assertEqual(upload[0], 'POST') + self.assertEqual(upload[1], f'/tenant/v1/proposals/{proposal_id}/additions/other?accessProfile=writer') + self.assertEqual(upload[3], content) + headers = {key.lower(): value for key, value in upload[2].items()} + self.assertEqual(headers['if-match'], '"condition"') + self.assertEqual(headers['idempotency-key'], 'addition-one') + slot = document['additions']['other'] + slot['maximumCount'] = 1 + slot['items'].append({**slot['items'][0], 'id': '00000000-0000-4000-8000-000000000003', 'links': {}}) + slot['links']['add']['availability'] = {'available': False, 'observedRevision': document['revision'], + 'reason': 'limit-reached', 'recovery': 'receipt-only'} + retained = client.get_proposal(contract.select_proposal_get('writer'), proposal_id) + self.assertEqual(len(retained.document['additions']['other']['items']), 2) + self.assertEqual(client.download_proposal_addition(retained, addition_id)['body'], content) + finally: + server.shutdown() + thread.join() + server.server_close() diff --git a/crates/registry-breg-client-py/tests/python/test_asks.py b/crates/registry-breg-client-py/tests/python/test_asks.py new file mode 100644 index 0000000000..7352362cf8 --- /dev/null +++ b/crates/registry-breg-client-py/tests/python/test_asks.py @@ -0,0 +1,82 @@ +"""Ask answers use the canonical Rust command contract.""" +import json +import threading +import unittest +from http.server import BaseHTTPRequestHandler, HTTPServer +from bootstrap import ensure_built + +ensure_built() +from registry_breg_client import BaseRegistryClient, BaseRegistryClientError + + +class AskTests(unittest.TestCase): + def test_answer_uses_the_promoted_ask_etag_and_caller_key(self): + proposal = '00000000-0000-4000-8000-000000000001' + ask = '00000000-0000-4000-8000-000000000007' + digest = 'sha256:' + 'a' * 64 + metadata = {'id': 'asks', 'version': '1', 'revision': digest, 'metadataVersion': '2', 'recordTypes': [], 'operations': [], 'actions': [], + 'proposals': {'actions': [{'actionId': 'correct', 'accessProfile': 'author', 'operations': ['get', 'answer'], 'readableInputs': [], 'readableContextFields': []}], + 'get': {'method': 'GET', 'path': '/v1/proposals/{proposal_id}', 'accessProfiles': ['author']}}} + document = {'id': proposal, 'actionId': 'correct', 'actionRevision': digest, 'submissionVersion': 1, 'revision': 2, 'state': 'submitted', 'effectDigest': digest, 'links': {}, + 'asks': [{'id': ask, 'text': 'Why?', 'wants': [{'kind': 'answer'}], 'askedAt': '2026-11-27T00:00:00Z', 'state': 'open', 'links': { + 'answer': {'method': 'POST', 'path': f'/v1/proposals/{proposal}/asks/{ask}/answer', 'accessProfile': 'author', 'operation': 'answer', 'ifMatch': '"condition"', 'availability': {'available': True, 'observedRevision': 2}}}}]} + requests = [] + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + requests.append(('GET', self.path, dict(self.headers), None)) + self.respond(metadata if '/registry?' in self.path else document) + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers['content-length']))) + requests.append(('POST', self.path, dict(self.headers), body)) + document['revision'] = 3 + document['asks'][0]['state'] = 'answered' + document['asks'][0]['answer'] = {**body, 'additions': [], 'answeredAt': '2026-11-27T01:00:00Z'} + document['asks'][0]['links']['answer']['availability'] = {'available': False, 'observedRevision': 3, 'reason': 'ask-answered', 'recovery': 'receipt-only'} + self.respond(document) + + def respond(self, value): + payload = json.dumps(value).encode() + self.send_response(200) + for key, value in [('content-type', 'application/json'), ('cache-control', 'no-store'), ('vary', 'authorization, accept'), + ('traceparent', '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'), ('content-length', str(len(payload)))]: + self.send_header(key, value) + self.end_headers() + self.wfile.write(payload) + + def log_message(self, *args): + return + + server = HTTPServer(('127.0.0.1', 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + client = BaseRegistryClient(f'http://127.0.0.1:{server.server_port}/tenant/') + self.assertTrue(hasattr(client, 'answer_proposal_ask')) + contract = client.registry_contract('author') + prior = client.get_proposal(contract.select_proposal_get('author'), proposal) + before = len(requests) + with self.assertRaises(BaseRegistryClientError): + client.answer_proposal_ask(prior, ask, {'text': ' '}, 'invalid') + self.assertEqual(len(requests), before) + document['asks'][0]['wants'] = [] + without_wants = client.get_proposal(contract.select_proposal_get('author'), proposal) + before_empty = len(requests) + for body in [{}, {'additions': []}]: + with self.assertRaises(BaseRegistryClientError): + client.answer_proposal_ask(without_wants, ask, body, 'empty') + self.assertEqual(len(requests), before_empty) + document['asks'][0]['wants'] = [{'kind': 'answer'}] + answered = client.answer_proposal_ask(prior, ask, {'text': 'The explanation'}, 'answer-one') + self.assertEqual(answered.document['asks'][0]['answer']['text'], 'The explanation') + wire = requests[-1] + self.assertEqual(wire[1], f'/tenant/v1/proposals/{proposal}/asks/{ask}/answer?accessProfile=author') + headers = {key.lower(): value for key, value in wire[2].items()} + self.assertEqual(headers['if-match'], '"condition"') + self.assertEqual(headers['idempotency-key'], 'answer-one') + self.assertEqual(wire[3], {'text': 'The explanation'}) + finally: + server.shutdown() + thread.join() + server.server_close() diff --git a/crates/registry-breg-client-py/tests/python/test_proposal_results.py b/crates/registry-breg-client-py/tests/python/test_proposal_results.py index 4d671e2144..cdb433c2c8 100644 --- a/crates/registry-breg-client-py/tests/python/test_proposal_results.py +++ b/crates/registry-breg-client-py/tests/python/test_proposal_results.py @@ -41,12 +41,56 @@ def status_document(state): class ProposalResultTests(unittest.TestCase): + def test_submit_attachment_problems_preserve_only_the_slot_location(self): + self.value = document() + self.value['state'] = 'draft' + del self.value['application'] + del self.value['effectDigest'] + self.value['links']['submit'] = {'method': 'POST', 'path': f'/v1/proposals/{ID}/submit', + 'accessProfile': 'reader', 'operation': 'submit', 'ifMatch': '"attachment-condition"'} + draft = self.client.get_proposal(self.binding, ID) + for code, status, detail in [ + ('attachment.required', 422, 'The required attachment slot is empty.'), + ('attachment.verification-pending', 409, 'The attachment is awaiting verification. Refresh the Proposal before submitting.'), + ('attachment.verification-rejected', 422, 'The attachment was rejected by verification. Replace or remove the file before submitting.'), + ]: + with self.subTest(code=code): + attempt = self.client.prepare_proposal(draft, 'submit', {}, f'attachment-{code}') + self.reply_status = status + self.content_type = 'application/problem+json' + self.value = {'type': 'https://id.registrystack.org/problems/registry-breg/' + code.replace('.', '/'), + 'title': 'Conflict' if status == 409 else 'Unprocessable Entity', 'status': status, + 'detail': detail, 'code': code, 'traceId': '4bf92f3577b34da6a3ce929d0e0e4736', + 'fieldPath': '/attachments/support'} + with self.assertRaises(BaseRegistryClientError) as raised: + self.client.execute_proposal(attempt) + error = raised.exception + self.assertEqual((error.kind, error.code, error.status, error.field_path), ('problem', code, status, '/attachments/support')) + self.assertFalse(error.outcome_unknown) + self.assertEqual(self.methods[-1], 'POST') + self.assertTrue(self.requests[-1][0].endswith('/submit?accessProfile=reader')) + + def test_application_refusals_preserve_rebase_and_revise_recovery(self): + for reason, recovery in [('stale-revision', 'rebase'), ('invalid-input', 'revise')]: + with self.subTest(recovery=recovery): + self.value = status_document('blocked') + self.value['applicationStatus'].update(reason='application-refused', recovery=recovery) + self.value['links']['apply'] = { + 'method': 'POST', 'path': f'/v1/proposals/{ID}/apply', + 'accessProfile': 'reader', 'operation': 'apply', 'ifMatch': '"blocked-condition"', + 'availability': {'available': False, 'observedRevision': 8, 'reason': reason, 'recovery': recovery}, + } + observed = self.client.get_proposal(self.binding, ID).document + self.assertEqual(observed['applicationStatus'], self.value['applicationStatus']) + self.assertEqual(observed['links']['apply']['availability'], self.value['links']['apply']['availability']) + def setUp(self): self.value = document() self.reply_status = 200 self.content_type = 'application/json' self.metadata = copy.deepcopy(METADATA) self.requests = [] + self.methods = [] self.download_bytes = None owner = self @@ -64,6 +108,7 @@ def do_DELETE(self): self.respond() def respond(self): + owner.methods.append(self.command) body = self.rfile.read(int(self.headers.get('content-length', '0'))) owner.requests.append((self.path, dict(self.headers), body)) if owner.download_bytes is not None and self.command == 'GET' and '/attachments/' in self.path: diff --git a/crates/registry-breg-client-py/tests/python/test_proposals.py b/crates/registry-breg-client-py/tests/python/test_proposals.py index 4f5f46210d..674e03fe28 100644 --- a/crates/registry-breg-client-py/tests/python/test_proposals.py +++ b/crates/registry-breg-client-py/tests/python/test_proposals.py @@ -28,6 +28,58 @@ class ProposalLookupTests(unittest.TestCase): + def test_status_is_closed_and_application_pending_requires_refresh(self): + document = dict(PROPOSAL) + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + self.send_header('Content-Type', 'application/json') + self.send_header('Cache-Control', 'no-store') + self.send_header('Vary', 'authorization, accept') + self.send_header('traceparent', '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01') + self.end_headers() + self.wfile.write(json.dumps(METADATA if '/registry' in self.path else document).encode()) + + def log_message(self, *_args): + return + + server = HTTPServer(('127.0.0.1', 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + client = BaseRegistryClient(f'http://127.0.0.1:{server.server_port}/') + binding = client.registry_contract('reader').select_proposal_get('reader') + for status, state, turn in [ + ('draft', 'draft', 'party'), ('awaiting-party', 'submitted', 'party'), + ('in-review', 'submitted', 'official'), ('approved', 'submitted', 'official'), + ('processing', 'submitted', 'nobody'), ('applied', 'applied', 'nobody'), + ('rejected', 'rejected', 'nobody'), ('cancelled', 'cancelled', 'nobody'), + ]: + document = dict(PROPOSAL, status=status, state=state, turn=turn, links={'self': PROPOSAL['links']['self']}) + if state == 'submitted': + document['effectDigest'] = REVISION + self.assertEqual(client.get_proposal(binding, ID).document['status'], status) + document = dict(PROPOSAL, state='submitted', status='approved', turn='official', effectDigest=REVISION, links={ + 'self': PROPOSAL['links']['self'], 'revise': { + 'method': 'POST', 'path': f'/v1/proposals/{ID}/revise', 'accessProfile': 'reader', 'operation': 'revise', + 'ifMatch': '"condition"', 'availability': {'available': False, 'observedRevision': 2, + 'reason': 'application-pending', 'recovery': 'refresh'}}}) + self.assertEqual(client.get_proposal(binding, ID).document['links']['revise']['availability']['reason'], 'application-pending') + document['links']['revise']['availability']['recovery'] = 'retry' + with self.assertRaises(BaseRegistryClientError): + client.get_proposal(binding, ID) + for status in ['unknown', None, False, 1]: + document = dict(PROPOSAL, status=status) + with self.assertRaises(BaseRegistryClientError): + client.get_proposal(binding, ID) + document = PROPOSAL + self.assertNotIn('status', client.get_proposal(binding, ID).document) + finally: + server.shutdown() + thread.join() + server.server_close() + def test_metadata_inventory_summaries_and_version_refusals(self): fixture = Path(__file__).resolve().parents[3] / 'registry-breg-client/tests/fixtures/attachments.json' document = json.loads(fixture.read_text())['metadata'] diff --git a/crates/registry-breg-client-py/tests/python/test_review_documents.py b/crates/registry-breg-client-py/tests/python/test_review_documents.py index 11ccfb8cc3..37369b52c7 100644 --- a/crates/registry-breg-client-py/tests/python/test_review_documents.py +++ b/crates/registry-breg-client-py/tests/python/test_review_documents.py @@ -77,12 +77,14 @@ def do_GET(self): binding = contract.select_proposal_review_context('reviewer', 'correct') self.assertIsInstance(binding, BRegProposalReviewBinding) observed = client.read_proposal_review_by_id(binding, identifier)['value'] + self.assertEqual(parse_qs(urlsplit(requests[-1]).query)['include'], ['answers']) batch = client.read_proposal_review_context_batch(binding, [identifier, concealed_id]) self.assertEqual(batch['value'], [observed, None]) batch_url = urlsplit(requests[-1]) self.assertEqual(batch_url.path, '/tenant/v1/proposals/review-context') self.assertEqual(parse_qs(batch_url.query)['ids'], [f'{identifier},{concealed_id}']) self.assertEqual(parse_qs(batch_url.query)['accessProfile'], ['reviewer']) + self.assertNotIn('include', parse_qs(batch_url.query)) before_batch_refusals = len(requests) for ids in [[], [identifier, identifier]]: with self.assertRaises(BaseRegistryClientError): diff --git a/crates/registry-breg-client/src/client.rs b/crates/registry-breg-client/src/client.rs index 1fe9cc7d2e..c11bd3046e 100644 --- a/crates/registry-breg-client/src/client.rs +++ b/crates/registry-breg-client/src/client.rs @@ -1382,6 +1382,7 @@ impl BaseRegistryClient { let url = self.url_with_query(&segments, &pairs)?; let method = match link.method() { "GET" => Method::GET, + "POST" => Method::POST, "PATCH" => Method::PATCH, "DELETE" => Method::DELETE, _ => { @@ -1450,14 +1451,32 @@ impl BaseRegistryClient { &self, link: &BRegProposalLink, ) -> Result, BaseRegistryClientError> { - if link.method() != "GET" || link.operation() != "get-review-status" { + self.proposal_review_include_exchange(link, "get-review-status", "progress") + .await + } + + pub(crate) async fn proposal_review_answers_exchange( + &self, + link: &BRegProposalLink, + ) -> Result, BaseRegistryClientError> { + self.proposal_review_include_exchange(link, "get-review-context", "answers") + .await + } + + async fn proposal_review_include_exchange( + &self, + link: &BRegProposalLink, + operation: &str, + include: &str, + ) -> Result, BaseRegistryClientError> { + if link.method() != "GET" || link.operation() != operation { return Err(BaseRegistryClientError::invalid_request( - "the selected Base Registry Engine Proposal review status link is invalid", + "the selected Base Registry Engine Proposal review link is invalid", )); } let segments = fixed_operation_segments(link.path())?; let mut pairs = access_profile_query(Some(link.access_profile()))?; - pairs.push(("include".to_owned(), "progress".to_owned())); + pairs.push(("include".to_owned(), include.to_owned())); let url = self.url_with_query(&segments, &pairs)?; let builder = self .authorize( @@ -2883,6 +2902,12 @@ async fn breg_problem(response: Response, transport: &Transport) -> BaseRegistry || extensions.reason_code.is_some() != (code == BRegProblemCode::StatisticalDatasetVersionWithdrawn) || extensions.guard_reason.is_some() && code != BRegProblemCode::ActionGuardFailed + || matches!( + code, + BRegProblemCode::AttachmentRequired + | BRegProblemCode::AttachmentVerificationPending + | BRegProblemCode::AttachmentVerificationRejected + ) && extensions.field_path.is_none() || code == BRegProblemCode::ActionRefused && !crate::error::bounded_refusal_label(&document.detail) || (code == BRegProblemCode::StatisticalDatasetReleaseRefused @@ -2950,6 +2975,7 @@ fn valid_statistics_reason_code(value: &str) -> bool { /// The closed forms a Base Registry Engine problem location takes. #[derive(Clone, Copy, PartialEq, Eq)] enum BRegProblemPath { + AttachmentSlot, EvidenceAlias, ActionInputField, ActionRequest, @@ -2969,6 +2995,12 @@ enum BRegProblemPath { impl BRegProblemPath { fn permits(self, code: BRegProblemCode) -> bool { match self { + Self::AttachmentSlot => matches!( + code, + BRegProblemCode::AttachmentRequired + | BRegProblemCode::AttachmentVerificationPending + | BRegProblemCode::AttachmentVerificationRejected + ), Self::EvidenceAlias => code == BRegProblemCode::ActionEvidenceFailed, Self::ActionInputField => matches!( code, @@ -3144,6 +3176,19 @@ fn parse_constraint_violation( } fn breg_problem_path(path: &str) -> Option { + if path.strip_prefix("/attachments/").is_some_and(|slot| { + !slot.is_empty() + && slot.len() <= 64 + && slot + .bytes() + .next() + .is_some_and(|byte| byte.is_ascii_lowercase()) + && slot.bytes().all(|byte| { + byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'_') + }) + }) { + return Some(BRegProblemPath::AttachmentSlot); + } if valid_evidence_problem_path(path) { return Some(BRegProblemPath::EvidenceAlias); } @@ -3282,7 +3327,10 @@ fn valid_action_input_problem_path(path: &str) -> bool { } fn valid_action_request_problem_path(path: &str) -> bool { - if matches!(path, "" | "/input" | "/preconditions") { + if matches!( + path, + "" | "/input" | "/preconditions" | "/text" | "/additions" + ) { return true; } let Some(remainder) = path.strip_prefix("/preconditions/") else { @@ -3324,3 +3372,15 @@ fn problem_failure(status: StatusCode, trace_id: TraceId) -> BaseRegistryClientE Some(trace_id), ) } + +#[cfg(test)] +mod ask_field_paths { + #[test] + fn answer_problem_locations_name_only_the_fixed_body_members() { + assert!(super::valid_action_request_problem_path("/text")); + assert!(super::valid_action_request_problem_path("/additions")); + assert!(!super::valid_action_request_problem_path( + "/additions/private-file" + )); + } +} diff --git a/crates/registry-breg-client/src/error.rs b/crates/registry-breg-client/src/error.rs index d2a34852d7..c97f0959f1 100644 --- a/crates/registry-breg-client/src/error.rs +++ b/crates/registry-breg-client/src/error.rs @@ -145,6 +145,10 @@ pub enum BRegProblemCode { AttachmentContentType, AttachmentDigestMismatch, AttachmentSlotWriteOnce, + AttachmentLimitReached, + AttachmentRequired, + AttachmentVerificationPending, + AttachmentVerificationRejected, AttachmentTooLarge, AuthenticationRefused, ExternalViewIncomplete, @@ -182,7 +186,7 @@ pub enum BRegProblemCode { } impl BRegProblemCode { - pub const ALL: [Self; 41] = [ + pub const ALL: [Self; 45] = [ Self::ActionEvidenceFailed, Self::ActionGuardFailed, Self::ActionHandlerFailed, @@ -190,6 +194,10 @@ impl BRegProblemCode { Self::AttachmentContentType, Self::AttachmentDigestMismatch, Self::AttachmentSlotWriteOnce, + Self::AttachmentLimitReached, + Self::AttachmentRequired, + Self::AttachmentVerificationPending, + Self::AttachmentVerificationRejected, Self::AttachmentTooLarge, Self::AuthenticationRefused, Self::ExternalViewIncomplete, @@ -236,6 +244,10 @@ impl BRegProblemCode { Self::AttachmentContentType => "attachment.content-type", Self::AttachmentDigestMismatch => "attachment.digest-mismatch", Self::AttachmentSlotWriteOnce => "attachment.slot-write-once", + Self::AttachmentLimitReached => "attachment.limit-reached", + Self::AttachmentRequired => "attachment.required", + Self::AttachmentVerificationPending => "attachment.verification-pending", + Self::AttachmentVerificationRejected => "attachment.verification-rejected", Self::AttachmentTooLarge => "attachment.too-large", Self::AuthenticationRefused => "authentication.refused", Self::ExternalViewIncomplete => "external_view.incomplete", @@ -287,6 +299,8 @@ impl BRegProblemCode { Self::LookupUnresolved | Self::ResourceNotFound => 404, Self::IngestionProfileMismatch | Self::WriteOutsideBoundary => 403, Self::AttachmentSlotWriteOnce + | Self::AttachmentLimitReached + | Self::AttachmentVerificationPending | Self::IdempotencyConflict | Self::IngestionChunkMismatch | Self::IngestionRunBlocked @@ -305,6 +319,8 @@ impl BRegProblemCode { Self::AttachmentContentType | Self::UnsupportedMediaType => 415, Self::ActionRefused | Self::AttachmentDigestMismatch + | Self::AttachmentRequired + | Self::AttachmentVerificationRejected | Self::StatisticalDatasetReleaseRefused => 422, Self::PreconditionRequired => 428, Self::StatisticalDatasetDomainViolation => 500, @@ -370,6 +386,10 @@ impl BRegProblemCode { "The record attachment slot already holds a file and is write-once." } Self::AttachmentTooLarge => "The file is larger than the attachment slot accepts.", + Self::AttachmentLimitReached => "The supporting document slot has reached its file limit.", + Self::AttachmentRequired => "The required attachment slot is empty.", + Self::AttachmentVerificationPending => "The attachment is awaiting verification. Refresh the Proposal before submitting.", + Self::AttachmentVerificationRejected => "The attachment was rejected by verification. Replace or remove the file before submitting.", Self::AuthenticationRefused => "The bearer token or delivery signature was not accepted.", Self::ExternalViewIncomplete => { "The external view's indexed coverage is incomplete for this request." diff --git a/crates/registry-breg-client/src/proposal.rs b/crates/registry-breg-client/src/proposal.rs index d05e0d98c3..08e2e41865 100644 --- a/crates/registry-breg-client/src/proposal.rs +++ b/crates/registry-breg-client/src/proposal.rs @@ -9,7 +9,19 @@ use std::fmt; use time::{format_description::well_known::Rfc3339, OffsetDateTime}; use zeroize::Zeroizing; +mod additions; +mod asks; +pub use asks::{ + BRegProposalAnswerRequest, BRegProposalAsk, BRegProposalAskAnswer, BRegProposalAskState, + BRegProposalAskWant, +}; +mod review_asks; mod review_document; +pub use additions::{BRegProposalAddition, BRegProposalAdditionSlot}; +pub use review_asks::{ + BRegProposalReviewAnswer, BRegProposalReviewAnswerDocument, BRegProposalReviewAnswerDownload, + BRegProposalReviewAsk, +}; // Mirrors MAX_PROPOSAL_SNAPSHOT_BYTES in registry-breg::proposal_store. // The client does not depend on the runtime. @@ -39,6 +51,13 @@ pub enum BRegAvailabilityReason { DependencyOutage, InvalidInput, AlreadyApplied, + LimitReached, + ApplicationPending, + AttachmentRequired, + AttachmentPending, + AskAnswered, + AskClosed, + AskDuePassed, } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -73,6 +92,27 @@ pub enum BRegProposalTurn { Nobody, } +/// The server's current display status, paired with its turn rule. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum BRegProposalStatus { + Draft, + AwaitingParty, + InReview, + Approved, + Processing, + Applied, + Rejected, + Cancelled, +} + +fn present_proposal_status<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + BRegProposalStatus::deserialize(deserializer).map(Some) +} + #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] @@ -167,6 +207,7 @@ pub enum BRegProposalApplicationReason { #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum BRegApplicationRecoveryHint { + Revise, Retry, Rebase, CorrectInput, @@ -365,6 +406,8 @@ pub struct BRegProposalReviewContext { pub contract: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub fields: Option>, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub asks: Vec, } /// Exact local interface exported by the governed producer, independent of a review policy pin. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -571,12 +614,22 @@ pub struct BRegProposal { links: BTreeMap, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] attachments: BTreeMap, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + additions: BTreeMap, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + asks: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] application: Option, #[serde(default, skip_serializing_if = "Option::is_none")] application_status: Option, #[serde(default, skip_serializing_if = "Option::is_none")] turn: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_proposal_status" + )] + status: Option, #[serde(default, skip_serializing_if = "Option::is_none")] decision: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -643,6 +696,32 @@ impl BRegProposal { { return Err(refusal()); } + if let Some(status) = self.status { + use BRegProposalStatus as Status; + let valid_state = match status { + Status::Draft => self.state == BRegProposalState::Draft, + Status::Applied => self.state == BRegProposalState::Applied, + Status::Rejected => self.state == BRegProposalState::Rejected, + Status::Cancelled => self.state == BRegProposalState::Cancelled, + Status::AwaitingParty + | Status::InReview + | Status::Approved + | Status::Processing => self.state == BRegProposalState::Submitted, + }; + let valid_turn = self.turn.is_none_or(|turn| match status { + Status::Draft | Status::AwaitingParty => turn == BRegProposalTurn::Party, + Status::InReview => turn == BRegProposalTurn::Official, + Status::Approved | Status::Processing => { + matches!(turn, BRegProposalTurn::Official | BRegProposalTurn::Nobody) + } + Status::Applied | Status::Rejected | Status::Cancelled => { + turn == BRegProposalTurn::Nobody + } + }); + if !valid_state || !valid_turn { + return Err(refusal()); + } + } if self.application_status.as_ref().is_some_and(|status| { self.effect_digest.is_none() || self.submission_version == 0 @@ -802,6 +881,8 @@ impl BRegProposal { return Err(refusal()); } } + self.validate_additions()?; + self.validate_asks()?; Ok(()) } fn discloses_application_actor(&self) -> bool { @@ -840,12 +921,18 @@ impl BRegProposal { pub const fn turn(&self) -> Option { self.turn } - /// The current submission's review decision, served on reads only. + pub const fn status(&self) -> Option { + self.status + } + /// The current submission's review decision. Reads serve it, and a + /// command response does when the caller's profile holds Get on the + /// Proposal. pub fn decision(&self) -> Option<&BRegProposalDecision> { self.decision.as_ref() } /// The review authority's allowlisted reason for refusing the current - /// submission, served on reads only. + /// submission, served on reads while the Proposal is submitted. No command + /// leaves a refused hand-off submitted, so command responses carry none. pub fn handoff_refusal(&self) -> Option { self.handoff_refusal.map(|member| member.code) } @@ -864,6 +951,9 @@ impl BRegProposal { pub fn link(&self, operation: &str) -> Option<&BRegProposalLink> { self.links.get(operation) } + pub fn asks(&self) -> &[BRegProposalAsk] { + &self.asks + } pub fn attachment(&self, id: &str) -> Option<&BRegProposalAttachment> { self.attachments.get(id) } @@ -884,6 +974,8 @@ impl BRegProposal { .values() .flat_map(|slot| slot.links.values()), ) + .chain(self.addition_links()) + .chain(self.asks.iter().flat_map(|ask| ask.links.values())) .any(|link| link.access_profile != profile) { return Err(refusal()); @@ -1250,6 +1342,7 @@ impl BaseRegistryClient { || document.proposal.authority.is_none() || fields.as_ref() != Some(&requested) || !valid_review_document(&document.proposal, true, false) + || !document.proposal.context.asks.is_empty() { return Err(refusal()); } @@ -1265,6 +1358,30 @@ impl BaseRegistryClient { &self, binding: &BRegProposalReviewBinding, id: &str, + ) -> Result, BaseRegistryClientError> { + self.read_proposal_review_by_id_with_answers( + binding, + id, + binding.operation == "get-review-context", + ) + .await + } + + /// Read governed context for admission without requesting live applicant answers. + pub async fn read_proposal_review_by_id_without_answers( + &self, + binding: &BRegProposalReviewBinding, + id: &str, + ) -> Result, BaseRegistryClientError> { + self.read_proposal_review_by_id_with_answers(binding, id, false) + .await + } + + async fn read_proposal_review_by_id_with_answers( + &self, + binding: &BRegProposalReviewBinding, + id: &str, + include_answers: bool, ) -> Result, BaseRegistryClientError> { if binding.source != self.source_binding() || !canonical_proposal_id(id) { return Err(refusal()); @@ -1277,15 +1394,21 @@ impl BaseRegistryClient { if_match: None, availability: None, }; - let response = self.proposal_exchange(&link, None, None).await?; + let response = if include_answers { + self.proposal_review_answers_exchange(&link).await? + } else { + self.proposal_exchange(&link, None, None).await? + }; let value = crate::strict_json::from_slice(response.value.as_bytes()).map_err(|_| refusal())?; let document: BRegProposalReviewDocument = serde_json::from_value(value).map_err(|_| refusal())?; let is_context = binding.operation == "get-review-context"; if document.id != id + || (!include_answers && !document.context.asks.is_empty()) || document.action_id != binding.action || !valid_review_document(&document, is_context, false) + || !review_asks::profiles(&document, &binding.profile) { return Err(refusal()); } @@ -1350,7 +1473,8 @@ impl BaseRegistryClient { if id == *expected && context.id == id && context.action_id == binding.action - && valid_review_document(&context, true, false) => + && valid_review_document(&context, true, false) + && review_asks::profiles(&context, &binding.profile) => { values.push(Some(*context)) } @@ -1433,6 +1557,8 @@ impl BaseRegistryClient { return Err(refusal()); } self.proposal_review_progress_exchange(link).await? + } else if operation == "reviewContext" { + self.proposal_review_answers_exchange(link).await? } else { self.proposal_exchange(link, None, None).await? }; @@ -1450,6 +1576,7 @@ impl BaseRegistryClient { .as_deref() .is_some_and(|digest| digest != document.effect_digest) || !valid_review_document(&document, operation == "reviewContext", include_progress) + || !review_asks::profiles(&document, &link.access_profile) { return Err(refusal()); } @@ -1704,6 +1831,7 @@ impl BaseRegistryClient { .values() .flat_map(|slot| slot.links.values()), ) + .chain(item.addition_links()) .any(|link| link.access_profile != collection.profile) { return Err(refusal()); @@ -2034,6 +2162,7 @@ fn valid_review_document( .as_ref() .is_none_or(|policy| policy.check().is_ok()) && valid_review_projection(document, is_context, include_progress) + && review_asks::valid(document) } fn valid_review_projection( @@ -2050,6 +2179,7 @@ fn valid_review_projection( && document.progress_code.is_none() } else { document.context.fields.is_none() + && document.context.asks.is_empty() && document .request_id .as_deref() @@ -2104,12 +2234,17 @@ fn valid_application_shape( Applied, Applying, AwaitingReview, Blocked, Cancelled, Pending, Rejected, }; let open = matches!(state, AwaitingReview | Pending | Applying | Blocked); - let paired = recovery - == reason.map(|reason| match reason { - DependencyOutage | LeaseExpired => BRegApplicationRecoveryHint::Retry, - PackageChanged => BRegApplicationRecoveryHint::Rebase, - _ => BRegApplicationRecoveryHint::CorrectInput, - }); + let paired = (reason == Some(BRegProposalApplicationReason::ApplicationRefused) + && matches!( + recovery, + Some(BRegApplicationRecoveryHint::Rebase | BRegApplicationRecoveryHint::Revise) + )) + || recovery + == reason.map(|reason| match reason { + DependencyOutage | LeaseExpired => BRegApplicationRecoveryHint::Retry, + PackageChanged => BRegApplicationRecoveryHint::Rebase, + _ => BRegApplicationRecoveryHint::CorrectInput, + }); let reason = reason.is_some(); paired && (state != Blocked || reason) @@ -2239,28 +2374,51 @@ fn valid_availability( (true, reason, recovery) => reason.is_none() && recovery.is_none(), (false, Some(reason), Some(recovery)) => matches!( (reason, recovery), - (Reason::PendingReview, Recovery::Refresh) - | ( - Reason::ReviewRejected, - Recovery::ReceiptOnly | Recovery::Revise - ) - | ( - Reason::ReviewChangesRequested | Reason::ReviewEnded, - Recovery::Revise - ) + ( + Reason::PendingReview | Reason::ApplicationPending, + Recovery::Refresh + ) | ( + Reason::ReviewRejected, + Recovery::ReceiptOnly | Recovery::Revise + ) | ( + Reason::ReviewChangesRequested | Reason::ReviewEnded, + Recovery::Revise + ) | ( + Reason::StaleRevision | Reason::AlreadyApplied, + Recovery::ReceiptOnly + ) | ( + Reason::LimitReached + | Reason::AskAnswered + | Reason::AskClosed + | Reason::AskDuePassed, + Recovery::ReceiptOnly + ) | (Reason::PackageChanged, Recovery::Rebase) + | (Reason::DependencyOutage, Recovery::Retry) + | (Reason::StaleRevision, Recovery::Rebase) | ( - Reason::StaleRevision | Reason::AlreadyApplied, - Recovery::ReceiptOnly + Reason::InvalidInput, + Recovery::Revise | Recovery::CorrectInput ) - | (Reason::PackageChanged, Recovery::Rebase) - | (Reason::DependencyOutage, Recovery::Retry) - | (Reason::InvalidInput, Recovery::CorrectInput) + | (Reason::AttachmentRequired, Recovery::CorrectInput) + | (Reason::AttachmentPending, Recovery::Refresh) ), (false, _, _) => false, } && (availability.available || match (availability.reason, availability.recovery) { (Some(Reason::AlreadyApplied), _) => state == State::Applied, + ( + Some( + Reason::ApplicationPending + | Reason::AskAnswered + | Reason::AskClosed + | Reason::AskDuePassed, + ), + _, + ) => state == State::Submitted, + (Some(Reason::AttachmentRequired | Reason::AttachmentPending), _) => { + state == State::Draft + } (Some(Reason::ReviewRejected), Some(Recovery::ReceiptOnly)) => { state == State::Rejected } @@ -2413,9 +2571,26 @@ fn unavailable(availability: &BRegAvailability) -> BaseRegistryClientError { (Some(Reason::DependencyOutage), Some(Recovery::Retry)) => { named!("dependency-outage", "retry") } + (Some(Reason::StaleRevision), Some(Recovery::Rebase)) => named!("stale-revision", "rebase"), + (Some(Reason::InvalidInput), Some(Recovery::Revise)) => named!("invalid-input", "revise"), (Some(Reason::InvalidInput), Some(Recovery::CorrectInput)) => { named!("invalid-input", "correct-input") } + (Some(Reason::AttachmentRequired), Some(Recovery::CorrectInput)) => { + named!("attachment-required", "correct-input") + } + (Some(Reason::AskAnswered), Some(Recovery::ReceiptOnly)) => { + named!("ask-answered", "receipt-only") + } + (Some(Reason::AskClosed), Some(Recovery::ReceiptOnly)) => { + named!("ask-closed", "receipt-only") + } + (Some(Reason::AskDuePassed), Some(Recovery::ReceiptOnly)) => { + named!("ask-due-passed", "receipt-only") + } + (Some(Reason::AttachmentPending), Some(Recovery::Refresh)) => { + named!("attachment-pending", "refresh") + } _ => return refusal(), }) } @@ -4067,6 +4242,23 @@ mod tests { fn client(origin: &str) -> BaseRegistryClient { BaseRegistryClient::new(BaseRegistryClientConfig::new(origin.parse().unwrap())).unwrap() } + #[test] + fn asks_are_known_proposal_members_and_terminal_reasons_are_closed() { + let mut value = document(); + value["asks"] = json!([{"id":"00000000-0000-4000-8000-000000000007","text":"Why?","wants":[{"kind":"answer"}],"askedAt":"2026-11-27T00:00:00Z","state":"open","links":{}}]); + assert!(BRegProposal::from_slice(&serde_json::to_vec(&value).unwrap()).is_ok()); + for reason in ["ask-answered", "ask-closed", "ask-due-passed"] { + let available: Result = serde_json::from_value( + json!({"available":false,"observedRevision":2,"reason":reason,"recovery":"receipt-only"}), + ); + assert!(available.is_ok(), "known ask reason {reason}"); + assert!(valid_availability( + &available.unwrap(), + 2, + BRegProposalState::Submitted + )); + } + } fn document() -> Value { json!({"id":ID,"actionId":"correct-address","actionRevision":REVISION, "submissionVersion":1,"revision":2,"state":"submitted","effectDigest":REVISION,"links":{ diff --git a/crates/registry-breg-client/src/proposal/additions.rs b/crates/registry-breg-client/src/proposal/additions.rs new file mode 100644 index 0000000000..860b018c2f --- /dev/null +++ b/crates/registry-breg-client/src/proposal/additions.rs @@ -0,0 +1,295 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; + +impl BaseRegistryClient { + /// Add supporting bytes to the exact submission named by a promoted slot. + pub async fn add_proposal_addition( + &self, + proposal: &BRegProposal, + slot: &str, + content_type: &str, + bytes: &[u8], + key: &BRegIdempotencyKey, + ) -> Result, BaseRegistryClientError> { + if proposal.source.as_deref() != Some(self.source_binding().as_str()) { + return Err(refusal()); + } + let slot = proposal.additions.get(slot).ok_or_else(refusal)?; + let link = slot + .links + .get("add") + .filter(|link| link.availability.as_ref().is_none_or(|a| a.available)) + .ok_or_else(refusal)?; + if proposal.state != BRegProposalState::Submitted + || bytes.is_empty() + || bytes.len() as u64 > slot.maximum_bytes + || slot.items.len() >= slot.maximum_count as usize + || !slot.content_types.iter().any(|media| media == content_type) + { + return Err(refusal()); + } + let response = self + .proposal_attachment_exchange( + link, + Some(bytes.to_vec()), + Some(content_type), + Some(key), + slot.maximum_bytes, + None, + ) + .await?; + let invalid_receipt = || { + BaseRegistryClientError::protocol( + 200, + BRegProtocolFailure::Body, + Some(response.metadata.trace_id().clone()), + ) + }; + let current = + BRegProposal::from_slice(response.value.as_bytes()).map_err(|_| invalid_receipt())?; + use sha2::{Digest, Sha256}; + let hash = Sha256::digest(bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + let current_slot = current + .additions + .get(&slot.id) + .ok_or_else(invalid_receipt)?; + let valid_items = current_slot.items.is_empty() && slot.items.is_empty() + || current_slot.items.len() == slot.items.len() + 1 + && slot.items.iter().all(|prior| { + current_slot.items.iter().any(|item| { + item.id == prior.id + && item.sha256 == prior.sha256 + && item.byte_size == prior.byte_size + && item.content_type == prior.content_type + }) + }) + && current_slot.items.iter().any(|item| { + !slot.items.iter().any(|prior| prior.id == item.id) + && item.sha256 == hash + && item.byte_size == bytes.len() as u64 + && item.content_type == content_type + }); + if current.discloses_application_actor() + || current.id != proposal.id + || current.action_id != proposal.action_id + || current.action_revision != proposal.action_revision + || current.state != BRegProposalState::Submitted + || current.submission_version != proposal.submission_version + || current.effect_digest != proposal.effect_digest + || current.revision <= proposal.revision + || !valid_items + { + return Err(invalid_receipt()); + } + Ok(BRegComplete { + value: current + .bind_profile(self.source_binding(), &link.access_profile) + .map_err(|_| invalid_receipt())?, + metadata: response.metadata, + }) + } + + pub async fn download_proposal_addition( + &self, + proposal: &BRegProposal, + addition: &str, + ) -> Result, BaseRegistryClientError> { + if proposal.source.as_deref() != Some(self.source_binding().as_str()) { + return Err(refusal()); + } + let item = proposal + .additions + .values() + .flat_map(|slot| &slot.items) + .find(|item| item.id == addition) + .ok_or_else(refusal)?; + let link = item + .links + .get("download") + .filter(|link| link.availability.as_ref().is_none_or(|a| a.available)) + .ok_or_else(refusal)?; + let response = self + .proposal_attachment_exchange(link, None, None, None, item.byte_size, None) + .await?; + crate::attachment::verify_download( + response, + &item.content_type, + item.byte_size, + &item.sha256, + ) + } +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalAdditionSlot { + id: String, + maximum_bytes: u64, + maximum_count: u32, + content_types: Vec, + classification: String, + items: Vec, + links: BTreeMap, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalAddition { + id: String, + submission_version: u32, + sha256: String, + byte_size: u64, + content_type: String, + added_at: String, + verification_status: String, + links: BTreeMap, +} + +impl BRegProposalAdditionSlot { + pub fn id(&self) -> &str { + &self.id + } + pub fn maximum_bytes(&self) -> u64 { + self.maximum_bytes + } + pub fn maximum_count(&self) -> u32 { + self.maximum_count + } + pub fn content_types(&self) -> &[String] { + &self.content_types + } + pub fn items(&self) -> &[BRegProposalAddition] { + &self.items + } + pub fn link(&self, operation: &str) -> Option<&BRegProposalLink> { + self.links.get(operation) + } +} +impl BRegProposalAddition { + pub fn id(&self) -> &str { + &self.id + } + pub fn submission_version(&self) -> u32 { + self.submission_version + } + pub fn sha256(&self) -> &str { + &self.sha256 + } + pub fn byte_size(&self) -> u64 { + self.byte_size + } + pub fn content_type(&self) -> &str { + &self.content_type + } + pub fn added_at(&self) -> &str { + &self.added_at + } + pub fn link(&self, operation: &str) -> Option<&BRegProposalLink> { + self.links.get(operation) + } +} + +impl BRegProposal { + pub fn addition_slot(&self, slot: &str) -> Option<&BRegProposalAdditionSlot> { + self.additions.get(slot) + } + pub(super) fn addition_links(&self) -> impl Iterator { + self.additions.values().flat_map(|slot| { + slot.links + .values() + .chain(slot.items.iter().flat_map(|item| item.links.values())) + }) + } + pub(super) fn validate_additions(&self) -> Result<(), BaseRegistryClientError> { + if self.additions.len() > 1 { + return Err(refusal()); + } + for (id, slot) in &self.additions { + if id != &slot.id + || !identifier(id) + || !(1..=MAX_BREG_ATTACHMENT_BYTES).contains(&slot.maximum_bytes) + || !(1..=32).contains(&slot.maximum_count) + || slot.items.len() > 32 + || slot.content_types.is_empty() + || slot.content_types.len() > MAX_BREG_ATTACHMENT_CONTENT_TYPES + || slot + .content_types + .iter() + .any(|media| !crate::attachment::valid_attachment_content_type(media)) + || slot + .content_types + .iter() + .collect::>() + .len() + != slot.content_types.len() + || !matches!( + slot.classification.as_str(), + "public" | "internal" | "restricted" + ) + { + return Err(refusal()); + } + for (name, link) in &slot.links { + if name != "add" + || link.operation != "add" + || link.method != "POST" + || link.path != format!("/v1/proposals/{}/additions/{id}", self.id) + || !identifier(&link.access_profile) + || !valid_condition(link.if_match.as_deref()) + || link + .availability + .as_ref() + .is_some_and(|a| !valid_availability(a, self.revision, self.state)) + { + return Err(refusal()); + } + } + let mut ids = std::collections::BTreeSet::new(); + for item in &slot.items { + if !canonical_proposal_id(&item.id) + || !ids.insert(&item.id) + || item.submission_version != self.submission_version + || !digest(&format!("sha256:{}", item.sha256)) + || !(1..=MAX_BREG_ATTACHMENT_BYTES).contains(&item.byte_size) + || !crate::attachment::valid_attachment_content_type(&item.content_type) + || proposal_instant(&item.added_at).is_none() + || !matches!( + item.verification_status.as_str(), + "notRequired" | "pending" | "approved" | "rejected" + ) + { + return Err(refusal()); + } + for (name, link) in &item.links { + if name != "download" + || link.operation != "download" + || link.method != "GET" + || link.path + != format!( + "/v1/proposals/{}/additions/{}?submissionVersion={}", + self.id, item.id, self.submission_version + ) + || !identifier(&link.access_profile) + || link.if_match.is_some() + || !matches!( + item.verification_status.as_str(), + "notRequired" | "approved" + ) + || link + .availability + .as_ref() + .is_some_and(|a| !valid_availability(a, self.revision, self.state)) + { + return Err(refusal()); + } + } + } + } + Ok(()) + } +} diff --git a/crates/registry-breg-client/src/proposal/asks.rs b/crates/registry-breg-client/src/proposal/asks.rs new file mode 100644 index 0000000000..635904a129 --- /dev/null +++ b/crates/registry-breg-client/src/proposal/asks.rs @@ -0,0 +1,235 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Applicant-visible asks and explicitly selected answer commands. +use super::*; +pub use registry_review_protocol::{ + ReviewAskState as BRegProposalAskState, ReviewAskWant as BRegProposalAskWant, +}; + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalAsk { + pub id: String, + pub text: String, + pub wants: Vec, + pub asked_at: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub due_at: Option, + pub state: BRegProposalAskState, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub answer: Option, + pub links: BTreeMap, +} +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalAskAnswer { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, + pub additions: Vec, + pub answered_at: String, +} +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalAnswerRequest { + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_text" + )] + pub text: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub additions: Vec, +} +impl fmt::Debug for BRegProposalAsk { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("BRegProposalAsk()") + } +} +impl fmt::Debug for BRegProposalAskAnswer { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("BRegProposalAskAnswer()") + } +} +impl fmt::Debug for BRegProposalAnswerRequest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("BRegProposalAnswerRequest()") + } +} + +fn valid_answer(text: Option<&str>, additions: &[String], wants: &[BRegProposalAskWant]) -> bool { + (text.is_some() || !additions.is_empty()) + && text.is_none_or(|text| { + !text.trim().is_empty() && text.len() <= 2000 && !text.contains('\0') + }) + && (text.is_some() || !wants.contains(&BRegProposalAskWant::Answer {})) + && additions.len() <= 32 + && additions.iter().all(|id| canonical_proposal_id(id)) + && additions + .iter() + .collect::>() + .len() + == additions.len() + && (!additions.is_empty() || !wants.contains(&BRegProposalAskWant::Document {})) +} + +impl BRegProposal { + pub(super) fn validate_asks(&self) -> Result<(), BaseRegistryClientError> { + if self.asks.len() > 50 { + return Err(refusal()); + } + let mut ids = std::collections::BTreeSet::new(); + for ask in &self.asks { + let asked = proposal_instant(&ask.asked_at).ok_or_else(refusal)?; + if !canonical_proposal_id(&ask.id) + || !ids.insert(&ask.id) + || registry_review_protocol::check_public_reason(&ask.text).is_err() + || ask.wants.len() > 8 + || ask + .wants + .iter() + .enumerate() + .any(|(i, w)| ask.wants[..i].contains(w)) + || ask + .due_at + .as_ref() + .is_some_and(|due| proposal_instant(due).is_none_or(|due| due <= asked)) + { + return Err(refusal()); + } + if let Some(answer) = &ask.answer { + let at = proposal_instant(&answer.answered_at).ok_or_else(refusal)?; + if ask.state != BRegProposalAskState::Answered + || at < asked + || !at.nanosecond().is_multiple_of(1000) + || !valid_answer(answer.text.as_deref(), &answer.additions, &ask.wants) + { + return Err(refusal()); + } + } + for (name, link) in &ask.links { + validate_link(link)?; + if name != "answer" + || link.method != "POST" + || link.operation != "answer" + || link.path != format!("/v1/proposals/{}/asks/{}/answer", self.id, ask.id) + || link + .availability + .as_ref() + .is_none_or(|a| !valid_availability(a, self.revision, self.state)) + { + return Err(refusal()); + } + } + } + Ok(()) + } +} + +fn present_text<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + String::deserialize(deserializer).map(Some) +} + +impl BaseRegistryClient { + /// Answer the explicitly selected ask using its promoted, origin-bound link. + /// The caller retains the same Proposal and key when resending an unknown outcome. + pub async fn answer_proposal_ask( + &self, + proposal: &BRegProposal, + ask_id: &str, + body: &BRegProposalAnswerRequest, + key: &BRegIdempotencyKey, + ) -> Result, BaseRegistryClientError> { + if proposal.source.as_deref() != Some(self.source_binding().as_str()) + || proposal.state != BRegProposalState::Submitted + { + return Err(refusal()); + } + let ask = proposal + .asks + .iter() + .find(|ask| ask.id == ask_id) + .ok_or_else(refusal)?; + let link = ask.links.get("answer").ok_or_else(refusal)?; + if let Some(availability) = link + .availability + .as_ref() + .filter(|availability| !availability.available) + { + return Err(unavailable(availability)); + } + if ask.state != BRegProposalAskState::Open + || ask.answer.is_some() + || !valid_answer(body.text.as_deref(), &body.additions, &ask.wants) + { + return Err(refusal()); + } + let response = self + .proposal_exchange( + link, + Some(serde_json::to_vec(body).map_err(|_| refusal())?), + Some(key), + ) + .await?; + let invalid = || { + BaseRegistryClientError::protocol( + 200, + BRegProtocolFailure::Body, + Some(response.metadata.trace_id().clone()), + ) + }; + let current = BRegProposal::from_slice(response.value.as_bytes()).map_err(|_| invalid())?; + let matches_answer = current.asks.is_empty() + || current + .asks + .iter() + .find(|candidate| candidate.id == ask.id) + .is_some_and(|candidate| { + candidate.text == ask.text + && candidate.wants == ask.wants + && candidate.asked_at == ask.asked_at + && candidate.due_at == ask.due_at + && candidate.answer.as_ref().is_some_and(|answer| { + answer.text == body.text + && answer + .additions + .iter() + .collect::>() + == body + .additions + .iter() + .collect::>() + }) + }); + if current.discloses_application_actor() + || current.id != proposal.id + || current.action_id != proposal.action_id + || current.action_revision != proposal.action_revision + || current.state != BRegProposalState::Submitted + || current.submission_version != proposal.submission_version + || current.effect_digest != proposal.effect_digest + || Some(current.revision) != proposal.revision.checked_add(1) + || !matches_answer + { + return Err(invalid()); + } + Ok(BRegComplete { + value: current + .bind_profile(self.source_binding(), &link.access_profile) + .map_err(|_| invalid())?, + metadata: response.metadata, + }) + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn an_answer_without_wants_still_needs_content_before_io() { + assert!(!valid_answer(None, &[], &[])); + assert!(valid_answer(Some("explanation"), &[], &[])); + } +} diff --git a/crates/registry-breg-client/src/proposal/review_asks.rs b/crates/registry-breg-client/src/proposal/review_asks.rs new file mode 100644 index 0000000000..9c49ba744c --- /dev/null +++ b/crates/registry-breg-client/src/proposal/review_asks.rs @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Live answers are intrinsic review context, outside the authored field schema. +use super::*; + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalReviewAsk { + pub id: String, + pub text: String, + pub wants: Vec, + pub asked_at: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub due_at: Option, + pub state: BRegProposalAskState, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub answer: Option, +} +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalReviewAnswer { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, + pub documents: Vec, + pub answered_at: String, +} +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalReviewAnswerDocument { + pub id: String, + pub sha256: String, + pub content_type: String, + pub byte_size: u64, + pub verification_status: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub download: Option, +} +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalReviewAnswerDownload { + pub method: String, + pub operation: String, + pub access_profile: String, + pub path: String, +} +impl fmt::Debug for BRegProposalReviewAsk { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("BRegProposalReviewAsk()") + } +} +impl fmt::Debug for BRegProposalReviewAnswer { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("BRegProposalReviewAnswer()") + } +} + +pub(super) fn valid(document: &BRegProposalReviewDocument) -> bool { + if document.context.asks.len() > 50 { + return false; + } + let mut ids = std::collections::BTreeSet::new(); + for ask in &document.context.asks { + let Some(asked) = proposal_instant(&ask.asked_at) else { + return false; + }; + if !canonical_proposal_id(&ask.id) + || !ids.insert(&ask.id) + || registry_review_protocol::check_public_reason(&ask.text).is_err() + || ask.wants.len() > 8 + || ask + .wants + .iter() + .enumerate() + .any(|(i, w)| ask.wants[..i].contains(w)) + || ask + .due_at + .as_deref() + .is_some_and(|due| proposal_instant(due).is_none_or(|due| due <= asked)) + { + return false; + } + if let Some(answer) = &ask.answer { + let Some(at) = proposal_instant(&answer.answered_at) else { + return false; + }; + if ask.state != BRegProposalAskState::Answered + || at < asked + || !at.nanosecond().is_multiple_of(1000) + || answer.text.as_deref().is_some_and(|text| { + text.trim().is_empty() || text.len() > 2000 || text.contains('\0') + }) + || (answer.text.is_none() && ask.wants.contains(&BRegProposalAskWant::Answer {})) + || (answer.text.is_none() && answer.documents.is_empty()) + || answer.documents.len() > 32 + || (answer.documents.is_empty() + && ask.wants.contains(&BRegProposalAskWant::Document {})) + { + return false; + } + let mut files = std::collections::BTreeSet::new(); + for file in &answer.documents { + if !canonical_proposal_id(&file.id) + || !files.insert(&file.id) + || !digest(&format!("sha256:{}", file.sha256)) + || !crate::attachment::valid_attachment_content_type(&file.content_type) + || !(1..=MAX_BREG_ATTACHMENT_BYTES).contains(&file.byte_size) + || !matches!( + file.verification_status.as_str(), + "notRequired" | "approved" | "pending" | "rejected" + ) + { + return false; + } + if let Some(link) = &file.download { + let Some(contract) = &document.context.contract else { + return false; + }; + let path=format!("/v1/proposals/{}/additions/{}?submissionVersion={}&reviewAskId={}&effectDigest={}&contextSchemaDigest={}",document.id,file.id,document.submission_version,ask.id,document.effect_digest.replace(':',"%3A"),contract.schema_digest.replace(':',"%3A")); + if link.method != "GET" + || link.operation != "get-review-context" + || !identifier(&link.access_profile) + || link.path != path + || !matches!( + file.verification_status.as_str(), + "notRequired" | "approved" + ) + { + return false; + } + } + } + } + } + document.context.asks.is_empty() || document.authority.is_some() +} +pub(super) fn profiles(document: &BRegProposalReviewDocument, profile: &str) -> bool { + document + .context + .asks + .iter() + .filter_map(|ask| ask.answer.as_ref()) + .flat_map(|answer| &answer.documents) + .filter_map(|file| file.download.as_ref()) + .all(|link| link.access_profile == profile) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn cited_documents_require_the_verification_status_that_the_server_schema_promises() { + let file = serde_json::json!({"id":"00000000-0000-4000-8000-000000000001","sha256":"a".repeat(64),"contentType":"text/plain","byteSize":1}); + assert!(serde_json::from_value::(file).is_err()); + } +} diff --git a/crates/registry-breg-client/tests/attachment_http_boundary.rs b/crates/registry-breg-client/tests/attachment_http_boundary.rs index be35b8f655..2fed0cd82d 100644 --- a/crates/registry-breg-client/tests/attachment_http_boundary.rs +++ b/crates/registry-breg-client/tests/attachment_http_boundary.rs @@ -248,6 +248,107 @@ fn proposal_response() -> MockResponse { .with_header("cache-control", "no-store") .with_header("vary", "authorization, accept") } + +fn addition_document(state: &str, revision: u64, filled: bool) -> Value { + let mut value = proposal_document(); + value["state"] = json!(state); + value["revision"] = json!(revision); + if state == "submitted" { + value["effectDigest"] = json!(REVISION); + } + value["links"]["submit"] = json!({"method":"POST","path":format!("/v1/proposals/{RECORD_ID}/submit"), + "accessProfile":"writer","operation":"submit","ifMatch":SERVER_ETAG}); + value["additions"] = json!({"other":{"id":"other","maximumBytes":1024,"maximumCount":2, + "contentTypes":["application/pdf"],"classification":"restricted","items":[],"links":{ + "add":{"method":"POST","path":format!("/v1/proposals/{RECORD_ID}/additions/other"), + "accessProfile":"writer","operation":"add","ifMatch":SERVER_ETAG}}}}); + if filled { + let id = "00000000-0000-4000-8000-000000000002"; + let sha256 = Sha256::digest(PDF) + .iter() + .map(|b| format!("{b:02x}")) + .collect::(); + value["additions"]["other"]["items"] = json!([{"id":id,"submissionVersion":2, + "sha256":sha256,"byteSize":PDF.len(),"contentType":"application/pdf","addedAt":"2026-11-27T00:00:00Z", + "verificationStatus":"notRequired","links":{"download":{"method":"GET", + "path":format!("/v1/proposals/{RECORD_ID}/additions/{id}?submissionVersion=2"), + "accessProfile":"writer","operation":"download"}}}]); + } + value +} + +#[tokio::test] +async fn additions_send_exact_raw_bytes_and_download_under_the_callers_token() { + let response = |value| { + MockResponse::json(StatusCode::OK, value) + .with_header("cache-control", "no-store") + .with_header("vary", "authorization, accept") + }; + let (fixture, draft) = selected_with_document( + addition_document("draft", 3, false), + vec![ + response(addition_document("submitted", 4, false)), + response(addition_document("submitted", 5, true)), + download_response(), + ], + ) + .await; + let client = &fixture.client; + let submitted = client + .execute_proposal( + &client + .prepare_proposal(&draft, "submit", json!({}), &key("addition-submit")) + .unwrap(), + ) + .await + .unwrap() + .value; + let requests_before = fixture.requests.lock().unwrap().len(); + for (media, bytes) in [ + ("application/pdf", b"".as_slice()), + ("text/plain", PDF), + ("application/pdf", &[0; 1025]), + ] { + assert!(client + .add_proposal_addition(&submitted, "other", media, bytes, &key("invalid-addition")) + .await + .is_err()); + } + assert_eq!(fixture.requests.lock().unwrap().len(), requests_before); + let added = client + .add_proposal_addition( + &submitted, + "other", + "application/pdf", + PDF, + &key("addition-one"), + ) + .await + .unwrap() + .value; + let downloaded = client + .download_proposal_addition(&added, "00000000-0000-4000-8000-000000000002") + .await + .unwrap(); + assert_eq!(downloaded.value.as_bytes(), PDF); + let requests = fixture.requests.lock().unwrap(); + let upload = &requests[requests_before]; + assert_eq!(upload.method, "POST"); + assert_eq!( + upload.uri, + format!("/tenant/base/v1/proposals/{RECORD_ID}/additions/other?accessProfile=writer") + ); + assert_eq!(upload.body, PDF); + assert_eq!(upload.if_match.as_deref(), Some(SERVER_ETAG)); + assert_eq!(upload.idempotency_key.as_deref(), Some("addition-one")); + let download = &requests[requests_before + 1]; + assert_eq!(download.method, "GET"); + assert!(download.uri.contains( + "/additions/00000000-0000-4000-8000-000000000002?accessProfile=writer&submissionVersion=2" + )); + assert!(upload.authorization.is_some()); + assert!(download.authorization.is_some()); +} fn action_metadata() -> Value { json!({"id":"attachment-test","version":"1","revision":REVISION,"metadataVersion":"2","recordTypes":[],"operations":[],"actions":[{ "id":"correct","apiName":"correct","revision":REVISION,"display":{},"execution":{"mode":"proposal"},"route":"/v1/actions/correct/proposals","inputMode":"fixed","inputs":[],"referenceInputs":[],"requiredConditionKeys":[],"resultEffects":[],"access":{"selectedProfile":"writer"}, diff --git a/crates/registry-breg-client/tests/proposal_additions.rs b/crates/registry-breg-client/tests/proposal_additions.rs new file mode 100644 index 0000000000..cd9d204370 --- /dev/null +++ b/crates/registry-breg-client/tests/proposal_additions.rs @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: Apache-2.0 +use registry_breg_client::BRegProposal; +use serde_json::{json, Value}; + +fn proposal() -> Value { + let id = "00000000-0000-4000-8000-000000000001"; + let addition = "00000000-0000-4000-8000-000000000002"; + json!({"id":id,"actionId":"correct","actionRevision":format!("sha256:{}","a".repeat(64)), + "submissionVersion":1,"revision":3,"state":"submitted","turn":"official", + "effectDigest":format!("sha256:{}","b".repeat(64)),"links":{}, + "additions":{"other":{"id":"other","maximumBytes":32,"maximumCount":2, + "contentTypes":["text/plain"],"classification":"restricted","links":{ + "add":{"method":"POST","path":format!("/v1/proposals/{id}/additions/other"), + "accessProfile":"writer","operation":"add","ifMatch":"\"breg-proposal-three\"", + "availability":{"available":true,"observedRevision":3}}}, + "items":[{"id":addition,"submissionVersion":1,"sha256":"a".repeat(64),"byteSize":4, + "contentType":"text/plain","addedAt":"2026-11-27T00:00:00Z","verificationStatus":"notRequired", + "links":{"download":{"method":"GET","path":format!("/v1/proposals/{id}/additions/{addition}?submissionVersion=1"), + "accessProfile":"writer","operation":"download","availability":{"available":true,"observedRevision":3}}}}]}}}) +} + +#[test] +fn additions_decode_and_keep_the_limit_reason_closed() { + let source = proposal(); + BRegProposal::from_slice(&serde_json::to_vec(&source).unwrap()).expect("additions decode"); + let mut full = source; + full["additions"]["other"]["links"]["add"]["availability"] = json!({ + "available":false,"observedRevision":3,"reason":"limit-reached","recovery":"receipt-only"}); + BRegProposal::from_slice(&serde_json::to_vec(&full).unwrap()).expect("limit reason decodes"); + full["additions"]["other"]["links"]["add"]["availability"]["reason"] = json!("unknown-reason"); + assert!(BRegProposal::from_slice(&serde_json::to_vec(&full).unwrap()).is_err()); +} + +#[test] +fn additions_retain_files_when_the_current_count_limit_is_lowered() { + let mut source = proposal(); + let slot = &mut source["additions"]["other"]; + slot["maximumCount"] = json!(1); + let mut second = slot["items"][0].clone(); + second["id"] = json!("00000000-0000-4000-8000-000000000003"); + second["links"] = json!({}); + slot["items"].as_array_mut().unwrap().push(second); + slot["links"]["add"]["availability"] = json!({ + "available":false,"observedRevision":3,"reason":"limit-reached","recovery":"receipt-only"}); + let decoded = BRegProposal::from_slice(&serde_json::to_vec(&source).unwrap()) + .expect("a lower current limit must not hide retained files"); + assert_eq!(decoded.addition_slot("other").unwrap().items().len(), 2); +} + +#[test] +fn additions_refuse_wrong_paths_versions_bounds_and_unknown_members() { + for mutation in 0..7 { + let mut source = proposal(); + let slot = &mut source["additions"]["other"]; + match mutation { + 0 => slot["maximumCount"] = json!(33), + 1 => slot["items"][0]["submissionVersion"] = json!(2), + 2 => { + slot["items"][0]["links"]["download"]["path"] = + json!("https://untrusted.example.test/file") + } + 3 => slot["links"]["add"]["method"] = json!("PATCH"), + 4 => slot["items"][0]["addedAt"] = json!("tomorrow"), + 5 => slot["items"][0]["fileName"] = json!("private-name"), + _ => { + slot["links"]["add"]["path"] = + json!("/v1/proposals/00000000-0000-4000-8000-000000000099/additions/other") + } + } + assert!( + BRegProposal::from_slice(&serde_json::to_vec(&source).unwrap()).is_err(), + "mutation {mutation}" + ); + } +} diff --git a/crates/registry-breg-client/tests/proposal_document_boundary.rs b/crates/registry-breg-client/tests/proposal_document_boundary.rs index c7c3dc09e9..b1ba4c7eee 100644 --- a/crates/registry-breg-client/tests/proposal_document_boundary.rs +++ b/crates/registry-breg-client/tests/proposal_document_boundary.rs @@ -128,6 +128,45 @@ fn proposal(state: &str) -> Value { value } +#[test] +fn proposal_status_is_closed_and_old_receipts_remain_readable() { + for (status, state, turn) in [ + ("draft", "draft", "party"), + ("awaiting-party", "submitted", "party"), + ("in-review", "submitted", "official"), + ("approved", "submitted", "official"), + ("processing", "submitted", "nobody"), + ("applied", "applied", "nobody"), + ("rejected", "rejected", "nobody"), + ("cancelled", "cancelled", "nobody"), + ] { + let mut value = proposal(state); + value["status"] = json!(status); + value["turn"] = json!(turn); + BRegProposal::from_slice(&serde_json::to_vec(&value).unwrap()) + .expect("known status decodes"); + } + let mut value = proposal("submitted"); + for status in [json!("unknown"), json!(null), json!(true), json!(42)] { + value["status"] = status; + assert!(BRegProposal::from_slice(&serde_json::to_vec(&value).unwrap()).is_err()); + } + value.as_object_mut().unwrap().remove("status"); + BRegProposal::from_slice(&serde_json::to_vec(&value).unwrap()).expect("stored older receipt"); +} + +#[test] +fn proposal_application_pending_is_a_refresh_only_link_reason() { + let mut value = proposal("submitted"); + value["links"]["revise"] = json!({"method":"POST","path":format!("/v1/proposals/{ID}/revise"), + "accessProfile":"writer","operation":"revise","ifMatch":"\"condition\"", + "availability":{"available":false,"observedRevision":2,"reason":"application-pending","recovery":"refresh"}}); + BRegProposal::from_slice(&serde_json::to_vec(&value).unwrap()) + .expect("application-pending decodes"); + value["links"]["revise"]["availability"]["recovery"] = json!("retry"); + assert!(BRegProposal::from_slice(&serde_json::to_vec(&value).unwrap()).is_err()); +} + fn review(context: bool) -> Value { let mut value = json!({"id":ID,"actionId":"correct","actionRevision":DIGEST, "submissionVersion":1,"revision":2,"effectDigest":DIGEST, @@ -360,13 +399,14 @@ async fn application_recovery_is_bound_to_its_reason_in_current_and_retained_rea "current":true,"effectDigest":DIGEST,"review":null,"application":application}); (current, submission) }; - // The only pairs BReg emits: a package change is rebased, a dependency - // outage or an expired lease can be retried, and application failures need - // corrected input. + // Refused applications name the next workflow command. Older receipts + // that named corrected input remain readable. for (reason, recovery) in [ ("package-changed", "rebase"), ("attempts-exhausted", "correct-input"), ("application-refused", "correct-input"), + ("application-refused", "rebase"), + ("application-refused", "revise"), ("dependency-outage", "retry"), ("lease-expired", "retry"), ] { @@ -428,10 +468,16 @@ async fn link_recovery_is_bound_to_its_availability_reason_in_current_and_list_r ("review-changes-requested", "revise"), ("review-ended", "revise"), ("stale-revision", "receipt-only"), + ("stale-revision", "rebase"), ("package-changed", "rebase"), ("dependency-outage", "retry"), ("invalid-input", "correct-input"), + ("invalid-input", "revise"), ("already-applied", "receipt-only"), + ("limit-reached", "receipt-only"), + ("application-pending", "refresh"), + ("attachment-required", "correct-input"), + ("attachment-pending", "refresh"), ]; let reads = |state: &str, availability: Value| { let mut value = proposal(state); @@ -449,6 +495,10 @@ async fn link_recovery_is_bound_to_its_availability_reason_in_current_and_list_r "dependency-outage", "invalid-input", "already-applied", + "limit-reached", + "application-pending", + "attachment-required", + "attachment-pending", ] { for recovery in [ "refresh", @@ -461,6 +511,7 @@ async fn link_recovery_is_bound_to_its_availability_reason_in_current_and_list_r let state = match (reason, recovery) { ("already-applied", _) => "applied", ("review-rejected", "receipt-only") => "rejected", + ("attachment-required" | "attachment-pending", _) => "draft", _ => "submitted", }; let (current, list) = reads( @@ -1915,3 +1966,98 @@ async fn submission_read_carries_only_an_allowlisted_handoff_refusal() { } assert!(accepted.is_empty(), "accepted: {accepted:?}"); } + +#[tokio::test] +async fn answer_commands_bind_the_selected_ask_and_validate_before_tokens_or_io() { + use registry_breg_client::BRegProposalAnswerRequest; + let fixture = Fixture::start().await; + let ask = "00000000-0000-4000-8000-000000000007"; + let mut prior = proposal("submitted"); + prior["asks"] = json!([{"id":ask,"text":"Why?","wants":[{"kind":"answer"}],"askedAt":"2026-11-27T00:00:00Z","state":"open","links":{ + "answer":{"method":"POST","path":format!("/v1/proposals/{ID}/asks/{ask}/answer"),"operation":"answer","accessProfile":"writer","ifMatch":"\"condition\"","availability":{"available":true,"observedRevision":2}}}}]); + let promoted = fixture.proposal(prior.clone()).await; + let key = BRegIdempotencyKey::parse("answer-once").unwrap(); + let tokens = fixture.token.0.load(Ordering::SeqCst); + let requests = fixture.requests.load(Ordering::SeqCst); + for body in [ + json!({}), + json!({"text":" "}), + json!({"text":"explanation","additions":["not-a-uuid"]}), + ] { + let body: BRegProposalAnswerRequest = serde_json::from_value(body).unwrap(); + assert_eq!( + fixture + .client + .answer_proposal_ask(&promoted, ask, &body, &key) + .await + .unwrap_err() + .kind(), + "invalid-request" + ); + } + assert_eq!(fixture.token.0.load(Ordering::SeqCst), tokens); + assert_eq!(fixture.requests.load(Ordering::SeqCst), requests); + let body = BRegProposalAnswerRequest { + text: Some("explanation".into()), + additions: vec![], + }; + let mut receipt = prior; + receipt["revision"] = json!(3); + receipt["asks"][0]["state"] = json!("answered"); + receipt["asks"][0]["answer"] = + json!({"text":"explanation","additions":[],"answeredAt":"2026-11-27T01:00:00Z"}); + receipt["asks"][0]["links"]["answer"]["availability"] = json!({"available":false,"observedRevision":3,"reason":"ask-answered","recovery":"receipt-only"}); + fixture.answer(receipt.clone()); + assert_eq!( + fixture + .client + .answer_proposal_ask(&promoted, ask, &body, &key) + .await + .unwrap() + .value + .asks()[0] + .answer + .as_ref() + .unwrap() + .text + .as_deref(), + Some("explanation") + ); + for mutation in 0..6 { + let mut invalid = receipt.clone(); + match mutation { + 0 => invalid["submissionVersion"] = json!(2), + 1 => invalid["asks"][0]["answer"]["text"] = json!("another answer"), + 2 => { + invalid["asks"][0]["links"]["answer"]["path"] = + json!("https://other.example.test/answer") + } + 3 => invalid["asks"][0]["links"]["answer"]["accessProfile"] = json!("other"), + 4 => { + invalid["revision"] = json!(4); + invalid["asks"][0]["links"]["answer"]["availability"]["observedRevision"] = + json!(4); + } + _ => invalid["effectDigest"] = json!(format!("sha256:{}", "b".repeat(64))), + } + fixture.answer(invalid); + assert_eq!( + fixture + .client + .answer_proposal_ask(&promoted, ask, &body, &key) + .await + .unwrap_err() + .kind(), + "protocol", + "mutation {mutation}" + ); + } + let inert = BRegProposal::from_slice(&serde_json::to_vec(&receipt).unwrap()).unwrap(); + let tokens = fixture.token.0.load(Ordering::SeqCst); + assert!(fixture + .client + .answer_proposal_ask(&inert, ask, &body, &key) + .await + .is_err()); + assert_eq!(fixture.token.0.load(Ordering::SeqCst), tokens); +} diff --git a/crates/registry-breg-client/tests/required_attachment_problem.rs b/crates/registry-breg-client/tests/required_attachment_problem.rs new file mode 100644 index 0000000000..4d8b772446 --- /dev/null +++ b/crates/registry-breg-client/tests/required_attachment_problem.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Apache-2.0 +use axum::{body::Body, extract::State, http::Response, routing::get, Router}; +use registry_breg_client::{BaseRegistryClient, BaseRegistryClientConfig}; +use serde_json::{json, Value}; +use std::sync::{Arc, Mutex}; + +async fn slot_problem(code: &str, status: u16, detail: &str) { + let problem = Arc::new(Mutex::new(json!({ + "type":format!("https://id.registrystack.org/problems/registry-breg/{}",code.replace('.',"/")), + "title":if status == 409 {"Conflict"} else {"Unprocessable Entity"},"status":status,"detail":detail, + "code":code,"traceId":"4bf92f3577b34da6a3ce929d0e0e4736", + "fieldPath":"/attachments/support" + }))); + async fn answer(State(problem): State>>) -> Response { + let document = problem.lock().unwrap().clone(); + Response::builder() + .status(document["status"].as_u64().unwrap() as u16) + .header("content-type", "application/problem+json") + .header("cache-control", "no-store") + .header( + "traceparent", + "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", + ) + .body(Body::from(document.to_string())) + .unwrap() + } + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let state = problem.clone(); + let server = tokio::spawn(async move { + axum::serve( + listener, + Router::new() + .route("/v1/registry", get(answer)) + .with_state(state), + ) + .await + .unwrap(); + }); + let client = BaseRegistryClient::new(BaseRegistryClientConfig::new( + url::Url::parse(&format!("http://{address}/")).unwrap(), + )) + .unwrap(); + let error = client.registry_metadata(None).await.unwrap_err(); + assert_eq!(error.problem_code().map(|code| code.code()), Some(code)); + assert_eq!( + error.field_path().map(|path| path.as_str()), + Some("/attachments/support") + ); + problem + .lock() + .unwrap() + .as_object_mut() + .unwrap() + .remove("fieldPath"); + assert_eq!( + client.registry_metadata(None).await.unwrap_err().kind(), + "protocol", + "the code requires a slot location" + ); + for invalid in [ + "/input/support", + "/attachments", + "/attachments/support/bytes", + "/attachments/UPPER", + "/attachments/a~1b", + ] { + problem.lock().unwrap()["fieldPath"] = json!(invalid); + assert_eq!( + client.registry_metadata(None).await.unwrap_err().kind(), + "protocol", + "{invalid}" + ); + } + server.abort(); +} + +#[tokio::test] +async fn required_attachment_problems_retain_only_a_valid_slot_location() { + for code in [ + registry_breg_client::BRegProblemCode::AttachmentRequired, + registry_breg_client::BRegProblemCode::AttachmentVerificationPending, + registry_breg_client::BRegProblemCode::AttachmentVerificationRejected, + ] { + let detail = match code { + registry_breg_client::BRegProblemCode::AttachmentRequired => "The required attachment slot is empty.", + registry_breg_client::BRegProblemCode::AttachmentVerificationPending => "The attachment is awaiting verification. Refresh the Proposal before submitting.", + _ => "The attachment was rejected by verification. Replace or remove the file before submitting.", + }; + slot_problem(code.code(), code.status(), detail).await; + } +} diff --git a/crates/registry-breg-client/tests/write_http_boundary.rs b/crates/registry-breg-client/tests/write_http_boundary.rs index 3aff3e657b..f8b5a13cec 100644 --- a/crates/registry-breg-client/tests/write_http_boundary.rs +++ b/crates/registry-breg-client/tests/write_http_boundary.rs @@ -2092,6 +2092,13 @@ fn problem_response(code: BRegProblemCode) -> MockResponse { }); if code == BRegProblemCode::ActionRefused { body["refusalCode"] = json!(REFUSAL_CODE); + } else if matches!( + code, + BRegProblemCode::AttachmentRequired + | BRegProblemCode::AttachmentVerificationPending + | BRegProblemCode::AttachmentVerificationRejected + ) { + body["fieldPath"] = json!("/attachments/support"); } else if code == BRegProblemCode::StatisticalDatasetReleaseRefused { body["refusalCode"] = json!("period-not-ended"); } else if code == BRegProblemCode::StatisticalDatasetVersionWithdrawn { @@ -2140,6 +2147,12 @@ fn problem_detail(code: BRegProblemCode) -> &'static str { Code::AttachmentDigestMismatch => { "The file content does not match its declared SHA-256 digest." } + Code::AttachmentLimitReached => { + "The supporting document slot has reached its file limit." + } + Code::AttachmentRequired => "The required attachment slot is empty.", + Code::AttachmentVerificationPending => "The attachment is awaiting verification. Refresh the Proposal before submitting.", + Code::AttachmentVerificationRejected => "The attachment was rejected by verification. Replace or remove the file before submitting.", Code::AttachmentSlotWriteOnce => { "The record attachment slot already holds a file and is write-once." } diff --git a/crates/registry-breg/examples/example-artifacts.rs b/crates/registry-breg/examples/example-artifacts.rs index bb207b9003..600323622c 100644 --- a/crates/registry-breg/examples/example-artifacts.rs +++ b/crates/registry-breg/examples/example-artifacts.rs @@ -9,7 +9,7 @@ fn main() -> Result<(), Box> { let mut args = env::args_os().skip(1); if args.next().as_deref() != Some(std::ffi::OsStr::new("--output")) { return Err( - "usage: example-artifacts --output DIRECTORY [--project minimal|facility]".into(), + "usage: example-artifacts --output DIRECTORY [--project minimal|facility|required-attachment]".into(), ); } let output = PathBuf::from(args.next().ok_or("missing output directory")?); @@ -18,7 +18,7 @@ fn main() -> Result<(), Box> { Some(flag) if flag == "--project" => args .next() .and_then(|value| value.into_string().ok()) - .ok_or("--project requires minimal or facility")?, + .ok_or("--project requires minimal, facility or required-attachment")?, _ => return Err("unexpected argument".into()), }; if args.next().is_some() { @@ -29,6 +29,10 @@ fn main() -> Result<(), Box> { include_bytes!("../../../products/breg/examples/minimal/registry.yaml"), Vec::new(), ), + "required-attachment" => ( + include_bytes!("../../../products/breg/examples/required-attachment/registry.yaml"), + Vec::new(), + ), "facility" => ( include_bytes!("../../../products/breg/examples/facility/registry.yaml"), vec![ModuleAssetSource { @@ -40,7 +44,7 @@ fn main() -> Result<(), Box> { .to_vec(), }], ), - _ => return Err("--project requires minimal or facility".into()), + _ => return Err("--project requires minimal, facility or required-attachment".into()), }; let project = parse_project_yaml(source)?; let model = compile_project_with_assets(&project, &[], &assets, CompileProfile::Authoring)?; diff --git a/crates/registry-breg/src/access.rs b/crates/registry-breg/src/access.rs index dc0d437806..d1c9f26081 100644 --- a/crates/registry-breg/src/access.rs +++ b/crates/registry-breg/src/access.rs @@ -1136,6 +1136,8 @@ fn timer_writer_explanations( matches!( operation, crate::contract::ProposalOperation::Edit + | crate::contract::ProposalOperation::Add + | crate::contract::ProposalOperation::Answer | crate::contract::ProposalOperation::Submit | crate::contract::ProposalOperation::Revise | crate::contract::ProposalOperation::Apply diff --git a/crates/registry-breg/src/api/actions.rs b/crates/registry-breg/src/api/actions.rs index 21815a5617..d0e95302ae 100644 --- a/crates/registry-breg/src/api/actions.rs +++ b/crates/registry-breg/src/api/actions.rs @@ -815,16 +815,16 @@ fn maximum_action_body_bytes(action: &CompiledAction, kind: ActionRouteKind) -> } /// Why an Action request body was not read. -enum ActionBodyError { +pub(super) enum ActionBodyError { /// The body is longer than the route reads. TooLarge, /// The body is empty or its stream failed. Invalid, } -/// Reads at most `maximum_bytes` of an Action request body. Unlike a plain +/// Reads at most `maximum_bytes` of an Action or attachment body. Unlike a plain /// bounded read, it tells a body that is too long apart from a broken one. -async fn read_action_body( +pub(super) async fn read_action_body( mut body: Body, maximum_bytes: usize, ) -> Result, ActionBodyError> { diff --git a/crates/registry-breg/src/api/attachments.rs b/crates/registry-breg/src/api/attachments.rs index fb52f50999..e905914c38 100644 --- a/crates/registry-breg/src/api/attachments.rs +++ b/crates/registry-breg/src/api/attachments.rs @@ -1,15 +1,55 @@ // SPDX-License-Identifier: Apache-2.0 //! Engine-owned Proposal slots. Get and Edit have explicit, separate byte grants. +use super::proposals::ReviewDocumentSource; use super::*; use crate::model::{CompiledActionExecution, HttpMethod, ProposalOperation}; use crate::postgres::{ProposalAuthority, ProposalAuthorityOperation}; pub(super) fn routes(_service: &HttpService) -> Router> { - Router::new().route( - "/v1/proposals/{proposal_id}/attachments/{slot_id}", - get(download).patch(upload).delete(remove), + Router::new() + .route( + "/v1/proposals/{proposal_id}/attachments/{slot_id}", + get(download).patch(upload).delete(remove), + ) + .route( + "/v1/proposals/{proposal_id}/additions/{file_id}", + get(download_addition).post(add), + ) +} + +async fn add( + State(service): State>, + Path((id, slot)): Path<(String, String)>, + Extension(correlation): Extension, + Authenticated(claims): Authenticated, + RawQuery(raw): RawQuery, + headers: HeaderMap, + body: Body, +) -> Response { + mutate( + service, + id, + slot, + correlation, + claims, + raw, + headers, + body, + false, + true, ) + .await +} + +fn mutation_method(removal: bool, addition: bool) -> HttpMethod { + if addition { + HttpMethod::Post + } else if removal { + HttpMethod::Delete + } else { + HttpMethod::Patch + } } #[allow(clippy::too_many_arguments)] @@ -32,6 +72,7 @@ async fn upload( headers, body, false, + false, ) .await } @@ -55,6 +96,7 @@ async fn remove( headers, body, true, + false, ) .await } @@ -67,7 +109,8 @@ async fn authorize( claims: &VerifiedRequestClaims, selected: Option<&str>, operation: ProposalOperation, - context_field: Option<&str>, + context_source: Option>, + addition: bool, method: HttpMethod, correlation: &RequestCorrelation, ) -> Result<(String, ProposalAuthority), Response> { @@ -119,14 +162,44 @@ async fn authorize( }); let allowed = grant.is_some_and(|grant| match operation { ProposalOperation::Get => grant.readable_attachments.contains(slot), - ProposalOperation::GetReviewContext => context_field.is_some_and(|field| - grant.readable_context_fields.contains(field) - && matches!(proposal.review_context.as_ref().and_then(|context| context.fields.get(field)), - Some(crate::contract::ProposalContextValueSource::Document { slot: mapped }) if mapped == slot)), - ProposalOperation::Edit => grant.writable_attachments.contains(slot), + ProposalOperation::GetReviewContext => match context_source { + // A file an answer cites is admitted in place of the authored + // additions field, so the caller's readable context fields do not + // apply to it. Only a human reviewer receives answers, so only a + // human reviewer is admitted here. + Some(ReviewDocumentSource::Ask(_)) => addition && authority.receives_review_answers, + Some(ReviewDocumentSource::Field(field)) => { + grant.readable_context_fields.contains(field) + && match proposal + .review_context + .as_ref() + .and_then(|context| context.fields.get(field)) + { + Some(crate::contract::ProposalContextValueSource::Document { + slot: mapped, + }) => !addition && mapped == slot, + Some(crate::contract::ProposalContextValueSource::Additions { + slot: mapped, + }) => addition && mapped == slot, + _ => false, + } + } + None => false, + }, + ProposalOperation::Edit | ProposalOperation::Add => { + grant.writable_attachments.contains(slot) + } _ => false, }); - if !proposal.attachments.contains_key(slot) || !allowed { + let declared = if addition { + proposal + .additions + .as_ref() + .is_some_and(|definition| definition.id == slot) + } else { + proposal.attachments.contains_key(slot) + }; + if !declared || !allowed { return Err(super::proposals::admitted_http_refusal( mutations, &authority, @@ -150,6 +223,7 @@ async fn mutate( headers: HeaderMap, body: Body, removal: bool, + addition: bool, ) -> Response { let Some(mutations) = &service.mutations else { return concealed(FailedCheck::Visibility); @@ -166,13 +240,14 @@ async fn mutate( &slot, &claims, selected.as_deref(), - ProposalOperation::Edit, - None, - if removal { - HttpMethod::Delete + if addition { + ProposalOperation::Add } else { - HttpMethod::Patch + ProposalOperation::Edit }, + None, + addition, + mutation_method(removal, addition), &correlation, ) .await @@ -186,11 +261,7 @@ async fn mutate( return super::proposals::admitted_http_refusal( mutations, &authority, - if removal { - HttpMethod::Delete - } else { - HttpMethod::Patch - }, + mutation_method(removal, addition), &correlation, missing_idempotency_key(), ) @@ -200,11 +271,7 @@ async fn mutate( return super::proposals::admitted_http_refusal( mutations, &authority, - if removal { - HttpMethod::Delete - } else { - HttpMethod::Patch - }, + mutation_method(removal, addition), &correlation, precondition_required(), ) @@ -220,17 +287,19 @@ async fn mutate( let CompiledActionExecution::Proposal { proposal } = &action.execution else { return concealed(FailedCheck::Operation); }; - let definition = &proposal.attachments[&slot]; + let (content_types, maximum_bytes) = if addition { + let definition = proposal.additions.as_ref().expect("admitted addition slot"); + (&definition.content_types, definition.maximum_bytes) + } else { + let definition = &proposal.attachments[&slot]; + (&definition.content_types, definition.maximum_bytes) + }; let (content_type, bytes) = if removal { if !to_bytes(body, 0).await.is_ok_and(|bytes| bytes.is_empty()) { return super::proposals::admitted_http_refusal( mutations, &authority, - if removal { - HttpMethod::Delete - } else { - HttpMethod::Patch - }, + mutation_method(removal, addition), &correlation, invalid_request(), ) @@ -238,59 +307,46 @@ async fn mutate( } (None, None) } else { - let Some(content_type) = single_header(&headers, CONTENT_TYPE.as_str()).filter(|value| { - definition - .content_types - .iter() - .any(|allowed| allowed == value) - }) else { + let Some(content_type) = single_header(&headers, CONTENT_TYPE.as_str()) + .filter(|value| content_types.iter().any(|allowed| allowed == value)) + else { return super::proposals::admitted_http_refusal( mutations, &authority, - if removal { - HttpMethod::Delete - } else { - HttpMethod::Patch - }, + mutation_method(removal, addition), &correlation, - unsupported_media_type(), + fixed_problem(ProblemCode::AttachmentContentType), ) .await; }; - let Ok(bytes) = bounded_body_to(body, definition.maximum_bytes as usize).await else { - return super::proposals::admitted_http_refusal( - mutations, - &authority, - if removal { - HttpMethod::Delete + let bytes = match super::actions::read_action_body(body, maximum_bytes as usize).await { + Ok(bytes) => bytes, + Err(error) => { + let problem = if matches!(error, super::actions::ActionBodyError::TooLarge) { + fixed_problem(ProblemCode::AttachmentTooLarge) } else { - HttpMethod::Patch - }, - &correlation, - invalid_request(), - ) - .await; + invalid_request() + }; + return super::proposals::admitted_http_refusal( + mutations, + &authority, + mutation_method(removal, addition), + &correlation, + problem, + ) + .await; + } }; - if bytes.is_empty() { - return super::proposals::admitted_http_refusal( - mutations, - &authority, - if removal { - HttpMethod::Delete - } else { - HttpMethod::Patch - }, - &correlation, - invalid_request(), - ) - .await; - } - (Some(content_type.to_owned()), Some(bytes.to_vec())) + (Some(content_type.to_owned()), Some(bytes)) }; let input = super::proposals::ProposalMutationInput { action_id: &action_id, proposal_id: Some(id), - operation: ProposalAuthorityOperation::Lifecycle(ProposalOperation::Edit), + operation: ProposalAuthorityOperation::Lifecycle(if addition { + ProposalOperation::Add + } else { + ProposalOperation::Edit + }), authority: &authority, idempotency_key: key, expected_etag: Some(etag), @@ -300,6 +356,7 @@ async fn mutate( reason: None, executor_lease: None, rebase_start_authority: None, + answer: None, attachment: Some(crate::attachment::AttachmentMutation { slot_id: slot, content_type, @@ -327,6 +384,28 @@ async fn download( Extension(correlation): Extension, Authenticated(claims): Authenticated, RawQuery(raw): RawQuery, +) -> Response { + download_file(service, id, slot, correlation, claims, raw, false).await +} + +async fn download_addition( + State(service): State>, + Path((id, file)): Path<(String, String)>, + Extension(correlation): Extension, + Authenticated(claims): Authenticated, + RawQuery(raw): RawQuery, +) -> Response { + download_file(service, id, file, correlation, claims, raw, true).await +} + +async fn download_file( + service: Arc, + id: String, + mut slot: String, + correlation: RequestCorrelation, + claims: VerifiedRequestClaims, + raw: Option, + addition: bool, ) -> Response { let Some(mutations) = &service.mutations else { return concealed(FailedCheck::Visibility); @@ -334,14 +413,38 @@ async fn download( let Ok(id) = Uuid::parse_str(&id) else { return concealed(FailedCheck::Visibility); }; + let addition_id = if addition { + let Ok(file) = Uuid::parse_str(&slot) else { + return concealed(FailedCheck::Visibility); + }; + let action_id = match mutations.proposal_action_id(id).await { + Ok(Some(action)) => action, + Ok(None) => return concealed(FailedCheck::Visibility), + Err(error) => return super::proposals::proposal_problem(error), + }; + let Some(definition) = service + .registry + .actions() + .actions + .iter() + .find(|action| action.id == action_id) + .and_then(|action| match &action.execution { + CompiledActionExecution::Proposal { proposal } => proposal.additions.as_ref(), + _ => None, + }) + else { + return concealed(FailedCheck::Visibility); + }; + slot = definition.id.clone(); + Some(file) + } else { + None + }; let Ok(query) = parse_download_query(raw.as_deref()) else { return concealed(FailedCheck::Visibility); }; let (field, operation) = match &query.review { - Some(review) => ( - Some(review.field.as_str()), - ProposalOperation::GetReviewContext, - ), + Some(review) => (Some(review.source()), ProposalOperation::GetReviewContext), None => (None, ProposalOperation::Get), }; let (action_id, authority) = match authorize( @@ -352,6 +455,7 @@ async fn download( query.selected.as_deref(), operation, field, + addition, HttpMethod::Get, &correlation, ) @@ -390,7 +494,7 @@ async fn download( .review .as_ref() .map(|review| super::proposals::ReviewContextDocumentRead { - field: &review.field, + source: review.source(), effect_digest: &review.effect_digest, schema_digest: &review.schema_digest, records: &records, @@ -400,6 +504,7 @@ async fn download( id, query.version, &slot, + addition_id, &authority, review.as_ref(), &correlation, @@ -430,12 +535,26 @@ struct AttachmentDownloadQuery { review: Option, } #[derive(Debug)] +enum ReviewDownloadSelector { + Field(String), + Ask(Uuid), +} +#[derive(Debug)] struct ReviewDownloadQuery { - field: String, + selector: ReviewDownloadSelector, effect_digest: String, schema_digest: String, } +impl ReviewDownloadQuery { + fn source(&self) -> ReviewDocumentSource<'_> { + match &self.selector { + ReviewDownloadSelector::Field(field) => ReviewDocumentSource::Field(field), + ReviewDownloadSelector::Ask(ask) => ReviewDocumentSource::Ask(*ask), + } + } +} + fn parse_download_query(raw: Option<&str>) -> Result { let raw = raw.ok_or(QueryParseError::Invalid)?; if raw.len() > MAX_RAW_QUERY_BYTES { @@ -444,6 +563,7 @@ fn parse_download_query(raw: Option<&str>) -> Result) -> Result { + let id = Uuid::parse_str(&value).map_err(|_| QueryParseError::Invalid)?; + if id.is_nil() || id.to_string() != value { + return Err(QueryParseError::Invalid); + } + ask = Some(id); + } "effectDigest" if effect_digest.is_none() && registry_platform_yaml::Digest::new(&value).is_ok() => @@ -481,10 +608,17 @@ fn parse_download_query(raw: Option<&str>) -> Result return Err(QueryParseError::Invalid), } } - let review = match (field, effect_digest, schema_digest) { - (None, None, None) => None, - (Some(field), Some(effect_digest), Some(schema_digest)) => Some(ReviewDownloadQuery { - field, + let review = match (field, ask, effect_digest, schema_digest) { + (None, None, None, None) => None, + (Some(field), None, Some(effect_digest), Some(schema_digest)) => { + Some(ReviewDownloadQuery { + selector: ReviewDownloadSelector::Field(field), + effect_digest, + schema_digest, + }) + } + (None, Some(ask), Some(effect_digest), Some(schema_digest)) => Some(ReviewDownloadQuery { + selector: ReviewDownloadSelector::Ask(ask), effect_digest, schema_digest, }), @@ -525,7 +659,9 @@ mod tests { fn review_document_query_is_complete_closed_and_exclusive() { let valid = format!("submissionVersion=1&reviewContextField=supportingDocument&effectDigest=sha256%3A{}&contextSchemaDigest=sha256%3A{}&accessProfile=reviewer_one", "a".repeat(64), "b".repeat(64)); let parsed = parse_download_query(Some(&valid)).unwrap(); - assert_eq!(parsed.review.unwrap().field, "supportingDocument"); + assert!( + matches!(parsed.review.unwrap().selector,ReviewDownloadSelector::Field(field) if field=="supportingDocument") + ); for invalid in [ "submissionVersion=1&reviewContextField=supportingDocument".to_owned(), valid.replace("effectDigest=", "unknown="), diff --git a/crates/registry-breg/src/api/mod.rs b/crates/registry-breg/src/api/mod.rs index 6fb5e80993..2be1e04dd2 100644 --- a/crates/registry-breg/src/api/mod.rs +++ b/crates/registry-breg/src/api/mod.rs @@ -206,6 +206,10 @@ fn route_set(service: Arc) -> Router { get(proposals::review_context_batch), ) .route("/v1/proposals/{proposal_id}", get(proposals::get)) + .route( + "/v1/proposals/{proposal_id}/asks/{ask_id}/answer", + post(proposals::answer), + ) .route( "/v1/proposals/{proposal_id}/submissions/{submission_version}", get(proposals::submission), @@ -569,12 +573,16 @@ async fn openapi( &mut paths, &mut schemas, ); - crate::artifacts::append_proposal_openapi( + if crate::artifacts::append_proposal_openapi( &mut paths, service.registry.actions(), service.registry.entities(), Some(&visible_proposals), - ); + ) + .is_err() + { + return unavailable(); + } statistics::append_openapi(&service, &claims, &options, &mut paths, &mut schemas); if service.external_views.is_some() { crate::external_view_artifacts::append( @@ -5747,6 +5755,19 @@ fn precondition_failed() -> Response { fixed_problem(ProblemCode::PreconditionFailed) } +fn attachment_slot_problem(problem: ProblemCode, slot: &str) -> Response { + crate::correlation::problem_response_with_field_path( + StatusCode::from_u16(problem.status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), + problem.title(), + problem.description(), + problem.code(), + format!( + "/attachments/{}", + slot.replace('~', "~0").replace('/', "~1") + ), + ) +} + fn mutation_problem(error: MutationError) -> Response { let check = error.failed_check(); let response = mutation_problem_response(error); @@ -5764,6 +5785,7 @@ fn mutation_problem_response(error: MutationError) -> Response { MutationError::InvalidRequestAt(location) => invalid_request_at(&location), MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed + | MutationError::ProposalTargetChanged | MutationError::FieldGuardFailed { .. } | MutationError::ProposalGuardFailed(_) | MutationError::TimerGenerationUnsupported => precondition_failed(), @@ -5778,6 +5800,16 @@ fn mutation_problem_response(error: MutationError) -> Response { fixed_problem(ProblemCode::AttachmentSlotWriteOnce) } MutationError::AttachmentTooLarge => fixed_problem(ProblemCode::AttachmentTooLarge), + MutationError::AttachmentLimitReached => fixed_problem(ProblemCode::AttachmentLimitReached), + MutationError::AttachmentRequired { slot } => { + attachment_slot_problem(ProblemCode::AttachmentRequired, &slot) + } + MutationError::AttachmentVerificationPending { slot } => { + attachment_slot_problem(ProblemCode::AttachmentVerificationPending, &slot) + } + MutationError::AttachmentVerificationRejected { slot } => { + attachment_slot_problem(ProblemCode::AttachmentVerificationRejected, &slot) + } MutationError::AttachmentContentType => fixed_problem(ProblemCode::AttachmentContentType), MutationError::AttachmentDigestMismatch => { fixed_problem(ProblemCode::AttachmentDigestMismatch) diff --git a/crates/registry-breg/src/api/proposals.rs b/crates/registry-breg/src/api/proposals.rs index 13c20a3a83..eb0597c5f3 100644 --- a/crates/registry-breg/src/api/proposals.rs +++ b/crates/registry-breg/src/api/proposals.rs @@ -4,11 +4,13 @@ //! admitted independently; a business Record is never used as a Proposal. use super::*; +mod answers; use crate::model::{ CompiledAction, CompiledActionExecution, CompiledActionRoute, CompiledProposalPermission, CompiledRegistry, HttpMethod, ProposalOperation, }; use crate::postgres::{ProposalAuthority, ProposalAuthorityOperation, RowBoundaryContext}; +pub(super) use answers::answer; pub(super) fn proposal_problem(error: MutationError) -> Response { match error { @@ -38,6 +40,7 @@ pub(crate) struct ProposalMutationInput<'a> { pub executor_lease: Option, pub rebase_start_authority: Option<&'a ProposalAuthority>, pub attachment: Option, + pub answer: Option, pub correlation: &'a RequestCorrelation, pub human_identity: Option<&'a registry_review_client::HumanIdentity>, pub claims: Option<&'a VerifiedRequestClaims>, @@ -60,8 +63,13 @@ pub(crate) struct ProposalRecordReadAuthority { pub context: crate::postgres::ClaimContext, } +#[derive(Clone, Copy)] +pub(crate) enum ReviewDocumentSource<'a> { + Field(&'a str), + Ask(Uuid), +} pub(crate) struct ReviewContextDocumentRead<'a> { - pub field: &'a str, + pub source: ReviewDocumentSource<'a>, pub effect_digest: &'a str, pub schema_digest: &'a str, pub records: &'a BTreeMap, @@ -305,7 +313,7 @@ pub(crate) fn authorize_checked( { return Err(FailedCheck::TaskGrantMissing); } - let (profile, targets, task_source) = match operation { + let (profile, targets, task_source, profile_kind) = match operation { ProposalAuthorityOperation::Start => { let grant = action .permissions @@ -339,6 +347,7 @@ pub(crate) fn authorize_checked( grant.profile_id.as_str(), targets, grant.task_grant.as_ref(), + grant.actor_kind, ) } ProposalAuthorityOperation::Lifecycle(operation) => { @@ -389,6 +398,7 @@ pub(crate) fn authorize_checked( grant.profile_id.as_str(), targets, grant.task_grant.as_ref(), + grant.actor_kind, ) } }; @@ -405,6 +415,27 @@ pub(crate) fn authorize_checked( authority.common = authority .common .with_audit_context(crate::audit::RequestAuditContext::from_claims(claims)); + // An applicant's answers and the files they cite reach human reviewers + // only: a verified human caller, on a profile written for humans or for + // any kind, acting for no one else and under no task grant. A delegated + // actor, a standing or task-granted agent and a service never receive + // them, whatever their grant says. + authority.receives_review_answers = claims.actor_kind() + == Some(registry_platform_oidc::ActorKind::Human) + && claims.actor_subject().is_none() + && claims.grant().is_none() + && task_source.is_none() + && matches!( + profile_kind, + None | Some(crate::contract::ActorKindSource::Human) + ); + // Answering is the applicant's own act and takes the same human test. + // The Proposal document's `asks` member follows this admission. + if operation == ProposalAuthorityOperation::Lifecycle(ProposalOperation::Answer) + && !authority.receives_review_answers + { + return Err(FailedCheck::ActorKind); + } match (task_source, claims.grant()) { (None, None) => {} (Some(source), Some(grant)) => { @@ -461,6 +492,10 @@ pub(super) fn selected_profile(raw: Option<&str>) -> Result, ()> } fn review_status_options(raw: Option<&str>) -> Result<(Option, bool), ()> { + review_include_options(raw, "progress") +} + +fn review_include_options(raw: Option<&str>, include: &str) -> Result<(Option, bool), ()> { let Some(raw) = raw else { return Ok((None, false)); }; @@ -468,20 +503,20 @@ fn review_status_options(raw: Option<&str>) -> Result<(Option, bool), () return Err(()); } let mut ordinary = Vec::new(); - let mut include_progress = false; + let mut included = false; for pair in raw.split('&') { let (name, value) = pair.split_once('=').ok_or(())?; if percent_decode(name).map_err(|_| ())? == "include" { - if include_progress || percent_decode(value).map_err(|_| ())? != "progress" { + if included || percent_decode(value).map_err(|_| ())? != include { return Err(()); } - include_progress = true; + included = true; } else { ordinary.push(pair); } } let ordinary = (!ordinary.is_empty()).then(|| ordinary.join("&")); - Ok((selected_profile(ordinary.as_deref())?, include_progress)) + Ok((selected_profile(ordinary.as_deref())?, included)) } fn parse_input(action: &CompiledAction, value: &Value) -> Result, ()> { @@ -764,6 +799,7 @@ pub(super) async fn start( executor_lease: None, rebase_start_authority: None, attachment: None, + answer: None, correlation: &correlation, human_identity: claims.human_identity(), claims: Some(&claims), @@ -1165,6 +1201,7 @@ pub(super) async fn transition( executor_lease: None, rebase_start_authority: rebase_start_authority.as_ref(), attachment: None, + answer: None, correlation: &correlation, human_identity: claims.human_identity(), claims: Some(&claims), @@ -1309,6 +1346,7 @@ pub(super) async fn review_context_batch( claims.clone(), profile.clone(), ProposalOperation::GetReviewContext, + ReviewAnswers::Omitted, correlation.clone(), ) .await; @@ -1352,6 +1390,7 @@ pub(super) async fn review_context( claims, raw, ProposalOperation::GetReviewContext, + ReviewAnswers::Served, correlation, ) .await @@ -1370,6 +1409,7 @@ pub(super) async fn review_status( claims, raw, ProposalOperation::GetReviewStatus, + ReviewAnswers::Omitted, correlation, ) .await @@ -1547,12 +1587,23 @@ pub(super) async fn task_grant_context( } } +/// Whether a review read may carry applicant answers. The batch inbox read +/// shows none, so it neither serves nor audits them; only the single-Proposal +/// review-context read does, and then only to a human reviewer. +#[derive(Clone, Copy, Eq, PartialEq)] +enum ReviewAnswers { + Served, + Omitted, +} + +#[allow(clippy::too_many_arguments)] async fn review_read( service: Arc, id: String, claims: VerifiedRequestClaims, raw: Option, operation: ProposalOperation, + answers: ReviewAnswers, correlation: RequestCorrelation, ) -> Response { let Some(mutations) = &service.mutations else { @@ -1561,8 +1612,10 @@ async fn review_read( let Ok(id) = Uuid::parse_str(&id) else { return concealed(FailedCheck::Visibility); }; - let Ok((selected, include_progress)) = (if operation == ProposalOperation::GetReviewStatus { + let Ok((selected, included)) = (if operation == ProposalOperation::GetReviewStatus { review_status_options(raw.as_deref()) + } else if operation == ProposalOperation::GetReviewContext { + review_include_options(raw.as_deref(), "answers") } else { selected_profile(raw.as_deref()).map(|selected| (selected, false)) }) else { @@ -1582,7 +1635,7 @@ async fn review_read( else { return concealed(FailedCheck::Visibility); }; - let authority = match authorize_checked( + let mut authority = match authorize_checked( &service.registry, action, &claims, @@ -1605,6 +1658,10 @@ async fn review_read( .await; } }; + if answers == ReviewAnswers::Omitted || !included { + authority.receives_review_answers = false; + } + let include_progress = included && operation == ProposalOperation::GetReviewStatus; let records = review_record_authorities( &service.registry, action, @@ -1661,6 +1718,7 @@ pub(crate) fn review_record_authorities( use crate::contract::ProposalContextValueSource; let target = match source { ProposalContextValueSource::Input { .. } + | ProposalContextValueSource::Additions { .. } | ProposalContextValueSource::Document { .. } => continue, ProposalContextValueSource::Record { input, .. } => { let input = action diff --git a/crates/registry-breg/src/api/proposals/answers.rs b/crates/registry-breg/src/api/proposals/answers.rs new file mode 100644 index 0000000000..a47486b712 --- /dev/null +++ b/crates/registry-breg/src/api/proposals/answers.rs @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Applicant answers use the same admission, ETag and receipt boundary as other commands. +use super::*; +use crate::review_store::asks::{AnswerBody, AnswerMutation}; + +#[allow(clippy::too_many_arguments)] +pub(in crate::api) async fn answer( + State(service): State>, + Path((id, ask)): Path<(String, String)>, + Extension(correlation): Extension, + Authenticated(claims): Authenticated, + RawQuery(raw_query): RawQuery, + headers: HeaderMap, + body: Body, +) -> Response { + let Some(mutations) = &service.mutations else { + return concealed(FailedCheck::Visibility); + }; + let (Ok(id), Ok(ask_id)) = (Uuid::parse_str(&id), Uuid::parse_str(&ask)) else { + return concealed(FailedCheck::Visibility); + }; + if id.is_nil() || ask_id.is_nil() { + return concealed(FailedCheck::Visibility); + } + let Ok(selected) = selected_profile(raw_query.as_deref()) else { + return concealed(FailedCheck::Visibility); + }; + let action_id = match mutations.proposal_action_id(id).await { + Ok(Some(action)) => action, + Ok(None) => return concealed(FailedCheck::Visibility), + Err(error) => return proposal_problem(error), + }; + let Some(action) = service + .registry + .actions() + .actions + .iter() + .find(|action| action.id == action_id) + else { + return concealed(FailedCheck::Visibility); + }; + let operation = ProposalAuthorityOperation::Lifecycle(ProposalOperation::Answer); + let authority = match authorize_checked( + &service.registry, + action, + &claims, + selected.as_deref(), + operation, + Some(id), + ) { + Ok(authority) => authority, + Err(check) => { + return known_action_refusal( + mutations, + action, + &claims, + selected.as_deref(), + operation, + HttpMethod::Post, + &correlation, + check, + ) + .await + } + }; + let refusal = async { + if !single_content_type(&headers, "application/json") { + return Err(unsupported_media_type()); + } + let key = single_header(&headers, "idempotency-key") + .filter(|key| valid_idempotency_key(key)) + .ok_or_else(missing_idempotency_key)?; + let etag = single_header(&headers, "if-match") + .filter(|etag| valid_if_match(etag)) + .ok_or_else(precondition_required)?; + let bytes = bounded_body_to(body, 16_384) + .await + .map_err(|_| invalid_request())?; + let value = parse_json_strict(&bytes).map_err(|_| invalid_request())?; + if value.get("text").is_some_and(Value::is_null) { + return Err(proposal_problem(MutationError::InvalidRequestAt( + crate::problem_location::RequestLocation::proposal_answer_text(), + ))); + } + let answer: AnswerBody = serde_json::from_value(value).map_err(|_| invalid_request())?; + Ok((key, etag, answer)) + } + .await; + let (key, etag, body) = match refusal { + Ok(values) => values, + Err(response) => { + return admitted_http_refusal( + mutations, + &authority, + HttpMethod::Post, + &correlation, + response, + ) + .await + } + }; + match mutations + .proposal_mutation(ProposalMutationInput { + action_id: &action.id, + proposal_id: Some(id), + operation, + authority: &authority, + idempotency_key: key, + expected_etag: Some(etag), + input: None, + submission_version: None, + effect_digest: None, + reason: None, + executor_lease: None, + rebase_start_authority: None, + attachment: None, + answer: Some(AnswerMutation { ask_id, body }), + correlation: &correlation, + human_identity: claims.human_identity(), + claims: Some(&claims), + }) + .await + { + Ok(outcome) => exact_mutation( + outcome.response(), + None, + "", + service.field_encryption.as_deref(), + ), + Err(error) => proposal_problem(error), + } +} diff --git a/crates/registry-breg/src/api/tests/immediate_action_tests.rs b/crates/registry-breg/src/api/tests/immediate_action_tests.rs index 0eb719aef4..7eccf1402a 100644 --- a/crates/registry-breg/src/api/tests/immediate_action_tests.rs +++ b/crates/registry-breg/src/api/tests/immediate_action_tests.rs @@ -290,6 +290,7 @@ async fn proposal_task_scopes_and_standing_agent_draft_and_context_permissions_a "requiredScopes":["case.rename"],"requiredPurposes":["case-management"],"taskGrant":{"sourceIssuer":"https://casework.example"}, "permissions":{"actions":[{"action":"propose-rename","operations":["start"],"targets":[{"recordType":"case","rowBoundaries":[{"field":"region","claim":"grantRegion","operator":"equals"}]}]}], "proposals":[{"action":"propose-rename","operations":["get","list","edit","submit","revise","cancel","apply","rebase","retry","get-review-status"],"ownership":"caller", + "readableInputs":["case-ref","case-label"], "targets":[{"recordType":"case","rowBoundaries":[{"field":"region","claim":"grantRegion","operator":"equals"}]}]}]}}); project .access_profiles @@ -297,6 +298,10 @@ async fn proposal_task_scopes_and_standing_agent_draft_and_context_permissions_a task_profile["id"] = json!("standing-proposer"); task_profile.as_object_mut().unwrap().remove("taskGrant"); task_profile["permissions"]["proposals"][0]["operations"] = json!(["edit"]); + task_profile["permissions"]["proposals"][0] + .as_object_mut() + .unwrap() + .remove("readableInputs"); project .access_profiles .push(serde_json::from_value(task_profile).unwrap()); diff --git a/crates/registry-breg/src/artifacts.rs b/crates/registry-breg/src/artifacts.rs index 57b2a6edc3..e32f6ea45a 100644 --- a/crates/registry-breg/src/artifacts.rs +++ b/crates/registry-breg/src/artifacts.rs @@ -305,7 +305,7 @@ pub(crate) fn generate_artifacts( schemas: &schemas, statistical_datasets, external_views, - }); + })?; insert_json_value(&mut artifacts, "generated/openapi.json", &openapi)?; if let Some(projection) = manifest_projection { let projected = project_manifest_artifacts(registry_id, projection, entities)?; @@ -1089,8 +1089,8 @@ pub(crate) fn openapi_action_response_schema( action: &CompiledAction, selected_result_effects: Option<&BTreeSet>, ) -> Value { - if action.execution.is_proposal() { - return proposal_schema(); + if let crate::model::CompiledActionExecution::Proposal { proposal } = &action.execution { + return proposal_schema_with_additions(proposal.additions.is_some()); } let result_shapes = action_response_result_shapes(action, selected_result_effects); let results_schema = match result_shapes.as_slice() { @@ -1518,12 +1518,14 @@ pub fn proposal_schema() -> Value { "createdAt":{"type":"string","format":"date-time"}, "submissionVersion":{"type":"integer","minimum":0},"revision":{"type":"integer","minimum":1}, "state":{"enum":["draft","submitted","applied","cancelled","rejected"]}, + "status":{"enum":crate::lifecycle::ProposalStatus::ALL.map(crate::lifecycle::ProposalStatus::as_str)}, "title":{"type":"string","maxLength":1024}, "input":{"type":"object"}, "application":proposal_application_schema(), "applicationStatus":proposal_application_status_schema(), "turn":{"enum":["party","official","nobody"]}, "decision":proposal_decision_schema(), + "asks":proposal_asks_schema(false), "handoffRefusal":proposal_handoff_refusal_schema(), "blockedReason":{"enum":["package-changed"]},"effectDigest":{"type":"string"}, "attachments":{"type":"object","maxProperties":8,"additionalProperties":proposal_attachment_schema()}, @@ -1537,6 +1539,75 @@ pub fn proposal_schema() -> Value { }}) } +/// Questions are intrinsic context and never authored context fields. +pub(crate) fn proposal_asks_schema(review: bool) -> Value { + let uuid = json!({"type":"string","format":"uuid"}); + let instant = json!({"type":"string","format":"date-time"}); + let text = json!({"type":"string","minLength":1,"maxLength":2000}); + let wants = json!({"type":"array","maxItems":8,"uniqueItems":true,"items":{ + "type":"object","additionalProperties":false,"required":["kind"], + "properties":{"kind":{"enum":["answer","document"]}}}}); + let mut answer = json!({"type":"object","additionalProperties":false, + "required":["answeredAt"],"properties":{"text":text,"answeredAt":instant}}); + let mut properties = json!({"id":uuid,"text":text,"wants":wants, + "askedAt":instant,"dueAt":instant,"state":{"enum":["open","answered","expired","closed"]}}); + let mut required = vec!["id", "text", "wants", "askedAt", "state"]; + if review { + answer["required"] = json!(["documents", "answeredAt"]); + answer["properties"]["documents"] = json!({"type":"array","maxItems":32,"items":{ + "type":"object","additionalProperties":false, + "required":["id","sha256","contentType","byteSize","verificationStatus"], + "properties":{"id":uuid,"sha256":{"type":"string","pattern":"^[0-9a-f]{64}$"}, + "contentType":{"type":"string","maxLength":255},"byteSize":{"type":"integer","minimum":1,"maximum":crate::contract::MAX_ATTACHMENT_BYTES}, + "verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}, + "download":{"type":"object","additionalProperties":false,"required":["method","operation","accessProfile","path"], + "properties":{"method":{"const":"GET"},"operation":{"const":"get-review-context"},"accessProfile":{"type":"string"},"path":{"type":"string"}}}}}}); + } else { + answer["required"] = json!(["additions", "answeredAt"]); + answer["properties"]["additions"] = + json!({"type":"array","maxItems":32,"uniqueItems":true,"items":uuid}); + required.push("links"); + properties["links"] = json!({"type":"object","additionalProperties":false,"properties":{"answer":{ + "type":"object","additionalProperties":false,"required":["method","path","accessProfile","operation","ifMatch","availability"], + "properties":{"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"},"accessProfile":{"type":"string"},"ifMatch":{"type":"string"},"availability":availability_schema()}}}}); + } + properties["answer"] = answer; + json!({"type":"array","maxItems":crate::contract::MAX_MIRRORED_REVIEW_ASKS,"items":{"type":"object","additionalProperties":false,"required":required,"properties":properties}}) +} + +pub(crate) fn proposal_schema_with_additions(enabled: bool) -> Value { + let mut schema = proposal_schema(); + if enabled { + append_proposal_additions_schema(&mut schema); + } + schema +} + +pub(crate) fn append_proposal_additions_schema(schema: &mut Value) { + let availability = availability_schema(); + let link = |method: &str, operation: &str| { + json!({"type":"object","additionalProperties":false, + "required":["method","path","accessProfile","operation"],"properties":{ + "method":{"const":method},"operation":{"const":operation},"path":{"type":"string"}, + "accessProfile":{"type":"string"},"ifMatch":{"type":"string"},"availability":availability}}) + }; + let item = json!({"type":"object","additionalProperties":false, + "required":["id","submissionVersion","sha256","byteSize","contentType","addedAt","verificationStatus","links"], + "properties":{"id":{"type":"string","format":"uuid"},"submissionVersion":{"type":"integer","minimum":1,"maximum":u32::MAX}, + "sha256":{"type":"string","pattern":"^[a-f0-9]{64}$"},"byteSize":{"type":"integer","minimum":1,"maximum":crate::contract::MAX_ATTACHMENT_BYTES}, + "contentType":{"type":"string"},"addedAt":{"type":"string","format":"date-time"}, + "verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}, + "links":{"type":"object","additionalProperties":false,"properties":{"download":link("GET","download")}}}}); + schema["properties"]["additions"] = json!({"type":"object","maxProperties":1,"additionalProperties":{ + "type":"object","additionalProperties":false, + "required":["id","maximumBytes","maximumCount","contentTypes","classification","items","links"], + "properties":{"id":{"type":"string"},"maximumBytes":{"type":"integer","minimum":1,"maximum":crate::contract::MAX_ATTACHMENT_BYTES}, + "maximumCount":{"type":"integer","minimum":1,"maximum":32}, + "contentTypes":{"type":"array","minItems":1,"maxItems":16,"uniqueItems":true,"items":{"type":"string"}}, + "classification":{"enum":["public","internal","restricted"]},"items":{"type":"array","maxItems":32,"items":item}, + "links":{"type":"object","additionalProperties":false,"properties":{"add":link("POST","add")}}}}}); +} + /// Why the review authority refused a submission's hand-off for good. Only /// allowlisted codes are named; the authority's text is never served. pub(crate) fn proposal_handoff_refusal_schema() -> Value { @@ -1564,7 +1635,7 @@ fn proposal_application_status_schema() -> Value { "state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}, "mode":{"enum":["automatic","manual"]}, "reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]}, - "recovery":{"enum":["retry","rebase","correct-input"]}, + "recovery":{"enum":["retry","rebase","revise","correct-input"]}, "automaticRetry":{"type":"object","additionalProperties":false, "required":["scheduled","attempts","maximumAttempts"],"properties":{ "scheduled":{"type":"boolean"},"attempts":{"type":"integer","minimum":0,"maximum":1000}, @@ -1607,8 +1678,8 @@ fn proposal_attachment_schema() -> Value { pub fn availability_schema() -> Value { json!({"type":"object","additionalProperties":false,"required":["available","observedRevision"], "properties":{"available":{"type":"boolean"},"observedRevision":{"type":"integer","minimum":1}, - "reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]}, - "recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}}, + "reason":{"enum":crate::lifecycle::ProposalAvailabilityReason::ALL.iter().map(|reason| reason.as_str()).collect::>()}, + "recovery":{"enum":crate::lifecycle::ProposalLinkRecovery::ALL.iter().map(|recovery| recovery.as_str()).collect::>()}}, "if":{"properties":{"available":{"const":false}}},"then":{"required":["reason","recovery"]}}) } @@ -1886,6 +1957,12 @@ fn action_operation_responses( ("200", success) }; let mut responses = Map::from_iter([(success_status.to_owned(), success)]); + if route.operation == Operation::Start { + let mut document = json!({"operationId":route.id,"responses":responses}); + proposal_artifacts::append_operation_problems(&mut document, "post"); + return document["responses"].take(); + } + for (status, problems) in action_problem_responses(route.kind, action, may_refuse_write) { let mut examples = problems .iter() @@ -2270,7 +2347,7 @@ struct OpenApiDocumentInput<'a> { external_views: &'a crate::external_views::CompiledExternalViews, } -fn openapi_document(input: OpenApiDocumentInput<'_>) -> Value { +fn openapi_document(input: OpenApiDocumentInput<'_>) -> Result { let OpenApiDocumentInput { registry_id, version, @@ -2415,7 +2492,7 @@ fn openapi_document(input: OpenApiDocumentInput<'_>) -> Value { openapi_action_operation(route, action, entities, OpenApiAccessProfiles::All), ); } - append_proposal_openapi(&mut paths, actions, entities, None); + append_proposal_openapi(&mut paths, actions, entities, None)?; crate::external_view_artifacts::append( &mut paths, external_views, @@ -2445,12 +2522,12 @@ fn openapi_document(input: OpenApiDocumentInput<'_>) -> Value { statistical_datasets, false, ); - json!({ + Ok(json!({ "openapi": "3.1.0", "info": {"title": registry_id, "version": version}, "paths": paths, "components": openapi_components(component_schemas, has_immediate_actions) - }) + })) } pub(crate) const ACCESS_LOG_RESPONSE_SCHEMA_ID: &str = "SubjectAccessLogPage"; @@ -4531,6 +4608,21 @@ fn problem_schema() -> Value { } }, "allOf": [ + { + "if": {"properties": {"code": {"enum": ["attachment.required","attachment.verification-pending","attachment.verification-rejected"]}}}, + "then": { + "required": ["fieldPath"], + "propertyNames": {"enum":["type","title","status","detail","code","traceId","fieldPath"]}, + "properties": { + "fieldPath": {"type":"string","pattern":"^/attachments/[a-z][a-z0-9_-]{0,63}$"} + }, + "allOf":[{ + "if":{"properties":{"code":{"const":"attachment.verification-pending"}}}, + "then":{"properties":{"status":{"const":409}}}, + "else":{"properties":{"status":{"const":422}}} + }] + } + }, { "if": {"properties": {"code": {"const": write_outside_boundary.code()}}}, "then": { @@ -5009,6 +5101,44 @@ fn canonicalization_error() -> Diagnostic { mod problem_contract_tests { use super::*; + #[test] + fn required_attachment_problem_contract_names_a_slot() { + let schema = problem_schema(); + let validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&schema) + .unwrap(); + for code in [ + crate::problem::ProblemCode::AttachmentRequired, + crate::problem::ProblemCode::AttachmentVerificationPending, + crate::problem::ProblemCode::AttachmentVerificationRejected, + ] { + let mut body = + problem_example(&code.status().to_string(), code.code(), code.description()); + assert!( + !validator.is_valid(&body), + "a required slot refusal must identify the slot" + ); + body["fieldPath"] = json!("/attachments/support"); + assert!(validator.is_valid(&body)); + for invalid in [ + "/input/support", + "/attachments", + "/attachments/support/bytes", + "/attachments/UPPER", + ] { + body["fieldPath"] = json!(invalid); + assert!(!validator.is_valid(&body), "{invalid}"); + } + body["fieldPath"] = json!("/attachments/support"); + body["recordType"] = json!("private-record"); + assert!( + !validator.is_valid(&body), + "a slot problem permits no record metadata" + ); + } + } + #[test] fn application_reason_contract_is_optional_bounded_and_closed() { { diff --git a/crates/registry-breg/src/attachment_store.rs b/crates/registry-breg/src/attachment_store.rs index db3d4fcfc1..3407aae137 100644 --- a/crates/registry-breg/src/attachment_store.rs +++ b/crates/registry-breg/src/attachment_store.rs @@ -16,6 +16,8 @@ use crate::mutation::MutationError; use crate::postgres::SqlIdentifier; use crate::proposal_workflow::AttachmentManifestEntry; +pub(crate) mod additions; + pub(crate) const ATTACHMENT_TABLES: &[(&str, &[&str])] = &[ ("registry_attachment_storage_binding", &["INSERT", "SELECT"]), ( @@ -30,6 +32,7 @@ pub(crate) const ATTACHMENT_TABLES: &[(&str, &[&str])] = &[ "registry_proposal_attachments", &["INSERT", "SELECT", "UPDATE", "DELETE"], ), + ("registry_proposal_additions", &["INSERT", "SELECT"]), // The runtime only adds record references. Erasure runs as the owning // migration role, and a write-once slot is never updated or deleted. ("registry_record_attachments", &["INSERT", "SELECT"]), @@ -95,6 +98,27 @@ pub(crate) async fn install( ); CREATE INDEX IF NOT EXISTS registry_attachment_live_references ON registry_internal.registry_proposal_attachments (sha256) WHERE erased_at IS NULL; + CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_additions ( + action_id text NOT NULL, + proposal_id uuid NOT NULL, + submission_version bigint NOT NULL CHECK (submission_version BETWEEN 1 AND 4294967295), + addition_id uuid NOT NULL, + slot_id text NOT NULL, + sha256 text CHECK (sha256 ~ '^[0-9a-f]{64}$'), + content_type text, + byte_size bigint CHECK (byte_size BETWEEN 1 AND 16777216), + added_at timestamptz, + added_by text, + erased_at timestamptz, + PRIMARY KEY (action_id, proposal_id, submission_version, addition_id), + FOREIGN KEY (action_id,proposal_id) REFERENCES registry_internal.registry_proposal_state, + CHECK ((erased_at IS NULL AND sha256 IS NOT NULL AND content_type IS NOT NULL + AND byte_size IS NOT NULL AND added_at IS NOT NULL AND added_by IS NOT NULL) + OR (erased_at IS NOT NULL AND sha256 IS NULL AND content_type IS NULL + AND byte_size IS NULL AND added_at IS NULL AND added_by IS NULL)) + ); + CREATE INDEX IF NOT EXISTS registry_addition_live_references + ON registry_internal.registry_proposal_additions (sha256) WHERE erased_at IS NULL; CREATE TABLE IF NOT EXISTS registry_internal.registry_record_attachments ( entity_id text NOT NULL CHECK (entity_id <> ''), record_id uuid NOT NULL, @@ -367,6 +391,47 @@ pub(crate) async fn put( for h in hashes { lock_hash(client, &h).await?; } + put_blob( + client, + &hash, + content_type, + bytes, + backend, + verification_policy, + ) + .await?; + let size = bytes.len() as i64; + let row=client.query_one("INSERT INTO registry_internal.registry_proposal_attachments + (action_id,proposal_id,submission_version,slot_id,sha256,content_type,byte_size,uploaded_at,uploaded_by) + VALUES ($1,$2,$3,$4,$5,$6,$7,transaction_timestamp(),$8) ON CONFLICT + (action_id,proposal_id,submission_version,slot_id) DO UPDATE SET + sha256=EXCLUDED.sha256,content_type=EXCLUDED.content_type,byte_size=EXCLUDED.byte_size,uploaded_at=EXCLUDED.uploaded_at,uploaded_by=EXCLUDED.uploaded_by + WHERE registry_proposal_attachments.erased_at IS NULL RETURNING to_char(uploaded_at AT TIME + ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')", &[&entity,&id,&version,&slot,&hash,&content_type,&size,&actor]).await.map_err(unavailable)?; + if let Some(old) = old { + retire_unreferenced(client, &old).await?; + } + let verification_status = verification_status(client, &hash, content_type).await?; + Ok(AttachmentMetadata { + verification_status, + slot_id: slot.to_owned(), + content_type: content_type.to_owned(), + byte_size: bytes.len() as u64, + sha256: hash, + uploaded_at: row.get(0), + uploaded_by: actor.to_owned(), + }) +} + +/// Store exact bytes and enqueue verification under the caller's hash lock. +async fn put_blob( + client: &Transaction<'_>, + hash: &str, + content_type: &str, + bytes: &[u8], + backend: &str, + verification_policy: &str, +) -> Result<(), MutationError> { let size = bytes.len() as i64; if backend == "database" { client @@ -379,7 +444,7 @@ pub(crate) async fn put( .await .map_err(unavailable)?; } - require_backend(client, &hash, backend, bytes.len() as u64).await?; + require_backend(client, hash, backend, bytes.len() as u64).await?; if backend == "database" { let intact: bool = client.query_one( "SELECT content=$2 FROM registry_internal.registry_attachment_blobs WHERE sha256=$1", @@ -397,27 +462,8 @@ pub(crate) async fn put( ) .await .map_err(unavailable)?; - request_verification(client, &hash, content_type, verification_policy).await?; - let row=client.query_one("INSERT INTO registry_internal.registry_proposal_attachments - (action_id,proposal_id,submission_version,slot_id,sha256,content_type,byte_size,uploaded_at,uploaded_by) - VALUES ($1,$2,$3,$4,$5,$6,$7,transaction_timestamp(),$8) ON CONFLICT - (action_id,proposal_id,submission_version,slot_id) DO UPDATE SET - sha256=EXCLUDED.sha256,content_type=EXCLUDED.content_type,byte_size=EXCLUDED.byte_size,uploaded_at=EXCLUDED.uploaded_at,uploaded_by=EXCLUDED.uploaded_by - WHERE registry_proposal_attachments.erased_at IS NULL RETURNING to_char(uploaded_at AT TIME - ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')", &[&entity,&id,&version,&slot,&hash,&content_type,&size,&actor]).await.map_err(unavailable)?; - if let Some(old) = old { - retire_unreferenced(client, &old).await?; - } - let verification_status = verification_status(client, &hash, content_type).await?; - Ok(AttachmentMetadata { - verification_status, - slot_id: slot.to_owned(), - content_type: content_type.to_owned(), - byte_size: bytes.len() as u64, - sha256: hash, - uploaded_at: row.get(0), - uploaded_by: actor.to_owned(), - }) + request_verification(client, hash, content_type, verification_policy).await?; + Ok(()) } async fn request_verification( @@ -491,6 +537,8 @@ async fn retire_unreferenced(client: &impl GenericClient, hash: &str) -> Result< DELETE FROM registry_internal.registry_attachment_verification v WHERE sha256=$1 AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_attachments a WHERE a.sha256=v.sha256 AND a.content_type=v.content_type AND a.erased_at IS NULL) + AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_additions a + WHERE a.sha256=v.sha256 AND a.content_type=v.content_type AND a.erased_at IS NULL) AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_record_attachments r WHERE r.sha256=v.sha256 AND r.content_type=v.content_type AND r.erased_at IS NULL) RETURNING verification_id) @@ -503,6 +551,8 @@ async fn retire_unreferenced(client: &impl GenericClient, hash: &str) -> Result< client.execute("UPDATE registry_internal.registry_attachment_blobs b SET state='delete_pending', deletion_checked_at=NULL WHERE sha256=$1 AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_attachments a WHERE a.sha256=b.sha256 AND a.erased_at IS NULL) + AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_additions a + WHERE a.sha256=b.sha256 AND a.erased_at IS NULL) AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_record_attachments r WHERE r.sha256=b.sha256 AND r.erased_at IS NULL)", &[&hash]).await.map_err(unavailable)?; client @@ -635,6 +685,57 @@ pub(crate) async fn require_frozen_reference( Ok(()) } +/// Submit and its link use this same stored-file decision, before any plan +/// evaluation. Rejected required files count as empty, then other files must +/// finish verification before their descriptors can enter the frozen manifest. +pub(crate) async fn submission_manifest( + client: &impl GenericClient, + action: &str, + id: Uuid, + version: i64, + slots: &BTreeMap, +) -> Result, MutationError> { + let policy = persisted_verification_policy(client).await?; + let files = metadata(client, action, id, version).await?; + for (slot, definition) in slots { + if definition.required + && files.get(slot).is_none_or(|file| { + file.verification_status == AttachmentVerificationStatus::Rejected + }) + { + return Err(MutationError::AttachmentRequired { slot: slot.clone() }); + } + } + for (slot, file) in &files { + if !slots.contains_key(slot) { + return Err(MutationError::PreconditionFailed); + } + match file.verification_status { + AttachmentVerificationStatus::Pending => { + return Err(MutationError::AttachmentVerificationPending { slot: slot.clone() }) + } + AttachmentVerificationStatus::Rejected => { + return Err(MutationError::AttachmentVerificationRejected { slot: slot.clone() }) + } + AttachmentVerificationStatus::NotRequired | AttachmentVerificationStatus::Approved => {} + } + } + Ok(files + .into_iter() + .map(|(slot, file)| { + ( + slot, + AttachmentManifestEntry { + sha256: file.sha256, + content_type: file.content_type, + byte_size: file.byte_size, + verification_policy: (policy != "disabled").then(|| policy.clone()), + }, + ) + }) + .collect()) +} + pub(crate) async fn manifest( client: &impl GenericClient, entity: &str, @@ -699,9 +800,12 @@ pub(crate) async fn erase( ) -> Result { let hashes = client .query( - "SELECT DISTINCT sha256 FROM registry_internal.registry_proposal_attachments WHERE - action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND erased_at IS NULL ORDER - BY sha256", + "SELECT sha256 FROM ( + SELECT sha256 FROM registry_internal.registry_proposal_attachments + WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND erased_at IS NULL + UNION SELECT sha256 FROM registry_internal.registry_proposal_additions + WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND erased_at IS NULL + ) AS files ORDER BY sha256", &[&entity, &id, &version], ) .await @@ -719,6 +823,13 @@ pub(crate) async fn erase( ) .await .map_err(unavailable)?; + let additions = client.execute("UPDATE registry_internal.registry_proposal_additions SET + sha256=NULL,content_type=NULL,byte_size=NULL,added_by=NULL,added_at=NULL,erased_at=transaction_timestamp() + WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND erased_at IS NULL", + &[&entity,&id,&version]).await.map_err(unavailable)?; + let count = count + .checked_add(additions) + .ok_or(MutationError::Unavailable)?; for row in hashes { retire_unreferenced(client, &row.get::<_, String>(0)).await?; } @@ -1093,6 +1204,8 @@ pub(crate) async fn finish_external_delete( AND state IN ('staged','delete_pending','delete_confirmed') AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_attachments a WHERE a.sha256=b.sha256 AND a.erased_at IS NULL) + AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_additions a + WHERE a.sha256=b.sha256 AND a.erased_at IS NULL) AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_record_attachments r WHERE r.sha256=b.sha256 AND r.erased_at IS NULL)", &[&hash, &backend], @@ -1116,6 +1229,8 @@ pub(crate) async fn fail_external_delete( AND state IN ('staged','delete_pending','delete_confirmed') AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_attachments a WHERE a.sha256=b.sha256 AND a.erased_at IS NULL) + AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_additions a + WHERE a.sha256=b.sha256 AND a.erased_at IS NULL) AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_record_attachments r WHERE r.sha256=b.sha256 AND r.erased_at IS NULL)", &[&hash, &backend], @@ -1440,6 +1555,8 @@ pub(crate) async fn load_verification_content( AND b.state='live' AND b.backend_id=$5 AND b.byte_size=$6 AND (EXISTS (SELECT 1 FROM registry_internal.registry_proposal_attachments a WHERE a.sha256=v.sha256 AND a.content_type=v.content_type AND a.erased_at IS NULL) + OR EXISTS (SELECT 1 FROM registry_internal.registry_proposal_additions a + WHERE a.sha256=v.sha256 AND a.content_type=v.content_type AND a.erased_at IS NULL) OR EXISTS (SELECT 1 FROM registry_internal.registry_record_attachments r WHERE r.sha256=v.sha256 AND r.content_type=v.content_type AND r.erased_at IS NULL))", &[ diff --git a/crates/registry-breg/src/attachment_store/additions.rs b/crates/registry-breg/src/attachment_store/additions.rs new file mode 100644 index 0000000000..78f0bb4701 --- /dev/null +++ b/crates/registry-breg/src/attachment_store/additions.rs @@ -0,0 +1,189 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Live supporting files are separate from the frozen attachment manifest. +use super::*; + +pub(crate) struct AdditionMetadata { + pub id: Uuid, + pub submission_version: i64, + pub file: AttachmentMetadata, +} + +pub(crate) async fn count( + client: &impl GenericClient, + action: &str, + proposal: Uuid, + version: i64, + slot: &str, +) -> Result { + let count: i64 = client.query_one( + "SELECT count(*) FROM registry_internal.registry_proposal_additions + WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND slot_id=$4 AND erased_at IS NULL", + &[&action, &proposal, &version, &slot], + ).await.map_err(unavailable)?.get(0); + u64::try_from(count).map_err(|_| MutationError::Unavailable) +} + +pub(crate) async fn prepare_put( + client: &impl GenericClient, + hash: &str, + backend: &str, + verification_policy: &str, +) -> Result<(), MutationError> { + pin_backend(client, backend, verification_policy).await?; + lock_hash(client, hash).await +} + +#[allow(clippy::too_many_arguments)] +pub(crate) async fn put( + client: &Transaction<'_>, + action: &str, + proposal: Uuid, + version: i64, + slot: &str, + content_type: &str, + bytes: &[u8], + actor: &str, + backend: &str, + verification_policy: &str, + maximum_count: u32, +) -> Result { + let admitted = client + .query_opt( + "SELECT 1 FROM registry_internal.registry_proposal_state + WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND state='submitted' + AND blocked_reason IS NULL AND detail_erased_at IS NULL FOR UPDATE", + &[&action, &proposal, &version], + ) + .await + .map_err(unavailable)? + .is_some(); + if !admitted { + return Err(MutationError::PreconditionFailed); + } + if bytes.is_empty() || bytes.len() > crate::contract::MAX_ATTACHMENT_BYTES as usize { + return Err(MutationError::InvalidRequest); + } + if count(client, action, proposal, version, slot).await? >= u64::from(maximum_count) { + return Err(MutationError::AttachmentLimitReached); + } + let hash = content_hash(bytes); + prepare_put(client, &hash, backend, verification_policy).await?; + put_blob( + client, + &hash, + content_type, + bytes, + backend, + verification_policy, + ) + .await?; + let addition = Uuid::new_v4(); + let size = bytes.len() as i64; + client.execute( + "INSERT INTO registry_internal.registry_proposal_additions + (action_id,proposal_id,submission_version,addition_id,slot_id,sha256,content_type,byte_size,added_at,added_by) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,transaction_timestamp(),$9)", + &[&action, &proposal, &version, &addition, &slot, &hash, &content_type, &size, &actor], + ).await.map_err(unavailable)?; + Ok(addition) +} + +const ADDITION_METADATA_SELECT: &str = "SELECT a.addition_id,a.submission_version,a.slot_id, + a.content_type,a.byte_size,a.sha256, + to_char(a.added_at AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'),a.added_by, + CASE WHEN COALESCE(p.verification_policy,'disabled')='disabled' THEN 'notRequired' + ELSE COALESCE(v.verdict,'pending') END + FROM registry_internal.registry_proposal_additions a + LEFT JOIN registry_internal.registry_attachment_storage_binding p ON p.singleton + LEFT JOIN registry_internal.registry_attachment_verification v + ON v.sha256=a.sha256 AND v.policy_digest=p.verification_policy AND v.content_type=a.content_type"; + +pub(crate) async fn metadata( + client: &impl GenericClient, + action: &str, + proposal: Uuid, + version: i64, + slot: &str, +) -> Result, MutationError> { + let rows = client + .query( + &format!( + "{ADDITION_METADATA_SELECT} WHERE a.action_id=$1 AND a.proposal_id=$2 AND a.submission_version=$3 + AND a.slot_id=$4 AND a.erased_at IS NULL ORDER BY a.added_at,a.addition_id LIMIT 33" + ), + &[&action, &proposal, &version, &slot], + ) + .await + .map_err(unavailable)?; + if rows.len() > 32 { + return Err(MutationError::Unavailable); + } + rows.into_iter() + .map(|row| { + Ok(AdditionMetadata { + id: row.get(0), + submission_version: row.get(1), + file: AttachmentMetadata { + slot_id: row.get(2), + content_type: row.get(3), + byte_size: u64::try_from(row.get::<_, i64>(4)) + .map_err(|_| MutationError::Unavailable)?, + sha256: row.get(5), + uploaded_at: row.get(6), + uploaded_by: row.get(7), + verification_status: AttachmentVerificationStatus::from_storage( + &row.get::<_, String>(8), + )?, + }, + }) + }) + .collect() +} + +pub(crate) async fn load( + client: &impl GenericClient, + action: &str, + proposal: Uuid, + version: i64, + addition: Uuid, + slot: &str, +) -> Result, MutationError> { + let Some(metadata) = metadata(client, action, proposal, version, slot) + .await? + .into_iter() + .find(|file| file.id == addition) + else { + return Ok(None); + }; + if !metadata.file.verification_status.permits_content() { + return Ok(None); + } + lock_hash(client, &metadata.file.sha256).await?; + if !verification_status(client, &metadata.file.sha256, &metadata.file.content_type) + .await? + .permits_content() + { + return Ok(None); + } + let row = client + .query_opt( + "SELECT b.backend_id,b.content FROM registry_internal.registry_attachment_blobs b JOIN + registry_internal.registry_proposal_additions a ON a.sha256=b.sha256 + WHERE a.action_id=$1 AND a.proposal_id=$2 AND a.submission_version=$3 AND a.addition_id=$4 + AND a.erased_at IS NULL AND a.sha256=$5 AND b.state='live'", + &[ + &action, + &proposal, + &version, + &addition, + &metadata.file.sha256, + ], + ) + .await + .map_err(unavailable)?; + Ok(row.map(|row| StoredAttachment { + metadata: metadata.file, + backend_id: row.get(0), + content: row.get(1), + })) +} diff --git a/crates/registry-breg/src/attachment_verification_worker.rs b/crates/registry-breg/src/attachment_verification_worker.rs index 2c7faa9c1f..1f177e44f3 100644 --- a/crates/registry-breg/src/attachment_verification_worker.rs +++ b/crates/registry-breg/src/attachment_verification_worker.rs @@ -117,6 +117,10 @@ macro_rules! verifiable { WHERE reference.sha256 = verdict.sha256 \ AND reference.content_type = verdict.content_type \ AND reference.erased_at IS NULL) \ + OR EXISTS (SELECT 1 FROM {schema}.registry_proposal_additions AS addition_reference \ + WHERE addition_reference.sha256 = verdict.sha256 \ + AND addition_reference.content_type = verdict.content_type \ + AND addition_reference.erased_at IS NULL) \ OR EXISTS (SELECT 1 FROM {schema}.registry_record_attachments AS record_reference \ WHERE record_reference.sha256 = verdict.sha256 \ AND record_reference.content_type = verdict.content_type \ diff --git a/crates/registry-breg/src/audit.rs b/crates/registry-breg/src/audit.rs index 1c0fbd6e22..6aa0c4e17d 100644 --- a/crates/registry-breg/src/audit.rs +++ b/crates/registry-breg/src/audit.rs @@ -648,6 +648,8 @@ fn proposal_pre_io_record( HttpMethod::Post => matches!( operation, "start" + | "add" + | "answer" | "edit" | "submit" | "revise" diff --git a/crates/registry-breg/src/auth.rs b/crates/registry-breg/src/auth.rs index b3e6d53c14..995fc19143 100644 --- a/crates/registry-breg/src/auth.rs +++ b/crates/registry-breg/src/auth.rs @@ -1189,6 +1189,8 @@ mod tests { "ProblemCode::AuthenticationRefused in artifacts.rs", "ProblemCode::AuthenticationRefused in auth.rs", "ProblemCode::AuthenticationRefused in mod.rs", + // Proposal OpenAPI schemas and examples, never a runtime 401. + "ProblemCode::AuthenticationRefused in proposal_artifacts.rs", ] ); } diff --git a/crates/registry-breg/src/compiler/attachments.rs b/crates/registry-breg/src/compiler/attachments.rs index 47672b78df..dad9a17865 100644 --- a/crates/registry-breg/src/compiler/attachments.rs +++ b/crates/registry-breg/src/compiler/attachments.rs @@ -35,6 +35,45 @@ pub(crate) fn validate_slots( validate_shapes(&shapes, "a Proposal", field_names, base, errors); } +pub(crate) fn validate_additions( + slot: &crate::contract::AdditionSlotSource, + attachments: &[AttachmentSlotSource], + field_names: &BTreeSet, + base: &str, + errors: &mut Vec, +) { + let mut names = field_names.clone(); + names.extend(attachments.iter().map(|attachment| attachment.id.clone())); + let mut diagnostics = Vec::new(); + validate_slots( + &[AttachmentSlotSource { + id: slot.id.clone(), + required: false, + maximum_bytes: slot.maximum_bytes, + content_types: slot.content_types.clone(), + classification: slot.classification, + }], + &names, + base, + &mut diagnostics, + ); + for mut diagnostic in diagnostics { + diagnostic.code = diagnostic + .code + .replace("breg.attachment.", "breg.addition."); + diagnostic.path = diagnostic.path.replace(&format!("{base}[0]"), base); + diagnostic.message = diagnostic.message.replace("attachment", "addition"); + errors.push(diagnostic); + } + if !(1..=32).contains(&slot.maximum_count) { + errors.push(Diagnostic::error( + "breg.addition.maximum-count-bounds-invalid", + format!("{base}.maximumCount"), + "addition maximumCount must be between 1 and 32", + )); + } +} + /// Validates a record type's slots. Each must also declare `writeOnce: true`, /// the only mode a record slot has. pub(crate) fn validate_record_slots( diff --git a/crates/registry-breg/src/compiler/review_context.rs b/crates/registry-breg/src/compiler/review_context.rs index 99c6d0c9e2..384238cfaa 100644 --- a/crates/registry-breg/src/compiler/review_context.rs +++ b/crates/registry-breg/src/compiler/review_context.rs @@ -51,6 +51,24 @@ pub fn compile_schema_from_parts( let mut bindings = Map::new(); for (name, projection) in &context.fields { let (schema, classification, binding) = match projection { + ProposalContextValueSource::Additions { slot } => { + let declared = proposal + .additions + .as_ref() + .filter(|declared| &declared.id == slot) + .ok_or_else(&invalid)?; + let mut item = document_schema(slot, true); + item["properties"]["download"]["properties"]["path"]["pattern"] = json!( + r"^/v1/proposals/[0-9a-f-]{36}/additions/[0-9a-f-]{36}\?submissionVersion=[1-9][0-9]{0,9}&reviewContextField=[a-z][a-zA-Z0-9]{0,63}&effectDigest=sha256%3A[0-9a-f]{64}&contextSchemaDigest=sha256%3A[0-9a-f]{64}$" + ); + ( + json!({"type":"array","maxItems":declared.maximum_count,"items":item}), + declared.classification, + json!({"kind":"live-additions","slot":slot,"classification":declared.classification, + "contentTypes":declared.content_types,"maximumBytes":declared.maximum_bytes, + "maximumCount":declared.maximum_count,"transport":"breg-review-context-document/v1"}), + ) + } ProposalContextValueSource::Document { slot } => { let declared = proposal.attachments.get(slot).ok_or_else(&invalid)?; ( diff --git a/crates/registry-breg/src/contract.rs b/crates/registry-breg/src/contract.rs index 5c4a2b33f5..f0cce6429b 100644 --- a/crates/registry-breg/src/contract.rs +++ b/crates/registry-breg/src/contract.rs @@ -623,6 +623,8 @@ pub struct ProposalPolicySource { pub retention: ProposalRetentionSource, #[serde(default)] pub attachments: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub additions: Option, #[serde(default)] pub review_context: Option, /// Post-commit observers of the fixed, value-free Proposal lifecycle event. @@ -660,6 +662,9 @@ impl registry_platform_yaml::Identified for ProposalHookSource { #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum ProposalEventTransition { + Asked, + Answered, + Added, Started, Edited, Submitted, @@ -675,6 +680,9 @@ pub enum ProposalEventTransition { impl ProposalEventTransition { pub const fn as_str(self) -> &'static str { match self { + Self::Asked => "asked", + Self::Answered => "answered", + Self::Added => "added", Self::Started => "started", Self::Edited => "edited", Self::Submitted => "submitted", @@ -785,6 +793,11 @@ pub struct ProposalReviewContextSource { )] #[cfg_attr(feature = "schema", schemars(!remote, tag = "type"))] pub enum ProposalContextValueSource { + Additions { + #[serde(deserialize_with = "local_id")] + #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] + slot: String, + }, Document { #[serde(deserialize_with = "local_id")] #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] @@ -817,9 +830,11 @@ serialize_tagged_union!(ProposalContextValueSource, tag = "type"); #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum ProposalOperation { + Answer, Get, List, Edit, + Add, Submit, Revise, Cancel, @@ -834,9 +849,11 @@ pub enum ProposalOperation { impl ProposalOperation { pub const fn as_str(self) -> &'static str { match self { + Self::Answer => "answer", Self::Get => "get", Self::List => "list", Self::Edit => "edit", + Self::Add => "add", Self::Submit => "submit", Self::Revise => "revise", Self::Cancel => "cancel", @@ -2499,6 +2516,8 @@ pub enum ConsentIssuerSource { /// A request may declare at most eight independently governed binary slots. pub const MAX_ATTACHMENT_SLOTS: usize = 8; +/// Maximum intrinsic review questions retained for one frozen submission. +pub const MAX_MIRRORED_REVIEW_ASKS: usize = 50; /// Bounds both database content and optional external storage operations. pub const MAX_ATTACHMENT_BYTES: u32 = 16 * 1024 * 1024; pub const MAX_ATTACHMENT_CONTENT_TYPES: usize = 16; @@ -2521,6 +2540,25 @@ pub struct AttachmentSlotSource { pub classification: Classification, } +/// Supporting files added to the current submission while its review is open. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct AdditionSlotSource { + #[serde(deserialize_with = "local_id")] + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub id: String, + #[cfg_attr( + feature = "schema", + schemars(with = "BoundedU32<1, MAX_ATTACHMENT_BYTES>") + )] + pub maximum_bytes: u32, + #[cfg_attr(feature = "schema", schemars(with = "BoundedU32<1, 32>"))] + pub maximum_count: u32, + pub content_types: Vec, + pub classification: Classification, +} + /// One file slot on a record type. A file enters it through an immediate /// Action create effect in the same request, or when an applied Proposal /// promotes one of its files. Once written it never changes. diff --git a/crates/registry-breg/src/immediate_actions.rs b/crates/registry-breg/src/immediate_actions.rs index 6e02a461c6..bad3a45cbe 100644 --- a/crates/registry-breg/src/immediate_actions.rs +++ b/crates/registry-breg/src/immediate_actions.rs @@ -3059,6 +3059,22 @@ fn compile_execution( errors, ); let attachments = crate::compiler::attachments::compile_slots(&proposal.attachments); + if let Some(slot) = &proposal.additions { + if matches!(proposal.review, ProposalReviewSource::None {}) { + errors.push(Diagnostic::error( + "breg.addition.review-required", + format!("actions[id={}].execution.proposal.additions", action.id), + "an additions slot requires review.type: required; configure required review or remove additions", + )); + } + crate::compiler::attachments::validate_additions( + slot, + &proposal.attachments, + &attachment_field_names, + &format!("actions[id={}].execution.proposal.additions", action.id), + errors, + ); + } let review = match &proposal.review { ProposalReviewSource::None {} => CompiledProposalReview::None, ProposalReviewSource::Required { @@ -3298,15 +3314,49 @@ fn compile_execution( "input disclosure grants must name declared Action inputs and require Get", )); } + let writes_inputs = grant.operations.iter().any(|operation| { + matches!( + operation, + ProposalOperation::Edit | ProposalOperation::Revise | ProposalOperation::Rebase + ) + }); + // A standing agent cannot hold Get, so it drafts blind and replaces the whole input + // as authored. The rule below protects clients that merge into what they read. + let standing_agent = + profile.actor_kind == Some(ActorKindSource::Agent) && profile.task_grant.is_none(); + if writes_inputs && !standing_agent { + // Edit, Revise, and Rebase replace the stored input wholesale. A client + // merges its change into what it read, so an input it may write but not + // read would be cleared, or would fail when required. + let written = grant + .writable_inputs + .as_ref() + .map_or(&input_ids, |writable| writable.as_set()); + let unreadable = written + .iter() + .filter(|id| input_ids.contains(*id) && !grant.readable_inputs.contains(*id)) + .cloned() + .collect::>(); + if !unreadable.is_empty() { + // Narrowing writableInputs cannot help: the fixed-input rule below + // requires every input outside it to be readable too. + errors.push(Diagnostic::error( + "breg.proposal.input-write-unreadable", + format!( + "accessProfiles[id={}].permissions.proposals[action={}].readableInputs", + profile.id, action.id + ), + &format!( + "access profile `{}` may write input(s) {} of Action `{}` through edit, revise, or rebase but cannot read them, so a client would clear or lose them. Next: add {} to readableInputs (with get)", + profile.id, + unreadable.join(", "), + action.id, + unreadable.join(", "), + ), + )); + } + } if let Some(writable) = &grant.writable_inputs { - let writes_inputs = grant.operations.iter().any(|operation| { - matches!( - operation, - ProposalOperation::Edit - | ProposalOperation::Revise - | ProposalOperation::Rebase - ) - }); let starts = profile.permissions.actions.iter().any(|permission| { permission.action == action.id && permission.operations.contains(&Operation::Start) @@ -3330,18 +3380,32 @@ fn compile_execution( )); } } - let attachment_ids = attachments.keys().cloned().collect::>(); + let attachment_ids = attachments + .keys() + .cloned() + .chain(proposal.additions.iter().map(|slot| slot.id.clone())) + .collect::>(); if !grant.readable_attachments.is_subset(&attachment_ids) || !grant.writable_attachments.is_subset(&attachment_ids) || (!grant.readable_attachments.is_empty() && !grant.operations.contains(&ProposalOperation::Get)) - || (!grant.writable_attachments.is_empty() - && !grant.operations.contains(&ProposalOperation::Edit)) + || grant.writable_attachments.iter().any(|id| { + let operation = if proposal + .additions + .as_ref() + .is_some_and(|slot| &slot.id == id) + { + ProposalOperation::Add + } else { + ProposalOperation::Edit + }; + !grant.operations.contains(&operation) + }) { errors.push(Diagnostic::error( "breg.proposal.attachment-grant-invalid", "accessProfiles[].permissions.proposals", - "attachment grants must name declared slots and require Get for reads or Edit for writes", + "attachment grants must name declared slots and require Get for reads, Edit for attachment writes, or Add for additions", )); } permissions.push(CompiledProposalPermission { @@ -3394,6 +3458,10 @@ fn compile_execution( use crate::contract::ProposalContextValueSource; let valid = match value { ProposalContextValueSource::Document { slot } => attachments.contains_key(slot), + ProposalContextValueSource::Additions { slot } => proposal + .additions + .as_ref() + .is_some_and(|declared| &declared.id == slot), ProposalContextValueSource::Input { input } => { action.inputs.iter().any(|field| &field.id == input) } @@ -3448,6 +3516,7 @@ fn compile_execution( }, review_context: proposal.review_context.clone(), attachments, + additions: proposal.additions.clone(), promotions: Vec::new(), permissions, }, @@ -3761,6 +3830,9 @@ pub(crate) fn definition_revision( } crate::model::CompiledActionExecution::Proposal { proposal } => { let mut policy = json!({"mode":"proposal","review":proposal.review,"application":proposal.application,"retention":proposal.retention,"reviewContext":proposal.review_context,"attachments":proposal.attachments}); + if let Some(slot) = &proposal.additions { + policy["additions"] = json!(slot); + } // Promotions change what an approved Proposal writes, so they are // part of the Action's identity. Omitting an empty list keeps the // revision of every Action without promotions unchanged. diff --git a/crates/registry-breg/src/lifecycle.rs b/crates/registry-breg/src/lifecycle.rs index cc92aa0f48..98524cfa5b 100644 --- a/crates/registry-breg/src/lifecycle.rs +++ b/crates/registry-breg/src/lifecycle.rs @@ -23,6 +23,7 @@ pub struct LifecycleDescription { pub struct LifecycleState { pub id: &'static str, pub turns: Vec, + pub statuses: Vec, pub initial: bool, pub terminal: bool, pub unreachable: bool, @@ -40,6 +41,14 @@ pub struct LifecycleTurn { pub condition: &'static str, } +/// One served status and the condition under which the shared rule selects it. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LifecycleStatus { + pub status: &'static str, + pub condition: &'static str, +} + /// How far the current submission's review has gone. Runtime code derives this /// only from BReg's retained submission and result rows; no authority is asked. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -81,9 +90,193 @@ pub(crate) enum ProposalApplicationProgress { pub(crate) struct ProposalTurnContext { pub(crate) submission_blocked: bool, pub(crate) review: ProposalReviewProgress, + pub(crate) ask_open: bool, pub(crate) application: ProposalApplicationProgress, } +// Each vocabulary is declared once: runtime values and served schemas use it. +macro_rules! proposal_wire_values { + ($name:ident { $($variant:ident => $wire:literal),+ $(,)? }) => { + #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] + pub enum $name { + $(#[serde(rename = $wire)] $variant),+ + } + impl $name { + pub const ALL: &'static [Self] = &[$(Self::$variant),+]; + pub const fn as_str(self) -> &'static str { + match self { $(Self::$variant => $wire),+ } + } + } + }; +} + +proposal_wire_values!(ProposalAvailabilityReason { + PendingReview => "pending-review", + ReviewRejected => "review-rejected", + ReviewChangesRequested => "review-changes-requested", + ReviewEnded => "review-ended", + StaleRevision => "stale-revision", + PackageChanged => "package-changed", + DependencyOutage => "dependency-outage", + InvalidInput => "invalid-input", + AlreadyApplied => "already-applied", + LimitReached => "limit-reached", + ApplicationPending => "application-pending", + AttachmentRequired => "attachment-required", + AttachmentPending => "attachment-pending", + AskAnswered => "ask-answered", + AskClosed => "ask-closed", + AskDuePassed => "ask-due-passed", +}); + +proposal_wire_values!(ProposalLinkRecovery { + Refresh => "refresh", + Revise => "revise", + Retry => "retry", + Rebase => "rebase", + CorrectInput => "correct-input", + ReceiptOnly => "receipt-only", +}); + +/// The reason and recovery pairs that Proposal links may serve. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ProposalLinkRefusal { + PendingReview, + ReviewRejected, + Rejected, + ChangesRequested, + ReviewEnded, + WrongState, + TargetChanged, + PackageChanged, + DependencyOutage, + InvalidInput, + ReviseInput, + AlreadyApplied, + LimitReached, + ApplicationPending, + AttachmentRequired, + AttachmentPending, + AskAnswered, + AskClosed, + AskDuePassed, +} + +impl ProposalLinkRefusal { + pub const ALL: &'static [Self] = &[ + Self::PendingReview, + Self::ReviewRejected, + Self::Rejected, + Self::ChangesRequested, + Self::ReviewEnded, + Self::WrongState, + Self::TargetChanged, + Self::PackageChanged, + Self::DependencyOutage, + Self::InvalidInput, + Self::ReviseInput, + Self::AlreadyApplied, + Self::LimitReached, + Self::ApplicationPending, + Self::AttachmentRequired, + Self::AttachmentPending, + Self::AskAnswered, + Self::AskClosed, + Self::AskDuePassed, + ]; + + pub const fn pair(self) -> (ProposalAvailabilityReason, ProposalLinkRecovery) { + use ProposalAvailabilityReason as Reason; + use ProposalLinkRecovery as Recovery; + match self { + Self::PendingReview => (Reason::PendingReview, Recovery::Refresh), + Self::ReviewRejected => (Reason::ReviewRejected, Recovery::Revise), + Self::Rejected => (Reason::ReviewRejected, Recovery::ReceiptOnly), + Self::ChangesRequested => (Reason::ReviewChangesRequested, Recovery::Revise), + Self::ReviewEnded => (Reason::ReviewEnded, Recovery::Revise), + Self::WrongState => (Reason::StaleRevision, Recovery::ReceiptOnly), + Self::TargetChanged => (Reason::StaleRevision, Recovery::Rebase), + Self::PackageChanged => (Reason::PackageChanged, Recovery::Rebase), + Self::DependencyOutage => (Reason::DependencyOutage, Recovery::Retry), + Self::InvalidInput => (Reason::InvalidInput, Recovery::CorrectInput), + Self::ReviseInput => (Reason::InvalidInput, Recovery::Revise), + Self::AlreadyApplied => (Reason::AlreadyApplied, Recovery::ReceiptOnly), + Self::LimitReached => (Reason::LimitReached, Recovery::ReceiptOnly), + Self::ApplicationPending => (Reason::ApplicationPending, Recovery::Refresh), + Self::AttachmentRequired => (Reason::AttachmentRequired, Recovery::CorrectInput), + Self::AttachmentPending => (Reason::AttachmentPending, Recovery::Refresh), + Self::AskAnswered => (Reason::AskAnswered, Recovery::ReceiptOnly), + Self::AskClosed => (Reason::AskClosed, Recovery::ReceiptOnly), + Self::AskDuePassed => (Reason::AskDuePassed, Recovery::ReceiptOnly), + } + } +} + +/// A link's complete availability. Private fields prevent JSON assembly from +/// bypassing the closed reason and recovery vocabulary. +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ProposalAvailability { + available: bool, + observed_revision: u64, + #[serde(skip_serializing_if = "Option::is_none")] + reason: Option, + #[serde(skip_serializing_if = "Option::is_none")] + recovery: Option, +} + +impl ProposalAvailability { + pub fn new(observed_revision: u64, refusal: Option) -> Self { + let pair = refusal.map(ProposalLinkRefusal::pair); + Self { + available: pair.is_none(), + observed_revision, + reason: pair.map(|pair| pair.0), + recovery: pair.map(|pair| pair.1), + } + } +} + +/// The current applicant-facing stage, derived together with the turn. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub(crate) enum ProposalStatus { + Draft, + AwaitingParty, + InReview, + Approved, + Processing, + Applied, + Rejected, + Cancelled, +} + +impl ProposalStatus { + pub(crate) const ALL: [Self; 8] = [ + Self::Draft, + Self::AwaitingParty, + Self::InReview, + Self::Approved, + Self::Processing, + Self::Applied, + Self::Rejected, + Self::Cancelled, + ]; + + pub(crate) const fn as_str(self) -> &'static str { + match self { + Self::Draft => "draft", + Self::AwaitingParty => "awaiting-party", + Self::InReview => "in-review", + Self::Approved => "approved", + Self::Processing => "processing", + Self::Applied => "applied", + Self::Rejected => "rejected", + Self::Cancelled => "cancelled", + } + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum ProposalTurn { Party, @@ -114,10 +307,10 @@ impl TurnCondition { match self { Self::Always => "Always while the Proposal is in this state.", Self::SubmittedParty => { - "The submission package is blocked; Review ended without a usable approval; or, after approval or when Review is not required, application is not manual and is blocked without recovery retry." + "The submission package is blocked; Review is pending or retrying with an open ask; Review ended without a usable approval; or, after approval or when Review is not required, application is not manual and is blocked without recovery retry." } Self::SubmittedOfficial => { - "The submission package is not blocked, and either Review is pending or being retried, or, after approval or when Review is not required, application is manual or is blocked with recovery retry." + "The submission package is not blocked, and either Review is pending or being retried without an open ask, or, after approval or when Review is not required, application is manual or is blocked with recovery retry." } Self::SubmittedNobody => { "The submission package is not blocked, Review is approved or not required, and application is neither manual nor blocked, including queued, running, or unreported application status." @@ -143,7 +336,11 @@ fn submitted_turn(context: ProposalTurnContext) -> ProposalTurn { } match context.review { ProposalReviewProgress::Pending | ProposalReviewProgress::Retrying => { - ProposalTurn::Official + if context.ask_open { + ProposalTurn::Party + } else { + ProposalTurn::Official + } } ProposalReviewProgress::Failed | ProposalReviewProgress::ApprovalExpired @@ -217,11 +414,88 @@ fn proposal_turn_rules(state: ProposalState) -> &'static [TurnRule] { /// new Proposal state cannot compile without an explicit turn rule. #[cfg(any(test, feature = "runtime"))] pub(crate) fn proposal_turn(state: ProposalState, context: ProposalTurnContext) -> ProposalTurn { - proposal_turn_rules(state) + proposal_status_and_turn(state, context).1 +} + +/// One rule owns both answers, including blocked submissions and open asks. +#[cfg(any(test, feature = "runtime"))] +pub(crate) fn proposal_status_and_turn( + state: ProposalState, + context: ProposalTurnContext, +) -> (ProposalStatus, ProposalTurn) { + let turn = proposal_turn_rules(state) .iter() .find(|rule| rule.condition.matches(context)) .expect("every Proposal state and context has a turn") - .turn + .turn; + let status = proposal_status_rules(state) + .iter() + .find(|(_, condition)| condition.matches(context, turn)) + .expect("every Proposal state and context has a status") + .0; + (status, turn) +} + +#[derive(Clone, Copy)] +enum StatusCondition { + Always, + Party, + ReviewPending, + ReviewApproved, + ReviewNotRequired, +} + +impl StatusCondition { + const fn description(self) -> &'static str { + match self { + Self::Always => "Always while the Proposal is in this state.", + Self::Party => TurnCondition::SubmittedParty.description(), + Self::ReviewPending => "The submission package is not blocked, Review is pending or retrying, and no ask is open.", + Self::ReviewApproved => "Review is approved and neither the submission package nor application needs action by the party.", + Self::ReviewNotRequired => "Review is not required and neither the submission package nor application needs action by the party.", + } + } + + #[cfg(any(test, feature = "runtime"))] + fn matches(self, context: ProposalTurnContext, turn: ProposalTurn) -> bool { + match self { + Self::Always => true, + Self::Party => turn == ProposalTurn::Party, + Self::ReviewPending => matches!( + context.review, + ProposalReviewProgress::Pending | ProposalReviewProgress::Retrying + ), + Self::ReviewApproved => context.review == ProposalReviewProgress::Approved, + Self::ReviewNotRequired => context.review == ProposalReviewProgress::NotRequired, + } + } +} + +fn proposal_status_rules(state: ProposalState) -> &'static [(ProposalStatus, StatusCondition)] { + use ProposalStatus as Status; + use StatusCondition as Condition; + match state { + ProposalState::Draft => &[(Status::Draft, Condition::Always)], + ProposalState::Cancelled => &[(Status::Cancelled, Condition::Always)], + ProposalState::Applied => &[(Status::Applied, Condition::Always)], + ProposalState::Rejected => &[(Status::Rejected, Condition::Always)], + ProposalState::Submitted => &[ + (Status::AwaitingParty, Condition::Party), + (Status::InReview, Condition::ReviewPending), + (Status::Approved, Condition::ReviewApproved), + (Status::Processing, Condition::ReviewNotRequired), + ], + } +} + +fn lifecycle_statuses(state: ProposalState) -> Vec { + proposal_status_rules(state) + .iter() + .map(|&(status, condition)| LifecycleStatus { + status: status.as_str(), + condition: condition.description(), + }) + .collect() } fn lifecycle_turns(state: ProposalState) -> Vec { @@ -280,6 +554,7 @@ fn build_lifecycle( LifecycleState { id: state_id, turns: lifecycle_turns(state), + statuses: lifecycle_statuses(state), initial, terminal: outgoing_transitions == 0, unreachable: incoming_transitions == 0 && !initial, @@ -329,6 +604,11 @@ fn proposal_enforcement() -> Vec { events: &["rebase"], description: "Rebase explicitly selects the active Action definition and requires both the current Rebase grant and active Start authority. An incompatible activation never silently changes a frozen submission.", }, + EnforcementLayer { + id: "submission-status", + events: &["revise", "rebase"], + description: "Revise and Rebase of a submitted Proposal require awaiting-party or in-review status from the shared status and turn rule. Approval and review-free processing preserve the current submission until Apply or Cancel, unless a recovery returns the turn to the party. Rebase of a draft is unchanged.", + }, EnforcementLayer { id: "application-authorization", events: &["apply"], @@ -444,6 +724,109 @@ mod tests { TrustedActorRef, TrustedTimestamp, TrustedTransitionContext, }; + #[test] + fn proposal_status_and_turn_follow_the_exhaustive_lifecycle_table() { + use ProposalApplicationProgress as A; + use ProposalReviewProgress as R; + use ProposalState as S; + let mut rows = [0usize; 23]; + for state in [ + S::Draft, + S::Cancelled, + S::Applied, + S::Rejected, + S::Submitted, + ] { + for blocked in [false, true] { + for review in [ + R::NotRequired, + R::Pending, + R::Retrying, + R::Failed, + R::Approved, + R::ApprovalExpired, + R::Rejected, + R::ChangesRequested, + R::Answered, + R::Ended, + ] { + for ask_open in [false, true] { + for application in [A::Manual, A::BlockedRetry, A::BlockedOther, A::Other] { + let expected = match state { + S::Draft => (0, "draft", "party"), + S::Cancelled => (1, "cancelled", "nobody"), + S::Applied => (2, "applied", "nobody"), + S::Rejected => (3, "rejected", "nobody"), + S::Submitted if blocked => (4, "awaiting-party", "party"), + S::Submitted => match review { + R::Pending if ask_open => (5, "awaiting-party", "party"), + R::Retrying if ask_open => (6, "awaiting-party", "party"), + R::Pending => (7, "in-review", "official"), + R::Retrying => (8, "in-review", "official"), + R::Failed => (9, "awaiting-party", "party"), + R::ApprovalExpired => (10, "awaiting-party", "party"), + R::Rejected => (11, "awaiting-party", "party"), + R::ChangesRequested => (12, "awaiting-party", "party"), + R::Answered => (13, "awaiting-party", "party"), + R::Ended => (14, "awaiting-party", "party"), + R::Approved => match application { + A::Manual => (15, "approved", "official"), + A::BlockedRetry => (16, "approved", "official"), + A::BlockedOther => (17, "awaiting-party", "party"), + A::Other => (18, "approved", "nobody"), + }, + R::NotRequired => match application { + A::Manual => (19, "processing", "official"), + A::BlockedRetry => (20, "processing", "official"), + A::BlockedOther => (21, "awaiting-party", "party"), + A::Other => (22, "processing", "nobody"), + }, + }, + }; + let context = ProposalTurnContext { + submission_blocked: blocked, + review, + ask_open, + application, + }; + let (status, turn) = proposal_status_and_turn(state, context); + rows[expected.0] += 1; + assert_eq!( + (status.as_str(), turn.as_str()), + (expected.1, expected.2), + "{state:?} {context:?}" + ); + assert_eq!(proposal_turn(state, context), turn); + assert_eq!( + turn.as_str() == "party", + matches!(status.as_str(), "draft" | "awaiting-party") + ); + for terminal in ["applied", "rejected", "cancelled"] { + assert_eq!( + status.as_str() == terminal, + proposal_state_id(state) == terminal + ); + } + if status.as_str() == "approved" { + assert_eq!(review, R::Approved); + } + if status.as_str() == "in-review" { + assert_eq!(turn.as_str(), "official"); + } + if matches!(status.as_str(), "approved" | "processing") { + assert!(matches!(turn.as_str(), "official" | "nobody")); + } + } + } + } + } + } + assert!( + rows.into_iter().all(|count| count > 0), + "all 23 rows are exercised" + ); + } + #[test] fn retry_names_the_runtime_recovery_reasons() { let lifecycle = proposal_lifecycle(); @@ -491,6 +874,7 @@ mod tests { ProposalTurnContext { submission_blocked, review, + ask_open: false, application, }, ) diff --git a/crates/registry-breg/src/model.rs b/crates/registry-breg/src/model.rs index 60771d351c..82d97d19da 100644 --- a/crates/registry-breg/src/model.rs +++ b/crates/registry-breg/src/model.rs @@ -525,6 +525,8 @@ pub struct CompiledProposalPolicy { pub retention: CompiledProposalRetentionMode, pub review_context: Option, pub attachments: BTreeMap, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub additions: Option, /// Proposal files that applied effects reference from record slots, in /// effect order. #[serde(default, skip_serializing_if = "Vec::is_empty")] diff --git a/crates/registry-breg/src/mutation.rs b/crates/registry-breg/src/mutation.rs index cfc932da6e..afd08be12e 100644 --- a/crates/registry-breg/src/mutation.rs +++ b/crates/registry-breg/src/mutation.rs @@ -9,7 +9,8 @@ pub(crate) use action::validate_action_attachments; pub(crate) use action::{HookChangeApplication, HookChangeOutcome}; mod proposal; pub(crate) use proposal::{ - proposal_operation_name, CheckedProposalTaskAuthority, ProposalApplyPreflight, + link_readable, proposal_http_method, proposal_operation_name, CheckedProposalTaskAuthority, + ProposalApplyPreflight, ProposalReadDisclosure, }; pub(crate) use proposal::{PUBLIC_REASON_REFERENCE, REVIEW_PROGRESS_REFERENCE}; mod timer; @@ -2381,6 +2382,36 @@ impl std::fmt::Debug for ProposalGuardFailure { } } +/// Party recovery for a refusal after admission of an exact frozen application. +/// Only facts about the frozen data block the Proposal. A write outside the +/// applying caller's row boundary is a fact about that caller: it refuses the +/// call and records nothing, so a caller whose boundary covers the result can +/// still Apply. +#[derive(Clone, Copy)] +pub(crate) enum ApplicationRefusal { + Rebase, + Revise, +} + +impl ApplicationRefusal { + pub(crate) fn for_error(error: &MutationError) -> Option { + match error { + MutationError::ProposalTargetChanged | MutationError::ProposalGuardFailed(_) => { + Some(Self::Rebase) + } + MutationError::ProposalUniqueConflict => Some(Self::Revise), + _ => None, + } + } + + pub(crate) fn storage_code(self) -> &'static str { + match self { + Self::Rebase => "application-rebase", + Self::Revise => "application-refused", + } + } +} + #[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] pub enum MutationError { #[error("mutation request is invalid")] @@ -2405,6 +2436,10 @@ pub enum MutationError { WriteOutsideBoundary, #[error("mutation precondition failed")] PreconditionFailed, + /// An admitted frozen application found a changed target. It keeps the + /// ordinary precondition problem, but records Rebase as its recovery. + #[error("mutation precondition failed")] + ProposalTargetChanged, /// Internal cause only. HTTP must retain the generic precondition refusal /// unless a fresh, ordinary authorized GET safely confirms the failed guard. #[error("mutation precondition failed")] @@ -2430,6 +2465,14 @@ pub enum MutationError { /// write-once, so a second write is refused whatever its bytes are. #[error("the record attachment slot already holds a file")] AttachmentSlotWriteOnce, + #[error("the supporting document slot has reached its file limit")] + AttachmentLimitReached, + #[error("the required attachment slot is empty")] + AttachmentRequired { slot: String }, + #[error("the attachment is awaiting verification")] + AttachmentVerificationPending { slot: String }, + #[error("the attachment was rejected by verification")] + AttachmentVerificationRejected { slot: String }, /// A file is larger than its attachment slot's `maximumBytes`. #[error("the file is larger than the attachment slot accepts")] AttachmentTooLarge, @@ -2510,12 +2553,17 @@ impl MutationError { | Self::InvalidRequestAt(_) | Self::InvalidTimerWindow { .. } | Self::PreconditionFailed + | Self::ProposalTargetChanged | Self::ProposalReviewResultMismatch | Self::Conflict | Self::ProposalUniqueConflict | Self::ProposalRejected | Self::AttachmentSlotWriteOnce | Self::AttachmentTooLarge + | Self::AttachmentLimitReached + | Self::AttachmentRequired { .. } + | Self::AttachmentVerificationPending { .. } + | Self::AttachmentVerificationRejected { .. } | Self::AttachmentContentType | Self::AttachmentDigestMismatch | Self::IdempotencyConflict diff --git a/crates/registry-breg/src/mutation/proposal.rs b/crates/registry-breg/src/mutation/proposal.rs index 3107d49bc1..cf3e4049b4 100644 --- a/crates/registry-breg/src/mutation/proposal.rs +++ b/crates/registry-breg/src/mutation/proposal.rs @@ -2,11 +2,15 @@ //! Revision-fenced durable Proposal transitions over one frozen neutral plan. use super::*; +mod additions; +mod asks; +pub(crate) use asks::ProposalReadDisclosure; mod context_projection; use crate::api::proposals::ProposalMutationInput; use crate::lifecycle::{ - proposal_turn as evaluate_proposal_turn, ProposalApplicationProgress, ProposalReviewProgress, - ProposalTurn, ProposalTurnContext, + proposal_status_and_turn, ProposalApplicationProgress, ProposalAvailability, + ProposalLinkRecovery as LinkRecovery, ProposalLinkRefusal as LinkRefusal, + ProposalReviewProgress, ProposalStatus, ProposalTurn, ProposalTurnContext, }; use crate::model::{ CompiledActionExecution, CompiledProposalReview, ProposalOperation, ProposalOwnership, @@ -106,34 +110,97 @@ fn validate_attachment_authority( let CompiledActionExecution::Proposal { proposal } = &action.execution else { return Err(MutationError::InvalidRequest); }; + let operation = match authority.operation { + ProposalAuthorityOperation::Lifecycle( + operation @ (ProposalOperation::Edit | ProposalOperation::Add), + ) => operation, + _ => return Err(MutationError::InvalidRequest), + }; let grant = proposal .permissions .iter() .find(|grant| { grant.profile_id == authority.common.access_profile() - && grant.operations.contains(&ProposalOperation::Edit) + && grant.operations.contains(&operation) }) .ok_or(MutationError::PreconditionFailed)?; - let slot = proposal - .attachments - .get(&attachment.slot_id) - .ok_or(MutationError::PreconditionFailed)?; - if !grant.writable_attachments.contains(&slot.id) { + let (maximum_bytes, content_types) = if operation == ProposalOperation::Add { + let slot = proposal + .additions + .as_ref() + .filter(|slot| slot.id == attachment.slot_id) + .ok_or(MutationError::PreconditionFailed)?; + (slot.maximum_bytes, &slot.content_types) + } else { + let slot = proposal + .attachments + .get(&attachment.slot_id) + .ok_or(MutationError::PreconditionFailed)?; + (slot.maximum_bytes, &slot.content_types) + }; + if !grant.writable_attachments.contains(&attachment.slot_id) { return Err(MutationError::PreconditionFailed); } match (&attachment.content_type, &attachment.bytes) { (Some(content_type), Some(bytes)) if !bytes.is_empty() - && bytes.len() <= slot.maximum_bytes as usize - && slot.content_types.contains(content_type) => + && bytes.len() <= maximum_bytes as usize + && content_types.contains(content_type) => { Ok(()) } - (None, None) => Ok(()), + (None, None) if operation == ProposalOperation::Edit => Ok(()), _ => Err(MutationError::InvalidRequest), } } +async fn ensure_additions_open( + tx: &Transaction<'_>, + document: &ProposalDocument, + workflow: &crate::proposal_workflow::ProposalWorkflow, +) -> Result<(), MutationError> { + if document.header.state != "submitted" || document.blocked_reason.is_some() { + return Err(MutationError::PreconditionFailed); + } + let frozen = workflow + .current_proposal() + .ok_or(MutationError::PreconditionFailed)?; + if !matches!( + review_progress(tx, document, frozen).await?, + ProposalReviewProgress::Pending | ProposalReviewProgress::Retrying + ) { + return Err(MutationError::PreconditionFailed); + } + Ok(()) +} + +async fn check_addition_count( + tx: &Transaction<'_>, + action: &CompiledAction, + document: &ProposalDocument, +) -> Result<(), MutationError> { + let CompiledActionExecution::Proposal { proposal } = &action.execution else { + return Err(MutationError::InvalidRequest); + }; + let slot = proposal + .additions + .as_ref() + .ok_or(MutationError::PreconditionFailed)?; + if crate::attachment_store::additions::count( + tx, + &action.id, + document.proposal_id, + document.header.submission_version, + &slot.id, + ) + .await? + >= u64::from(slot.maximum_count) + { + return Err(MutationError::AttachmentLimitReached); + } + Ok(()) +} + /// Refuse a value for an input outside the grant's `writableInputs`. Start /// has no base, so any value is refused; Edit, Revise and Rebase must restate /// each fixed input exactly as `base` holds it. A grant without @@ -186,6 +253,8 @@ pub(crate) fn proposal_operation_name(operation: ProposalAuthorityOperation) -> ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get) => "get", ProposalAuthorityOperation::Lifecycle(ProposalOperation::List) => "list", ProposalAuthorityOperation::Lifecycle(ProposalOperation::Edit) => "edit", + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Add) => "add", + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Answer) => "answer", ProposalAuthorityOperation::Lifecycle(ProposalOperation::Submit) => "submit", ProposalAuthorityOperation::Lifecycle(ProposalOperation::Revise) => "revise", ProposalAuthorityOperation::Lifecycle(ProposalOperation::Cancel) => "cancel", @@ -208,6 +277,9 @@ pub(crate) fn proposal_operation_name(operation: ProposalAuthorityOperation) -> } pub(crate) fn proposal_http_method(input: &ProposalMutationInput<'_>) -> HttpMethod { + if input.operation == ProposalAuthorityOperation::Lifecycle(ProposalOperation::Add) { + return HttpMethod::Post; + } match &input.attachment { Some(attachment) if attachment.bytes.is_some() => HttpMethod::Patch, Some(_) => HttpMethod::Delete, @@ -238,15 +310,17 @@ fn validate_recovery_actor( } impl MutationTransaction { - /// Carry a review result just recorded for one submission into the + /// Carry a review result or newly opened ask for one submission into the /// Proposal lifecycle, in the transaction that recorded it. A rejection /// of the current submission ends the Proposal in `rejected`; a /// changes-requested result leaves it submitted and revisable and records - /// `review-returned`. Any other result, or a result for a submission that + /// `review-returned`. A new open ask bumps the revision and records `asked`. + /// A mirrored ask state change bumps the revision without a lifecycle event. + /// Any other result, or an observation for a submission that /// is no longer current, changes nothing. The caller holds the Proposal's /// state row lock. #[allow(clippy::too_many_arguments)] - pub(crate) async fn record_review_result( + pub(crate) async fn record_review_change( &self, tx: &Transaction<'_>, registry: &CompiledRegistry, @@ -257,6 +331,8 @@ impl MutationTransaction { status: &str, ) -> Result<(), MutationError> { let transition = match status { + "ask-state-changed" => "ask-state-changed", + "asked" => "asked", "rejected" => "rejected", "changes-requested" => "review-returned", _ => return Ok(()), @@ -269,16 +345,24 @@ impl MutationTransaction { return Ok(()); } let mut workflow = proposal_store::load(tx, action_id, proposal_id, false).await?; - if transition == "rejected" { + if matches!(transition, "rejected" | "asked" | "ask-state-changed") { let previous = i64::try_from(workflow.workflow_revision().get()) .map_err(|_| MutationError::Unavailable)?; let actor = self.proposal_actor(&format!("review-authority:{authority}"))?; - workflow = workflow - .reject(transition_context(&actor)?) - .map_err(workflow_error)? - .into_workflow(); + workflow = if transition == "ask-state-changed" { + workflow.record_ask_change(transition_context(&actor)?) + } else if transition == "asked" { + workflow.record_ask(transition_context(&actor)?) + } else { + workflow.reject(transition_context(&actor)?) + } + .map_err(workflow_error)? + .into_workflow(); proposal_store::save(tx, action_id, proposal_id, previous, &workflow).await?; } + if transition == "ask-state-changed" { + return Ok(()); + } let document = proposal_store::load_document(tx, proposal_id, proposal_store::DocumentLock::None) .await?; @@ -353,7 +437,11 @@ impl MutationTransaction { let Some(bytes) = &attachment.bytes else { return Ok(()); }; - if input.operation != ProposalAuthorityOperation::Lifecycle(ProposalOperation::Edit) { + let adding = + input.operation == ProposalAuthorityOperation::Lifecycle(ProposalOperation::Add); + if !adding + && input.operation != ProposalAuthorityOperation::Lifecycle(ProposalOperation::Edit) + { return Err(MutationError::InvalidRequest); } let action = proposal_action(registry, input.action_id)?; @@ -386,7 +474,7 @@ impl MutationTransaction { if document.header.state == "rejected" { return Err(MutationError::ProposalRejected); } - if document.header.state != "draft" + if document.header.state != if adding { "submitted" } else { "draft" } || document.blocked_reason.is_some() || document.header.current_proposal_erased || document.action_revision != action.definition_revision @@ -395,6 +483,11 @@ impl MutationTransaction { { return Err(MutationError::PreconditionFailed); } + if adding { + let workflow = proposal_store::load(tx, &action.id, id, false).await?; + ensure_additions_open(tx, &document, &workflow).await?; + check_addition_count(tx, action, &document).await?; + } check_current_proposal_grant(input.authority)?; crate::attachment_store::stage_external( tx, @@ -456,6 +549,29 @@ impl MutationTransaction { count: usize, field_set_reference: Option<&'static str>, correlation: &RequestCorrelation, + ) -> Result<(), MutationError> { + self.finish_proposal_read_audit_detail( + authority, + method, + document, + count, + ProposalReadDisclosure { + field_set_reference, + ..Default::default() + }, + correlation, + ) + .await + } + + pub(crate) async fn finish_proposal_read_audit_detail( + &self, + authority: &ProposalAuthority, + method: HttpMethod, + document: Option<&ProposalDocument>, + count: usize, + disclosure: ProposalReadDisclosure, + correlation: &RequestCorrelation, ) -> Result<(), MutationError> { let reference = document .map(|document| { @@ -492,10 +608,11 @@ impl MutationTransaction { result_count: Some(count), // Optional review disclosures use fixed markers; their // released values never reach the journal. - field_set_reference: field_set_reference.map(str::to_owned), + field_set_reference: disclosure.field_set_reference.map(str::to_owned), correlation: correlation.clone(), }, )?; + let entry = disclosure.annotate(entry, correlation); self.audit .append(entry) .await @@ -575,13 +692,28 @@ impl MutationTransaction { proposal_operation_name(input.operation) ), }; + if let Some(answer) = &input.answer { + route = format!( + "/v1/proposals/{}/asks/{}/answer", + input.proposal_id.ok_or(MutationError::InvalidRequest)?, + answer.ask_id + ); + } let method = if let Some(attachment) = &input.attachment { route = format!( - "/v1/proposals/{}/attachments/{}", + "/v1/proposals/{}/{}/{}", input.proposal_id.ok_or(MutationError::InvalidRequest)?, + if input.operation == ProposalAuthorityOperation::Lifecycle(ProposalOperation::Add) + { + "additions" + } else { + "attachments" + }, attachment.slot_id ); - if attachment.bytes.is_some() { + if input.operation == ProposalAuthorityOperation::Lifecycle(ProposalOperation::Add) { + HttpMethod::Post + } else if attachment.bytes.is_some() { HttpMethod::Patch } else { HttpMethod::Delete @@ -601,9 +733,14 @@ impl MutationTransaction { if let Some(writable_inputs)=&permission.writable_inputs { contract["writableInputs"]=json!(writable_inputs); } + // A receipt holds the inputs a Get served, so narrowing them refuses the old key + // instead of replaying a withheld value. Bound only when non-empty, as above. + if !permission.readable_inputs.is_empty() { + contract["readableInputs"]=json!(permission.readable_inputs); + } contract }); - let digest=Sha256::digest(canonicalize_json(&json!({ + let mut canonical_request = json!({ "proposalId":input.proposal_id,"operation":proposal_operation_name(input.operation), "ifMatch":input.expected_etag,"input":input.input,"submissionVersion":input.submission_version, "effectDigest":input.effect_digest,"reason":input.reason, @@ -611,7 +748,14 @@ impl MutationTransaction { "attachment":input.attachment.as_ref().map(|attachment|json!({"slot":attachment.slot_id, "contentType":attachment.content_type,"sha256":attachment.sha256(), "byteSize":attachment.bytes.as_ref().map(Vec::len)})), - })).map_err(|_|MutationError::InvalidRequest)?).into(); + }); + if let Some(answer) = &input.answer { + canonical_request["answer"] = json!(answer); + } + let digest = Sha256::digest( + canonicalize_json(&canonical_request).map_err(|_| MutationError::InvalidRequest)?, + ) + .into(); Ok(resolve_action_binding( self.audit.profile(), &self.idempotency, @@ -730,6 +874,18 @@ impl MutationTransaction { registry: &CompiledRegistry, document: &ProposalDocument, authority: &ProposalAuthority, + ) -> Result<(), MutationError> { + self.check_proposal_document(tx, registry, document, authority, true) + .await + } + + async fn check_proposal_document( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + document: &ProposalDocument, + authority: &ProposalAuthority, + lock_targets: bool, ) -> Result<(), MutationError> { let action = proposal_action(registry, &document.action_id)?; if let Some(check) = proposal_document_refusal( @@ -808,17 +964,18 @@ impl MutationTransaction { ) .await .map_err(target_install_error)?; - let lock = !matches!( - authority.operation, - ProposalAuthorityOperation::Lifecycle( - ProposalOperation::Get - | ProposalOperation::List - | ProposalOperation::GetReviewContext - | ProposalOperation::GetTaskGrantContext - | ProposalOperation::GetReviewStatus - | ProposalOperation::GetApplicationActor - ) - ); + let lock = lock_targets + && !matches!( + authority.operation, + ProposalAuthorityOperation::Lifecycle( + ProposalOperation::Get + | ProposalOperation::List + | ProposalOperation::GetReviewContext + | ProposalOperation::GetTaskGrantContext + | ProposalOperation::GetReviewStatus + | ProposalOperation::GetApplicationActor + ) + ); let row = load_proposal_row(tx, entity, *id, lock).await?; if !authority .authorizes_snapshot(entity, *id, &row.data) @@ -955,6 +1112,7 @@ impl MutationTransaction { TerminalAuditOutcome::Replayed, 0, &[], + replayed_public_reason(stored.response.body())?, )?; check_current_proposal_grant(input.authority)?; guarded @@ -1163,6 +1321,7 @@ impl MutationTransaction { TerminalAuditOutcome::Replayed, 0, &[], + replayed_public_reason(stored.response.body())?, )?; check_current_proposal_grant(input.authority)?; guarded @@ -1234,6 +1393,20 @@ impl MutationTransaction { if workflow.state() == crate::proposal_workflow::ProposalState::Rejected { return Err(MutationError::ProposalRejected); } + if workflow.state() == ProposalState::Submitted + && matches!( + operation, + ProposalOperation::Revise | ProposalOperation::Rebase + ) + && !matches!( + current_status_and_turn(tx, document, workflow.current_proposal()) + .await? + .0, + ProposalStatus::AwaitingParty | ProposalStatus::InReview + ) + { + return Err(MutationError::PreconditionFailed); + } if !matches!( operation, ProposalOperation::Cancel | ProposalOperation::Rebase @@ -1258,7 +1431,10 @@ impl MutationTransaction { } else { document.action_revision == action.definition_revision }; - if document.blocked_reason.is_some() || !compatible { + if (document.blocked_reason.is_some() + && !(operation == ProposalOperation::Revise && application_block(document))) + || !compatible + { return Err(MutationError::PreconditionFailed); } } @@ -1266,12 +1442,123 @@ impl MutationTransaction { .map_err(|_| MutationError::Unavailable)?; let context = transition_context(&actor)?; let (workflow, transition) = match operation { + ProposalOperation::Answer => { + if workflow.state() != ProposalState::Submitted { + return Err(MutationError::PreconditionFailed); + } + let frozen = workflow + .current_proposal() + .ok_or(MutationError::PreconditionFailed)?; + if !matches!( + review_progress(tx, document, frozen).await?, + ProposalReviewProgress::Pending | ProposalReviewProgress::Retrying + ) { + return Err(MutationError::PreconditionFailed); + } + self.commit_ask_answer( + tx, + document, + input.answer.as_ref().ok_or(MutationError::InvalidRequest)?, + &actor, + ) + .await?; + let workflow = workflow + .record_answer(context) + .map_err(workflow_error)? + .into_workflow(); + proposal_store::save(tx, &action.id, id, previous, &workflow).await?; + (workflow, "answered") + } + ProposalOperation::Add => { + ensure_additions_open(tx, document, &workflow).await?; + check_addition_count(tx, action, document).await?; + let attachment = input + .attachment + .as_ref() + .ok_or(MutationError::InvalidRequest)?; + validate_attachment_authority(action, input.authority, attachment)?; + let (Some(content_type), Some(bytes)) = + (&attachment.content_type, &attachment.bytes) + else { + return Err(MutationError::InvalidRequest); + }; + let CompiledActionExecution::Proposal { proposal } = &action.execution + else { + return Err(MutationError::InvalidRequest); + }; + let slot = proposal + .additions + .as_ref() + .ok_or(MutationError::PreconditionFailed)?; + let hash = crate::attachment_store::content_hash(bytes); + crate::attachment_store::additions::prepare_put( + tx, + &hash, + &self.attachment_storage.binding_digest(), + &self.attachment_verification.binding_digest(), + ) + .await?; + if let crate::attachment_storage::AttachmentStorage::S3(store) = + &self.attachment_storage + { + crate::attachment_store::require_backend( + tx, + &hash, + &self.attachment_storage.binding_digest(), + bytes.len() as u64, + ) + .await?; + check_current_proposal_grant(input.authority)?; + store + .put(&hash, bytes.clone()) + .await + .map_err(|_| MutationError::Unavailable)?; + } + crate::attachment_store::additions::put( + tx, + &action.id, + id, + document.header.submission_version, + &slot.id, + content_type, + bytes, + &actor, + &self.attachment_storage.binding_digest(), + &self.attachment_verification.binding_digest(), + slot.maximum_count, + ) + .await?; + let workflow = workflow + .record_addition(context) + .map_err(workflow_error)? + .into_workflow(); + proposal_store::save(tx, &action.id, id, previous, &workflow).await?; + (workflow, "added") + } ProposalOperation::Submit => { + if workflow.state() != ProposalState::Draft { + return Err(MutationError::PreconditionFailed); + } let values = document .input .as_ref() .ok_or(MutationError::PreconditionFailed)?; proposal_prepare::validate_inputs(action, values)?; + let CompiledActionExecution::Proposal { proposal: policy } = + &action.execution + else { + return Err(MutationError::InvalidRequest); + }; + self.verify_proposal_attachment_binding(tx).await?; + let attachments = crate::attachment_store::submission_manifest( + tx, + &action.id, + id, + document.header.submission_version, + &policy.attachments, + ) + .await?; + let values = values.clone(); let trusted_now = time::OffsetDateTime::now_utc(); let evaluation_date = crate::action_handler::trusted_evaluation_date( @@ -1363,27 +1650,6 @@ impl MutationTransaction { bases, guards, )?; - let CompiledActionExecution::Proposal { proposal: policy } = - &action.execution - else { - return Err(MutationError::InvalidRequest); - }; - self.verify_proposal_attachment_binding(tx).await?; - let attachments = crate::attachment_store::manifest( - tx, - &action.id, - id, - document.header.submission_version, - ) - .await?; - if policy.attachments.iter().any(|(slot, definition)| { - definition.required && !attachments.contains_key(slot) - }) || attachments - .keys() - .any(|slot| !policy.attachments.contains_key(slot)) - { - return Err(MutationError::PreconditionFailed); - } prepared.proposal = prepared .proposal .with_attachments(attachments) @@ -1544,6 +1810,9 @@ impl MutationTransaction { crate::review_store::close_application_jobs(tx, &action.id, id).await?; } proposal_store::save(tx, &action.id, id, previous, &workflow).await?; + if operation == ProposalOperation::Revise && application_block(document) { + proposal_store::clear_rebase_block(tx, &action.id, id).await?; + } if operation == ProposalOperation::Rebase { let start = input .rebase_start_authority @@ -1741,30 +2010,30 @@ impl MutationTransaction { ) .await?; proposal_prepare::validate_frozen_targets(frozen, &targets)?; - self.lock_frozen_scope( - tx, - registry, - action, - document, - input.authority, - frozen, - ) - .await?; - self.verify_frozen_guards( - tx, - registry, - action, - document, - input.authority, - frozen, - ) - .await?; let application_id = Uuid::new_v4(); tx.batch_execute("SAVEPOINT proposal_application_effects") .await .map_err(map_database_error)?; - let application = self - .apply_frozen_proposal( + let application = async { + self.lock_frozen_scope( + tx, + registry, + action, + document, + input.authority, + frozen, + ) + .await?; + self.verify_frozen_guards( + tx, + registry, + action, + document, + input.authority, + frozen, + ) + .await?; + self.apply_frozen_proposal( tx, registry, document, @@ -1775,7 +2044,9 @@ impl MutationTransaction { application_id, timer_staging.as_ref(), ) - .await; + .await + } + .await; match application { Ok((observed, links)) => { tx.batch_execute("RELEASE SAVEPOINT proposal_application_effects") @@ -1834,11 +2105,11 @@ impl MutationTransaction { ) .await .map_err(map_database_error)?; - if error == MutationError::ProposalUniqueConflict - && !input.authority.is_system() + if let Some(refusal) = ApplicationRefusal::for_error(&error) + .filter(|_| !input.authority.is_system()) { proposal_store::block_manual_application_refusal( - tx, &action.id, id, previous, + tx, &action.id, id, previous, refusal, ) .await?; terminal_error = Some(error); @@ -1869,6 +2140,7 @@ impl MutationTransaction { TerminalAuditOutcome::Refused, 0, &[], + ProposalReadDisclosure::default(), )?; if tokio::time::Instant::now() >= deadline { return Err(MutationError::Unavailable); @@ -1981,6 +2253,7 @@ impl MutationTransaction { TerminalAuditOutcome::Committed, result_count, &changed_inputs, + ProposalReadDisclosure::for_value(&value), )?; if tokio::time::Instant::now() >= deadline { return Err(MutationError::Unavailable); @@ -2055,6 +2328,7 @@ impl MutationTransaction { }) } + #[allow(clippy::too_many_arguments)] fn proposal_terminal( &self, input: &ProposalMutationInput<'_>, @@ -2063,6 +2337,7 @@ impl MutationTransaction { outcome: TerminalAuditOutcome, count: u16, changed_inputs: &[String], + disclosure: ProposalReadDisclosure, ) -> Result { let terminal = TerminalAudit { context: input.authority.common.audit_context().cloned(), @@ -2082,7 +2357,7 @@ impl MutationTransaction { record_reference: None, record_revision: None, result_count: Some(usize::from(count)), - field_set_reference: None, + field_set_reference: disclosure.field_set_reference.map(str::to_owned), correlation: input.correlation.clone(), }; let entry = if outcome == TerminalAuditOutcome::Refused { @@ -2108,6 +2383,10 @@ impl MutationTransaction { { record["changedInputs"] = json!(changed_inputs); } + if let Some(answer) = &input.answer { + record["reviewAskId"] = json!(answer.ask_id); + record["citedAdditionIds"] = json!(answer.body.additions); + } record["authorityKind"] = json!(if input.authority.is_system() { "system" } else { @@ -2116,10 +2395,13 @@ impl MutationTransaction { if let Some(revision) = input.authority.system_grant_revision() { record["systemApplyGrantRevision"] = json!(revision); } - Ok(registry_platform_audit::AuditEntry::response( - crate::audit::AUDIT_SCHEMA, - input.correlation.request_id().to_string(), - record, + Ok(disclosure.annotate( + registry_platform_audit::AuditEntry::response( + crate::audit::AUDIT_SCHEMA, + input.correlation.request_id().to_string(), + record, + ), + input.correlation, )) } @@ -2425,7 +2707,7 @@ impl MutationTransaction { .filter(|guard| guard.input == target.id) { if guard.revision_unchanged && row.record_revision != target.expected_revision { - return Err(MutationError::PreconditionFailed); + return Err(MutationError::ProposalTargetChanged); } let timestamp = entity.fields.get(&guard.field).is_some_and(|field| { matches!( @@ -2599,9 +2881,12 @@ impl MutationTransaction { let current = load_proposal_row(tx, entity, target.record_id, true).await?; if current.record_revision != revision || Some(¤t.data) != target.before.as_ref() - || !authority - .authorizes_snapshot(entity, target.record_id, ¤t.data) - .map_err(|_| MutationError::PreconditionFailed)? + { + return Err(MutationError::ProposalTargetChanged); + } + if !authority + .authorizes_snapshot(entity, target.record_id, ¤t.data) + .map_err(|_| MutationError::PreconditionFailed)? { return Err(MutationError::PreconditionFailed); } @@ -2620,7 +2905,7 @@ impl MutationTransaction { .authorizes_snapshot(entity, target.record_id, &target.after) .map_err(|_| MutationError::PreconditionFailed)? { - return Err(MutationError::PreconditionFailed); + return Err(MutationError::WriteOutsideBoundary); } authority .install_target( @@ -3272,6 +3557,7 @@ impl MutationTransaction { matches!( source, crate::contract::ProposalContextValueSource::Document { .. } + | crate::contract::ProposalContextValueSource::Additions { .. } ) }) }) { @@ -3290,6 +3576,24 @@ impl MutationTransaction { ) .await?, ); + // Answers are served to human reviewers of the current + // binding only; see `receives_review_answers`. + if authority.operation + == ProposalAuthorityOperation::Lifecycle(ProposalOperation::GetReviewContext) + && authority.receives_review_answers + && matches!( + frozen.review_requirement(), + CompiledProposalReview::Required { .. } + ) + { + let schema = value["context"]["contract"]["schemaDigest"] + .as_str() + .ok_or(MutationError::Unavailable)? + .to_owned(); + value["context"]["asks"] = self + .intrinsic_asks(tx, registry, document, authority, frozen, &schema) + .await?; + } } _ => return Err(MutationError::PreconditionFailed), } @@ -3333,15 +3637,21 @@ impl MutationTransaction { proposal_application_status(tx, document, proposal).await?; } } - value["turn"] = json!( - current_turn( - tx, - document, - workflow - .as_ref() - .and_then(|workflow| workflow.current_proposal()) - ) - .await? + let (status, turn) = current_status_and_turn( + tx, + document, + workflow + .as_ref() + .and_then(|workflow| workflow.current_proposal()), + ) + .await?; + value["turn"] = json!(turn.as_str()); + if claims.is_some() { + value["status"] = json!(status); + } + let can_change_submission = matches!( + status, + ProposalStatus::AwaitingParty | ProposalStatus::InReview ); if let Some(application) = workflow .as_ref() @@ -3355,18 +3665,50 @@ impl MutationTransaction { let Some(claims) = claims else { return Ok(value); }; - // The decision is disclosed on the reads only, beside the inputs the - // same Get authority discloses; a lifecycle command's response omits it. + // A command response discloses the decision, the hand-off refusal, + // the inputs and the attachments to a caller whose selected access + // profile holds Get authority on this Proposal: a command's authority + // is not read authority, so a profile without Get is served none of + // them. Reads serve the inputs and attachments the same way; a List + // item carries the decision under List authority. + let get_authority = match crate::api::proposals::authorize( + registry, + action, + claims, + Some(current.common.access_profile()), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), + Some(document.proposal_id), + ) { + Some(authority) => link_readable( + self.check_proposal_document(tx, registry, document, &authority, false) + .await, + )? + .then_some(authority), + None => None, + }; + if get_authority.is_some() { + self.append_public_asks( + tx, + registry, + document, + current, + claims, + workflow + .as_ref() + .and_then(|workflow| workflow.current_proposal()), + &mut value, + ) + .await?; + } + let is_read = matches!( + current.operation, + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get | ProposalOperation::List) + ); if document.header.state != "draft" && workflow .as_ref() .is_some_and(|workflow| workflow.current_proposal().is_some()) - && matches!( - current.operation, - ProposalAuthorityOperation::Lifecycle( - ProposalOperation::Get | ProposalOperation::List - ) - ) + && (is_read || get_authority.is_some()) { if let Some(decision) = review_decision( tx, @@ -3391,6 +3733,22 @@ impl MutationTransaction { } } } + if let Some(get_authority) = &get_authority { + let CompiledActionExecution::Proposal { proposal } = &action.execution else { + return Err(MutationError::InvalidRequest); + }; + if let Some(permission) = proposal + .permissions + .iter() + .find(|permission| permission.profile_id == get_authority.common.access_profile()) + { + if let Some(inputs) = + public_inputs(action, &permission.readable_inputs, document.input.as_ref()) + { + value["input"] = Value::Object(inputs); + } + } + } let review_refusal = match workflow .as_ref() .and_then(|workflow| workflow.current_proposal()) @@ -3410,6 +3768,40 @@ impl MutationTransaction { }, _ => false, }; + let attachment_refusal = if document.header.state == "draft" + && document.blocked_reason.is_none() + && document.action_revision == action.definition_revision + { + let CompiledActionExecution::Proposal { proposal } = &action.execution else { + return Err(MutationError::Unavailable); + }; + match crate::attachment_store::submission_manifest( + tx, + &document.action_id, + document.proposal_id, + document.header.submission_version, + &proposal.attachments, + ) + .await + { + Ok(_) => None, + Err(MutationError::AttachmentRequired { .. }) => { + Some(LinkRefusal::AttachmentRequired) + } + Err(MutationError::AttachmentVerificationPending { .. }) => { + Some(LinkRefusal::AttachmentPending) + } + Err(MutationError::AttachmentVerificationRejected { .. }) => { + Some(LinkRefusal::InvalidInput) + } + // A retained reference outside the current slot policy refuses + // Submit, without concealing the otherwise readable Proposal. + Err(MutationError::PreconditionFailed) => Some(LinkRefusal::WrongState), + Err(error) => return Err(error), + } + } else { + None + }; let retry_available = document.header.state == "submitted" && crate::review_store::submission_work_is_retryable( tx, @@ -3431,19 +3823,19 @@ impl MutationTransaction { ("reviewContext", ProposalOperation::GetReviewContext), ]; for (name, operation) in operations { - let profiles = std::iter::once(current.common.access_profile()); - let authority = profiles - .filter_map(|profile| { - crate::api::proposals::authorize( - registry, - action, - claims, - Some(profile), - ProposalAuthorityOperation::Lifecycle(operation), - Some(document.proposal_id), - ) - }) - .next(); + // The Get gate above already ran the document check for `self`. + let authority = if operation == ProposalOperation::Get { + get_authority.clone() + } else { + crate::api::proposals::authorize( + registry, + action, + claims, + Some(current.common.access_profile()), + ProposalAuthorityOperation::Lifecycle(operation), + Some(document.proposal_id), + ) + }; let Some(authority) = authority else { continue; }; @@ -3460,36 +3852,14 @@ impl MutationTransaction { { continue; } - if self - .authorize_proposal_document(tx, registry, document, &authority) - .await - .is_err() + if operation != ProposalOperation::Get + && !link_readable( + self.check_proposal_document(tx, registry, document, &authority, false) + .await, + )? { continue; } - if operation == ProposalOperation::Get - && matches!( - current.operation, - ProposalAuthorityOperation::Lifecycle( - ProposalOperation::Get | ProposalOperation::List - ) - ) - { - let CompiledActionExecution::Proposal { proposal } = &action.execution else { - return Err(MutationError::InvalidRequest); - }; - if let Some(permission) = proposal - .permissions - .iter() - .find(|permission| permission.profile_id == authority.common.access_profile()) - { - if let Some(inputs) = - public_inputs(action, &permission.readable_inputs, document.input.as_ref()) - { - value["input"] = Value::Object(inputs); - } - } - } let available = match operation { ProposalOperation::Get => true, ProposalOperation::Edit => { @@ -3499,14 +3869,17 @@ impl MutationTransaction { document.header.state == "draft" && document.blocked_reason.is_none() && review_available + && attachment_refusal.is_none() } ProposalOperation::Revise => { document.header.state == "submitted" - && document.blocked_reason.is_none() + && can_change_submission + && (document.blocked_reason.is_none() || application_block(document)) && document.action_revision == action.definition_revision } ProposalOperation::Rebase => { - matches!(document.header.state.as_str(), "draft" | "submitted") + document.header.state == "draft" + || document.header.state == "submitted" && can_change_submission } ProposalOperation::Retry => { document.header.state == "submitted" @@ -3534,6 +3907,7 @@ impl MutationTransaction { document.header.state != "draft" && !document.header.current_proposal_erased } ProposalOperation::GetApplicationActor => false, + ProposalOperation::Add | ProposalOperation::Answer => false, ProposalOperation::List => false, }; if !available @@ -3564,24 +3938,13 @@ impl MutationTransaction { proposal_operation_name(authority.operation) ), }; - let mut link = json!({"method":if matches!(operation,ProposalOperation::Get|ProposalOperation::GetReviewContext|ProposalOperation::GetReviewStatus){"GET"}else{"POST"}, - "path":path,"accessProfile":authority.common.access_profile(),"operation":proposal_operation_name(authority.operation), - "availability":{"available":available,"observedRevision":document.header.workflow_revision}}); - if !matches!( - operation, - ProposalOperation::Get - | ProposalOperation::GetReviewContext - | ProposalOperation::GetReviewStatus - ) { - link["ifMatch"] = json!(self.proposal_etag(document, &authority)?); - } - if !available { + let refusal = if available { + None + } else { if document.header.state == "applied" { - link["availability"]["reason"] = json!("already-applied"); - link["availability"]["recovery"] = json!("receipt-only"); + Some(LinkRefusal::AlreadyApplied) } else if document.header.state == "rejected" { - link["availability"]["reason"] = json!("review-rejected"); - link["availability"]["recovery"] = json!("receipt-only"); + Some(LinkRefusal::Rejected) } else if match operation { ProposalOperation::Edit | ProposalOperation::Submit => { document.header.state != "draft" @@ -3594,39 +3957,55 @@ impl MutationTransaction { } _ => false, } { - link["availability"]["reason"] = json!("stale-revision"); - link["availability"]["recovery"] = json!("receipt-only"); + Some(LinkRefusal::WrongState) + } else if matches!( + operation, + ProposalOperation::Revise | ProposalOperation::Rebase + ) && matches!( + status, + ProposalStatus::Approved | ProposalStatus::Processing + ) { + Some(LinkRefusal::ApplicationPending) } else if operation == ProposalOperation::Revise && document.action_revision != action.definition_revision { - link["availability"]["reason"] = json!("package-changed"); - link["availability"]["recovery"] = json!("rebase"); + Some(LinkRefusal::PackageChanged) } else if let Some(blocked_reason) = document.blocked_reason.as_deref() { - let (reason, recovery) = if blocked_reason == "application-refused" { - ("invalid-input", "correct-input") + let refusal = if blocked_reason == "application-refused" { + LinkRefusal::ReviseInput + } else if blocked_reason == "application-rebase" { + LinkRefusal::TargetChanged } else { - ("package-changed", "rebase") + LinkRefusal::PackageChanged }; - link["availability"]["reason"] = json!(reason); - link["availability"]["recovery"] = json!(recovery); + Some(refusal) } else if operation == ProposalOperation::Retry && !retry_available { // A review that has ended leaves nothing to retry: the // same review outcome Apply reports names Revise. - let (reason, recovery) = review_refusal - .filter(|(_, recovery)| *recovery == "revise") - .unwrap_or(("invalid-input", "correct-input")); - link["availability"]["reason"] = json!(reason); - link["availability"]["recovery"] = json!(recovery); + let refusal = review_refusal + .filter(|refusal| refusal.pair().1 == LinkRecovery::Revise) + .unwrap_or(LinkRefusal::InvalidInput); + Some(refusal) + } else if operation == ProposalOperation::Submit && attachment_refusal.is_some() { + attachment_refusal } else if !review_available { - link["availability"]["reason"] = json!("dependency-outage"); - link["availability"]["recovery"] = json!("retry"); - } else if let Some((reason, recovery)) = review_refusal { - link["availability"]["reason"] = json!(reason); - link["availability"]["recovery"] = json!(recovery); + Some(LinkRefusal::DependencyOutage) + } else if let Some(refusal) = review_refusal { + Some(refusal) } else { - link["availability"]["reason"] = json!("pending-review"); - link["availability"]["recovery"] = json!("refresh"); + Some(LinkRefusal::PendingReview) } + }; + let mut link = json!({"method":if matches!(operation,ProposalOperation::Get|ProposalOperation::GetReviewContext|ProposalOperation::GetReviewStatus){"GET"}else{"POST"}, + "path":path,"accessProfile":authority.common.access_profile(),"operation":proposal_operation_name(authority.operation), + "availability":ProposalAvailability::new(document.header.workflow_revision as u64, refusal)}); + if !matches!( + operation, + ProposalOperation::Get + | ProposalOperation::GetReviewContext + | ProposalOperation::GetReviewStatus + ) { + link["ifMatch"] = json!(self.proposal_etag(document, &authority)?); } value["links"][name] = link; } @@ -3638,14 +4017,8 @@ impl MutationTransaction { .iter() .find(|permission| permission.profile_id == current.common.access_profile()); if let Some(permission) = permission { - let read = crate::api::proposals::authorize( - registry, - action, - claims, - Some(current.common.access_profile()), - ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), - Some(document.proposal_id), - ); + // Attachments are Get-scoped like the inputs: the same gate decides them. + let read = get_authority.as_ref(); let write = crate::api::proposals::authorize( registry, action, @@ -3654,6 +4027,14 @@ impl MutationTransaction { ProposalAuthorityOperation::Lifecycle(ProposalOperation::Edit), Some(document.proposal_id), ); + let write = match write { + Some(authority) => link_readable( + self.check_proposal_document(tx, registry, document, &authority, false) + .await, + )? + .then_some(authority), + None => None, + }; let metadata = if read.is_some() && !permission.readable_attachments.is_empty() { crate::attachment_store::metadata( tx, @@ -3683,7 +4064,7 @@ impl MutationTransaction { if metadata.verification_status.permits_content() { descriptor["links"]["download"] = json!({"method":"GET","path":format!("{path}?submissionVersion={}",document.header.submission_version), "accessProfile":current.common.access_profile(),"operation":"download", - "availability":{"available":true,"observedRevision":document.header.workflow_revision}}); + "availability":ProposalAvailability::new(document.header.workflow_revision as u64, None)}); } } } @@ -3693,7 +4074,7 @@ impl MutationTransaction { let etag = self.proposal_etag(document, write)?; for (name, method) in [("upload", "PATCH"), ("remove", "DELETE")] { descriptor["links"][name] = json!({"method":method,"path":path,"accessProfile":current.common.access_profile(), - "ifMatch":etag,"operation":name,"availability":{"available":true,"observedRevision":document.header.workflow_revision}}); + "ifMatch":etag,"operation":name,"availability":ProposalAvailability::new(document.header.workflow_revision as u64, None)}); } } slots.insert(id.clone(), descriptor); @@ -3701,6 +4082,10 @@ impl MutationTransaction { if !slots.is_empty() { value["attachments"] = Value::Object(slots); } + self.append_additions( + tx, registry, action, document, current, claims, permission, read, &mut value, + ) + .await?; } Ok(value) } @@ -3894,6 +4279,8 @@ async fn proposal_application_status( ("dependency-outage", "retry") } Some("lease-expired") => ("lease-expired", "retry"), + Some("application-rebase") => ("application-refused", "rebase"), + Some("application-refused") => ("application-refused", "revise"), _ => ("application-refused", "correct-input"), }; value["reason"] = json!(reason); @@ -3905,8 +4292,15 @@ async fn proposal_application_status( /// The `applicationStatus` reason for a Proposal whose lifecycle row is /// blocked: a refused manual Apply is reported as such, any other block is a /// package change. +fn application_block(document: &ProposalDocument) -> bool { + matches!( + document.blocked_reason.as_deref(), + Some("application-refused" | "application-rebase") + ) +} + fn blocked_application_reason(document: &ProposalDocument) -> &'static str { - if document.blocked_reason.as_deref() == Some("application-refused") { + if application_block(document) { "application-refused" } else { "package-changed" @@ -3915,7 +4309,7 @@ fn blocked_application_reason(document: &ProposalDocument) -> &'static str { fn blocked_application_recovery(document: &ProposalDocument) -> &'static str { if document.blocked_reason.as_deref() == Some("application-refused") { - "correct-input" + "revise" } else { "rebase" } @@ -3992,16 +4386,16 @@ fn proposal_action<'a>( impl ProposalReviewProgress { /// The Apply availability a review that has not approved this /// submission gives. `None` for an approval or no review. - fn apply_refusal(self) -> Option<(&'static str, &'static str)> { + fn apply_refusal(self) -> Option { match self { Self::NotRequired | Self::Approved => None, - Self::Pending => Some(("pending-review", "refresh")), + Self::Pending => Some(LinkRefusal::PendingReview), // Retry resumes the delivery or lookup that failed. - Self::Retrying => Some(("dependency-outage", "retry")), - Self::Rejected => Some(("review-rejected", "revise")), - Self::ChangesRequested => Some(("review-changes-requested", "revise")), + Self::Retrying => Some(LinkRefusal::DependencyOutage), + Self::Rejected => Some(LinkRefusal::ReviewRejected), + Self::ChangesRequested => Some(LinkRefusal::ChangesRequested), Self::Failed | Self::ApprovalExpired | Self::Answered | Self::Ended => { - Some(("review-ended", "revise")) + Some(LinkRefusal::ReviewEnded) } } } @@ -4070,30 +4464,46 @@ pub(crate) async fn current_turn( document: &ProposalDocument, frozen: Option<&crate::proposal_workflow::ProposalSnapshot>, ) -> Result<&'static str, MutationError> { - let blocked = document.blocked_reason.is_some(); - if document.header.state != "submitted" { - return Ok(proposal_turn( - &document.header.state, - blocked, - ProposalReviewProgress::NotRequired, - &Value::Null, - )); - } - let frozen = frozen.ok_or(MutationError::PreconditionFailed)?; - let review = review_progress(tx, document, frozen).await?; - let application = proposal_application_status(tx, document, frozen).await?; - Ok(proposal_turn( - &document.header.state, - blocked, - review, - &application, - )) + let (state, context) = current_turn_context(tx, document, frozen).await?; + Ok(crate::lifecycle::proposal_turn(state, context).as_str()) +} + +async fn current_status_and_turn( + tx: &Transaction<'_>, + document: &ProposalDocument, + frozen: Option<&crate::proposal_workflow::ProposalSnapshot>, +) -> Result<(ProposalStatus, ProposalTurn), MutationError> { + let (state, context) = current_turn_context(tx, document, frozen).await?; + Ok(proposal_status_and_turn(state, context)) +} + +async fn current_turn_context( + tx: &Transaction<'_>, + document: &ProposalDocument, + frozen: Option<&crate::proposal_workflow::ProposalSnapshot>, +) -> Result<(ProposalState, ProposalTurnContext), MutationError> { + let state = ProposalState::from_storage(&document.header.state) + .map_err(|_| MutationError::Unavailable)?; + let (review, application) = if state == ProposalState::Submitted { + let frozen = frozen.ok_or(MutationError::PreconditionFailed)?; + ( + review_progress(tx, document, frozen).await?, + proposal_application_status(tx, document, frozen).await?, + ) + } else { + (ProposalReviewProgress::NotRequired, Value::Null) + }; + let mut context = + proposal_turn_context(document.blocked_reason.is_some(), review, &application); + context.ask_open = document.ask_open; + Ok((state, context)) } /// Whose move a Proposal waits on: the party that drives it, an official /// who reviews or applies it, or nobody. Derived from the lifecycle state, /// the current submission's review progress and its application status; /// nothing stores it. +#[cfg(test)] pub(crate) fn proposal_turn( state: &str, blocked: bool, @@ -4103,6 +4513,15 @@ pub(crate) fn proposal_turn( let Ok(state) = ProposalState::from_storage(state) else { return ProposalTurn::Nobody.as_str(); }; + crate::lifecycle::proposal_turn(state, proposal_turn_context(blocked, review, application)) + .as_str() +} + +fn proposal_turn_context( + blocked: bool, + review: ProposalReviewProgress, + application: &Value, +) -> ProposalTurnContext { let application = if application["mode"] == "manual" { ProposalApplicationProgress::Manual } else { @@ -4115,21 +4534,41 @@ pub(crate) fn proposal_turn( _ => ProposalApplicationProgress::Other, } }; - evaluate_proposal_turn( - state, - ProposalTurnContext { - submission_blocked: blocked, - review, - application, - }, - ) - .as_str() + ProposalTurnContext { + submission_blocked: blocked, + review, + ask_open: false, + application, + } } -/// The audit marker of a read that served a decision's public reason. +/// The audit marker of a response that served a decision's public reason: a +/// read, a command, or a command's replay. pub(crate) const PUBLIC_REASON_REFERENCE: &str = "proposal-review-public-reason"; pub(crate) const REVIEW_PROGRESS_REFERENCE: &str = "proposal-review-progress"; +/// Whether a Get-authority document check lets the caller read the Proposal. +/// Only the two refusals a Proposal read gives a caller who may not read it +/// withhold what Get serves. A conflict, a retryable conflict or any other +/// failure stays an error, so nobody takes a failure for a refusal that would +/// silently omit what the caller may read. +pub(crate) fn link_readable(outcome: Result<(), MutationError>) -> Result { + match outcome { + Ok(()) => Ok(true), + Err(MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed) => { + Ok(false) + } + Err(error) => Err(error), + } +} + +/// The audit marker a replay records when the stored response it serves +/// again holds a decision's public reason. +fn replayed_public_reason(body: &[u8]) -> Result { + let response: Value = serde_json::from_slice(body).map_err(|_| MutationError::Unavailable)?; + Ok(ProposalReadDisclosure::for_value(&response)) +} + /// Why the review authority refused one submission's hand-off for good, as /// the allowlisted code recorded when it refused. A hand-off still pending, /// accepted, retrying or withdrawn names no refusal, and neither does a diff --git a/crates/registry-breg/src/mutation/proposal/additions.rs b/crates/registry-breg/src/mutation/proposal/additions.rs new file mode 100644 index 0000000000..5ff58fe47a --- /dev/null +++ b/crates/registry-breg/src/mutation/proposal/additions.rs @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; + +impl MutationTransaction { + #[allow(clippy::too_many_arguments)] + pub(super) async fn append_additions( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + action: &CompiledAction, + document: &ProposalDocument, + current: &ProposalAuthority, + claims: &crate::api::VerifiedRequestClaims, + permission: &crate::model::CompiledProposalPermission, + read: Option<&ProposalAuthority>, + value: &mut Value, + ) -> Result<(), MutationError> { + let CompiledActionExecution::Proposal { proposal } = &action.execution else { + return Ok(()); + }; + let Some(slot) = &proposal.additions else { + return Ok(()); + }; + let readable = read.is_some() && permission.readable_attachments.contains(&slot.id); + let write = crate::api::proposals::authorize( + registry, + action, + claims, + Some(current.common.access_profile()), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Add), + Some(document.proposal_id), + ) + .filter(|_| permission.writable_attachments.contains(&slot.id)); + let write = match write { + Some(authority) => link_readable( + self.check_proposal_document(tx, registry, document, &authority, false) + .await, + )? + .then_some(authority), + None => None, + }; + if !readable && write.is_none() { + return Ok(()); + } + let metadata = crate::attachment_store::additions::metadata( + tx, + &action.id, + document.proposal_id, + document.header.submission_version, + &slot.id, + ) + .await?; + let mut descriptor = json!({"id":slot.id,"maximumBytes":slot.maximum_bytes,"maximumCount":slot.maximum_count, + "contentTypes":slot.content_types,"classification":slot.classification,"items":[],"links":{}}); + if readable { + let mut items = Vec::new(); + for addition in &metadata { + let file = &addition.file; + let mut item = json!({"id":addition.id,"submissionVersion":addition.submission_version, + "sha256":file.sha256,"byteSize":file.byte_size,"contentType":file.content_type, + "addedAt":file.uploaded_at,"verificationStatus":file.verification_status,"links":{}}); + if file.verification_status.permits_content() { + item["links"]["download"] = json!({"method":"GET", + "path":format!("/v1/proposals/{}/additions/{}?submissionVersion={}", document.proposal_id, addition.id, addition.submission_version), + "accessProfile":current.common.access_profile(),"operation":"download", + "availability":ProposalAvailability::new(document.header.workflow_revision as u64, None)}); + } + items.push(item); + } + descriptor["items"] = json!(items); + } + if let Some(write) = write { + let workflow = if document.header.state == "submitted" + && !document.header.current_proposal_erased + { + Some(proposal_store::load(tx, &action.id, document.proposal_id, false).await?) + } else { + None + }; + let progress = match workflow + .as_ref() + .and_then(|workflow| workflow.current_proposal()) + { + Some(frozen) => review_progress(tx, document, frozen).await?, + None => ProposalReviewProgress::NotRequired, + }; + let refusal = if document.header.state == "applied" { + Some(LinkRefusal::AlreadyApplied) + } else if document.header.state == "rejected" { + Some(LinkRefusal::Rejected) + } else if document.header.state != "submitted" + || document.header.current_proposal_erased + { + Some(LinkRefusal::WrongState) + } else if metadata.len() > slot.maximum_count as usize { + // Retained files remain visible after a lower current limit. + Some(LinkRefusal::LimitReached) + } else if document.blocked_reason.as_deref() == Some("application-refused") { + Some(LinkRefusal::ReviseInput) + } else if document.blocked_reason.as_deref() == Some("application-rebase") { + Some(LinkRefusal::TargetChanged) + } else if document.blocked_reason.is_some() + || document.action_revision != action.definition_revision + { + Some(LinkRefusal::PackageChanged) + } else if !matches!( + progress, + ProposalReviewProgress::Pending | ProposalReviewProgress::Retrying + ) { + Some(match progress { + ProposalReviewProgress::Rejected => LinkRefusal::ReviewRejected, + ProposalReviewProgress::ChangesRequested => LinkRefusal::ChangesRequested, + _ => LinkRefusal::ReviewEnded, + }) + } else if metadata.len() >= slot.maximum_count as usize { + Some(LinkRefusal::LimitReached) + } else { + None + }; + let link = json!({"method":"POST","path":format!("/v1/proposals/{}/additions/{}",document.proposal_id,slot.id), + "accessProfile":write.common.access_profile(),"operation":"add","ifMatch":self.proposal_etag(document,&write)?, + "availability":ProposalAvailability::new(document.header.workflow_revision as u64, refusal)}); + descriptor["links"]["add"] = link; + } + value["additions"] = json!({slot.id.clone():descriptor}); + Ok(()) + } +} diff --git a/crates/registry-breg/src/mutation/proposal/asks.rs b/crates/registry-breg/src/mutation/proposal/asks.rs new file mode 100644 index 0000000000..ecb1574d5a --- /dev/null +++ b/crates/registry-breg/src/mutation/proposal/asks.rs @@ -0,0 +1,369 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Local answers are committed atomically with their revision and delivery job. +use super::*; +use crate::problem_location::RequestLocation; +use crate::review_store::asks::{answer_time, AnswerMutation}; +use chrono::{DateTime, Utc}; +use registry_platform_authcommon::FailedCheck; + +impl MutationTransaction { + pub(super) async fn commit_ask_answer( + &self, + tx: &Transaction<'_>, + document: &ProposalDocument, + answer: &AnswerMutation, + actor: &str, + ) -> Result<(), MutationError> { + let row = tx.query_opt( + "SELECT a.authority,a.review_request_id,a.wants,a.asked_at_wire,a.due_at_wire,a.state, + s.producer_id, EXISTS(SELECT 1 FROM registry_internal.registry_proposal_review_ask_answers x + WHERE x.authority=a.authority AND x.review_request_id=a.review_request_id AND x.ask_id=a.ask_id) + FROM registry_internal.registry_proposal_review_asks a + JOIN registry_internal.registry_proposal_review_submissions s USING(action_id,proposal_id,submission_version) + WHERE a.action_id=$1 AND a.proposal_id=$2 AND a.submission_version=$3 AND a.ask_id=$4 + AND a.detail_erased_at IS NULL AND NOT s.withdrawn AND s.state='accepted' + AND s.authority=a.authority AND s.accepted_binding->>'requestId'=a.review_request_id::text", + &[&document.action_id,&document.proposal_id,&document.header.submission_version,&answer.ask_id] + ).await.map_err(map_database_error)?.ok_or(MutationError::AuthorizationRefused(FailedCheck::Visibility))?; + let now = Utc::now(); + let due = row + .get::<_, Option>(4) + .map(|at| { + at.parse::>() + .map_err(|_| MutationError::Unavailable) + }) + .transpose()?; + if row.get::<_, String>(5) != "open" + || row.get::<_, bool>(7) + || due.is_some_and(|at| at <= now) + { + return Err(MutationError::PreconditionFailed); + } + let wants: Vec = + serde_json::from_value(row.get(2)).map_err(|_| MutationError::Unavailable)?; + answer.body.validate(&wants).map_err(|field| { + MutationError::InvalidRequestAt(if field == "text" { + RequestLocation::proposal_answer_text() + } else { + RequestLocation::proposal_answer_additions() + }) + })?; + let asked: DateTime = row + .get::<_, String>(3) + .parse() + .map_err(|_| MutationError::Unavailable)?; + let answered_at = answer_time(now, asked).ok_or(MutationError::Unavailable)?; + if due.is_some_and(|at| answered_at > at) { + return Err(MutationError::PreconditionFailed); + } + let authority: String = row.get(0); + let request: Uuid = row.get(1); + let producer: String = row.get(6); + let configured = self + .review_authorities + .as_ref() + .filter(|configured| configured.contains_binding(&authority, &producer)) + .ok_or(MutationError::Unavailable)?; + let days = configured + .recovery_days(&authority) + .ok_or(MutationError::Unavailable)?; + let deadline = answered_at + .checked_add_signed(chrono::Duration::days(i64::from(days))) + .ok_or(MutationError::Unavailable)?; + let eligible: i64 = tx.query_one("SELECT count(*) FROM registry_internal.registry_proposal_additions f WHERE f.action_id=$1 AND f.proposal_id=$2 AND f.submission_version=$3 AND f.addition_id=ANY($4::uuid[]) AND f.erased_at IS NULL AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_review_ask_files c WHERE c.action_id=f.action_id AND c.proposal_id=f.proposal_id AND c.submission_version=f.submission_version AND c.addition_id=f.addition_id)",&[&document.action_id,&document.proposal_id,&document.header.submission_version,&answer.body.additions]).await.map_err(map_database_error)?.get(0); + if eligible != answer.body.additions.len() as i64 { + return Err(MutationError::InvalidRequestAt( + RequestLocation::proposal_answer_additions(), + )); + } + let key_material = canonicalize_json( + &json!({"authority":authority,"requestId":request,"askId":answer.ask_id}), + ) + .map_err(|_| MutationError::Unavailable)?; + let key = format!( + "proposal-answer:{}", + hex_bytes(&Sha256::digest(key_material)) + ); + tx.execute("INSERT INTO registry_internal.registry_proposal_review_ask_answers (authority,review_request_id,ask_id,action_id,proposal_id,submission_version,text,answered_by,answered_at,delivery_key,delivery_state,delivery_deadline) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,'pending',$11)",&[&authority,&request,&answer.ask_id,&document.action_id,&document.proposal_id,&document.header.submission_version,&answer.body.text,&actor,&answered_at,&key,&deadline]).await.map_err(map_database_error)?; + for addition in &answer.body.additions { + tx.execute("INSERT INTO registry_internal.registry_proposal_review_ask_files(authority,review_request_id,ask_id,action_id,proposal_id,submission_version,addition_id) VALUES($1,$2,$3,$4,$5,$6,$7)",&[&authority,&request,&answer.ask_id,&document.action_id,&document.proposal_id,&document.header.submission_version,addition]).await.map_err(map_database_error)?; + } + // The mirror keeps the provider's state. The local answer row makes + // the applicant document answered and ends the party's turn immediately. + Ok(()) + } +} + +impl MutationTransaction { + #[allow(clippy::too_many_arguments)] + pub(super) async fn append_public_asks( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + document: &ProposalDocument, + current: &ProposalAuthority, + claims: &crate::api::VerifiedRequestClaims, + frozen: Option<&crate::proposal_workflow::ProposalSnapshot>, + value: &mut Value, + ) -> Result<(), MutationError> { + let rows = ask_rows(tx, document, None).await?; + if rows.is_empty() { + return Ok(()); + } + let action = proposal_action(registry, &document.action_id)?; + let write = crate::api::proposals::authorize( + registry, + action, + claims, + Some(current.common.access_profile()), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Answer), + Some(document.proposal_id), + ); + // Questions and answers reach only the party who may answer on this + // Proposal. The Answer admission carries the human test, so other Get + // holders, agents and services receive no `asks` member at all. + let Some(write) = write else { + return Ok(()); + }; + if !link_readable( + self.check_proposal_document(tx, registry, document, &write, false) + .await, + )? { + return Ok(()); + } + let progress = match frozen { + Some(frozen) => review_progress(tx, document, frozen).await?, + None => ProposalReviewProgress::NotRequired, + }; + let shared = if document.header.state == "applied" { + Some(LinkRefusal::AlreadyApplied) + } else if document.header.state == "rejected" { + Some(LinkRefusal::Rejected) + } else if document.header.state != "submitted" || document.header.current_proposal_erased { + Some(LinkRefusal::WrongState) + } else if document.blocked_reason.as_deref() == Some("application-refused") { + Some(LinkRefusal::ReviseInput) + } else if document.blocked_reason.as_deref() == Some("application-rebase") { + Some(LinkRefusal::TargetChanged) + } else if document.blocked_reason.is_some() + || document.action_revision != action.definition_revision + { + Some(LinkRefusal::PackageChanged) + } else if !matches!( + progress, + ProposalReviewProgress::Pending | ProposalReviewProgress::Retrying + ) { + Some(match progress { + ProposalReviewProgress::Rejected => LinkRefusal::ReviewRejected, + ProposalReviewProgress::ChangesRequested => LinkRefusal::ChangesRequested, + _ => LinkRefusal::ReviewEnded, + }) + } else { + None + }; + let now = Utc::now(); + let mut asks = Vec::with_capacity(rows.len()); + for row in rows { + let id: Uuid = row.get(0); + let answered: bool = row.get(6); + let due: Option = row.get(4); + let state: String = row.get(5); + let due_passed = due + .as_deref() + .map(|due| { + due.parse::>() + .map(|due| due <= now) + .map_err(|_| MutationError::Unavailable) + }) + .transpose()? + .unwrap_or(false); + let mut ask = ask_value(&row); + let refusal = shared.or_else(|| { + if answered { + Some(LinkRefusal::AskAnswered) + } else if state != "open" { + Some(LinkRefusal::AskClosed) + } else if due_passed { + Some(LinkRefusal::AskDuePassed) + } else { + None + } + }); + ask["links"] = json!({"answer":{"method":"POST","path":format!("/v1/proposals/{}/asks/{id}/answer",document.proposal_id),"accessProfile":write.common.access_profile(),"operation":"answer","ifMatch":self.proposal_etag(document,&write)?,"availability":ProposalAvailability::new(document.header.workflow_revision as u64,refusal)}}); + asks.push(ask); + } + value["asks"] = json!(asks); + Ok(()) + } +} + +/// Fixed disclosure markers and admitted download correlation, never answer contents. +#[derive(Default)] +pub(crate) struct ProposalReadDisclosure { + pub(crate) field_set_reference: Option<&'static str>, + pub(crate) asks: bool, + pub(crate) ask_download: Option<(Uuid, Uuid)>, +} +const ASK_REFERENCE: &str = "proposal-review-ask"; +impl ProposalReadDisclosure { + pub(crate) fn for_value(value: &Value) -> Self { + Self { + field_set_reference: value + .pointer("/decision/publicReason") + .is_some() + .then_some(PUBLIC_REASON_REFERENCE), + asks: value + .get("asks") + .or_else(|| value.pointer("/context/asks")) + .and_then(Value::as_array) + .is_some_and(|asks| !asks.is_empty()), + ask_download: None, + } + } + pub(crate) fn for_list(value: &Value, action: &str) -> Self { + let mut disclosure = Self::default(); + if let Some(items) = value["items"].as_array() { + for item in items + .iter() + .filter(|item| item["actionId"].as_str() == Some(action)) + { + let next = Self::for_value(item); + disclosure.asks |= next.asks; + disclosure.field_set_reference = + disclosure.field_set_reference.or(next.field_set_reference); + } + } + disclosure + } + pub(super) fn annotate( + &self, + entry: AuditEntry, + correlation: &RequestCorrelation, + ) -> AuditEntry { + let mut record = entry.record().clone(); + if self.asks { + record["askFieldSetReference"] = json!(ASK_REFERENCE); + if self.field_set_reference.is_none() { + record["fieldSetReference"] = json!(ASK_REFERENCE); + } + } + if let Some((ask, file)) = self.ask_download { + record["reviewAskId"] = json!(ask); + record["additionId"] = json!(file); + } + AuditEntry::response( + crate::audit::AUDIT_SCHEMA, + correlation.request_id().to_string(), + record, + ) + } +} + +async fn ask_rows( + tx: &Transaction<'_>, + document: &ProposalDocument, + binding: Option<(&str, Uuid)>, +) -> Result, MutationError> { + tx.query("SELECT a.ask_id,a.text,a.wants,a.asked_at_wire,a.due_at_wire,a.state,x.ask_id IS NOT NULL,x.text,x.answered_at,ARRAY(SELECT c.addition_id FROM registry_internal.registry_proposal_review_ask_files c WHERE c.authority=a.authority AND c.review_request_id=a.review_request_id AND c.ask_id=a.ask_id ORDER BY c.addition_id) FROM registry_internal.registry_proposal_review_asks a LEFT JOIN registry_internal.registry_proposal_review_ask_answers x USING(authority,review_request_id,ask_id) WHERE a.action_id=$1 AND a.proposal_id=$2 AND a.submission_version=$3 AND a.text IS NOT NULL AND a.detail_erased_at IS NULL AND ($4::text IS NULL OR (a.authority=$4 AND a.review_request_id=$5 AND EXISTS (SELECT 1 FROM registry_internal.registry_proposal_review_submissions s WHERE s.action_id=a.action_id AND s.proposal_id=a.proposal_id AND s.submission_version=a.submission_version AND s.authority=a.authority AND s.accepted_binding->>'requestId'=a.review_request_id::text AND NOT s.withdrawn AND s.state='accepted'))) ORDER BY a.asked_at_wire DESC,a.ask_id DESC LIMIT $6",&[&document.action_id,&document.proposal_id,&document.header.submission_version,&binding.map(|b|b.0),&binding.map(|b|b.1),&(crate::contract::MAX_MIRRORED_REVIEW_ASKS as i64)]).await.map_err(map_database_error) +} + +fn ask_value(row: &tokio_postgres::Row) -> Value { + let answered: bool = row.get(6); + let state: String = row.get(5); + let mut value = json!({"id":row.get::<_,Uuid>(0),"text":row.get::<_,String>(1),"wants":row.get::<_,Value>(2),"askedAt":row.get::<_,String>(3),"state":if answered{"answered"}else{&state}}); + if let Some(due) = row.get::<_, Option>(4) { + value["dueAt"] = json!(due); + } + if answered { + let at: DateTime = row.get(8); + let files: Vec = row.get(9); + let mut answer = json!({"additions":files,"answeredAt":at}); + if let Some(text) = row.get::<_, Option>(7) { + answer["text"] = json!(text); + } + value["answer"] = answer; + } + value +} + +impl MutationTransaction { + #[allow(clippy::too_many_arguments)] + pub(super) async fn intrinsic_asks( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + document: &ProposalDocument, + authority: &ProposalAuthority, + frozen: &crate::proposal_workflow::ProposalSnapshot, + schema_digest: &str, + ) -> Result { + let CompiledProposalReview::Required { + authority: review_authority, + .. + } = frozen.review_requirement() + else { + return Ok(json!([])); + }; + let Some(binding) = crate::review_store::load_status_binding( + tx, + registry, + &document.action_id, + document.proposal_id, + frozen, + ) + .await? + else { + return Ok(json!([])); + }; + let rows = ask_rows(tx, document, Some((review_authority, binding.request_id))).await?; + let has_files = rows + .iter() + .any(|row| !row.get::<_, Vec>(9).is_empty()); + let metadata = if has_files { + self.verify_proposal_attachment_binding(tx).await?; + let action = proposal_action(registry, &document.action_id)?; + let CompiledActionExecution::Proposal { proposal } = &action.execution else { + return Err(MutationError::Unavailable); + }; + let slot = proposal + .additions + .as_ref() + .ok_or(MutationError::Unavailable)?; + crate::attachment_store::additions::metadata( + tx, + &document.action_id, + document.proposal_id, + document.header.submission_version, + &slot.id, + ) + .await? + } else { + Vec::new() + }; + let mut asks = Vec::with_capacity(rows.len()); + for row in rows { + let id: Uuid = row.get(0); + let files: Vec = row.get(9); + let mut ask = ask_value(&row); + if let Some(answer) = ask.get_mut("answer").and_then(Value::as_object_mut) { + answer.remove("additions"); + let mut documents = Vec::with_capacity(files.len()); + for file in files { + let file = metadata + .iter() + .find(|item| item.id == file) + .ok_or(MutationError::Unavailable)?; + let mut descriptor = json!({"id":file.id,"sha256":file.file.sha256,"contentType":file.file.content_type,"byteSize":file.file.byte_size,"verificationStatus":file.file.verification_status}); + if file.file.verification_status.permits_content() { + let path=format!("/v1/proposals/{}/additions/{}?submissionVersion={}&reviewAskId={id}&effectDigest={}&contextSchemaDigest={}",document.proposal_id,file.id,frozen.version().get(),frozen.effect_digest().as_str().replace(':',"%3A"),schema_digest.replace(':',"%3A")); + descriptor["download"] = json!({"method":"GET","operation":"get-review-context","accessProfile":authority.common.access_profile(),"path":path}); + } + documents.push(descriptor); + } + answer.insert("documents".into(), json!(documents)); + } + asks.push(ask); + } + Ok(json!(asks)) + } +} diff --git a/crates/registry-breg/src/mutation/proposal/context_projection.rs b/crates/registry-breg/src/mutation/proposal/context_projection.rs index 0b04cb47b0..489b642fcd 100644 --- a/crates/registry-breg/src/mutation/proposal/context_projection.rs +++ b/crates/registry-breg/src/mutation/proposal/context_projection.rs @@ -38,8 +38,13 @@ pub(super) async fn fields( .iter() .filter(|(field, _)| selected_fields.is_none_or(|selected| selected.contains(*field))) .map(|(_, source)| source) - .any(|source| matches!(source, ProposalContextValueSource::Document { .. })) - { + .any(|source| { + matches!( + source, + ProposalContextValueSource::Document { .. } + | ProposalContextValueSource::Additions { .. } + ) + }) { Some( crate::compiler::review_context::compile_schema(registry, action) .map_err(|_| MutationError::Unavailable)? @@ -93,6 +98,34 @@ pub(super) async fn fields( return Err(MutationError::PreconditionFailed); } let resolved = match source { + ProposalContextValueSource::Additions { slot } => { + let schema = document_contract + .as_ref() + .ok_or(MutationError::PreconditionFailed)?; + let mut items = Vec::new(); + for addition in crate::attachment_store::additions::metadata( + tx, + &document.action_id, + document.proposal_id, + i64::from(frozen.version().get()), + slot, + ) + .await? + { + let file = addition.file; + if !file.verification_status.permits_content() { + continue; + } + let path = format!("/v1/proposals/{}/additions/{}?submissionVersion={}&reviewContextField={}&effectDigest={}&contextSchemaDigest={}", + document.proposal_id, addition.id, frozen.version().get(), field, + frozen.effect_digest().as_str().replace(':', "%3A"), schema.digest.replace(':', "%3A")); + items.push(json!({"type":"document","slotId":slot,"sha256":file.sha256, + "contentType":file.content_type,"byteSize":file.byte_size, + "download":{"method":"GET","operation":"get-review-context", + "accessProfile":authority.common.access_profile(),"path":path}})); + } + json!(items) + } ProposalContextValueSource::Document { slot } => { let definition = proposal .attachments diff --git a/crates/registry-breg/src/package/tests/immediate_actions.rs b/crates/registry-breg/src/package/tests/immediate_actions.rs index b15ee16fb8..7f37979e0e 100644 --- a/crates/registry-breg/src/package/tests/immediate_actions.rs +++ b/crates/registry-breg/src/package/tests/immediate_actions.rs @@ -919,14 +919,55 @@ fn proposal_writable_inputs_accept_start_only_or_fully_writable_grants() { assert!(proposal_permission(&compile(&start_only)) .writable_inputs .is_some()); - let mut edit_without_get = proposal_source(&["edit", "submit"], &[]); - edit_without_get["accessProfiles"]["operator"]["permissions"]["proposals"][0] - ["writableInputs"] = json!(["item", "label"]); - assert!(proposal_permission(&compile(&edit_without_get)) + let mut edit_with_get = proposal_source(&["get", "edit", "submit"], &["item", "label"]); + edit_with_get["accessProfiles"]["operator"]["permissions"]["proposals"][0]["writableInputs"] = + json!(["item", "label"]); + assert!(proposal_permission(&compile(&edit_with_get)) .writable_inputs .is_some()); } +#[test] +fn proposal_write_grants_must_read_every_input_they_may_write() { + for operation in ["edit", "revise", "rebase"] { + // writableInputs absent: every declared input may be written, so every one must be readable. + let value = proposal_source(&["get", operation], &["label"]); + let diagnostics = compile_diagnostics(&value); + assert!( + diagnostics.contains("breg.proposal.input-write-unreadable") + && diagnostics.contains("operator") + && diagnostics.contains("rename-item") + && diagnostics.contains("item") + && diagnostics.contains( + "accessProfiles[id=operator].permissions.proposals[action=rename-item].readableInputs" + ), + "{operation}: {diagnostics}" + ); + // The fixed-input rule keeps every input outside writableInputs readable, so + // narrowing writableInputs never resolves this refusal. + assert!( + !diagnostics.contains("narrow writableInputs"), + "{operation}: {diagnostics}" + ); + // writableInputs present: only the writable inputs must be readable. + let mut narrowed = proposal_source(&["get", operation], &["label"]); + narrowed["accessProfiles"]["operator"]["permissions"]["proposals"][0]["writableInputs"] = + json!(["item", "label"]); + let diagnostics = compile_diagnostics(&narrowed); + assert!( + diagnostics.contains("breg.proposal.input-write-unreadable"), + "{operation}: {diagnostics}" + ); + let accepted = proposal_source(&["get", operation], &["item", "label"]); + compile(&accepted); + } +} + +#[test] +fn proposal_grants_without_write_authority_need_no_readable_inputs() { + compile(&proposal_source(&["get", "submit"], &[])); +} + fn evidence_contract_asset() -> ModuleAssetSource { ModuleAssetSource { module: None, @@ -1212,7 +1253,7 @@ fn reviewed_successor_installs_added_proposal_operation_policies() { let before = compile(&proposal_source(&["get", "cancel"], &[])); let after = compile(&proposal_source( &["get", "cancel", "edit", "submit", "apply"], - &[], + &["item", "label"], )); let plan = reviewed_plan(&before, &after); let before_sql = before diff --git a/crates/registry-breg/src/postgres/catalog.rs b/crates/registry-breg/src/postgres/catalog.rs index 147f822d83..b05a58e7ad 100644 --- a/crates/registry-breg/src/postgres/catalog.rs +++ b/crates/registry-breg/src/postgres/catalog.rs @@ -543,6 +543,14 @@ impl ExpectedManagedCatalog { ); catalog.sequence(DELIVERY_SEQUENCE, ["SELECT", "USAGE"]); for (table, privileges) in crate::proposal_store::PROPOSAL_TABLES { + // File-reference tables are registered with their attachment RLS + // policies below, even when Proposal ownership supplies the grants. + if crate::attachment_store::ATTACHMENT_TABLES + .iter() + .any(|(attachment, _)| attachment == table) + { + continue; + } catalog.table( &format!("registry_internal.{table}"), privileges.iter().copied(), diff --git a/crates/registry-breg/src/postgres/mutation.rs b/crates/registry-breg/src/postgres/mutation.rs index 11b4e1692a..8c1257e964 100644 --- a/crates/registry-breg/src/postgres/mutation.rs +++ b/crates/registry-breg/src/postgres/mutation.rs @@ -333,7 +333,7 @@ impl PostgresRecordMutationService { /// Carry a review result recorded in `transaction` into the Proposal /// lifecycle: a rejection ends the Proposal and a changes-requested /// result records `review-returned`, each with its lifecycle event. - pub(crate) async fn record_review_result( + pub(crate) async fn record_review_change( &self, transaction: &tokio_postgres::Transaction<'_>, authority: &str, @@ -343,7 +343,7 @@ impl PostgresRecordMutationService { status: &str, ) -> Result<(), MutationError> { self.coordinator - .record_review_result( + .record_review_change( transaction, &self.registry, authority, @@ -2043,6 +2043,7 @@ impl PostgresRecordMutationService { Some(IngestionServiceError::RequestInvalid), ), MutationError::PreconditionFailed + | MutationError::ProposalTargetChanged | MutationError::FieldGuardFailed { .. } | MutationError::ProposalGuardFailed(_) | MutationError::ProposalReviewResultMismatch @@ -2075,6 +2076,10 @@ impl PostgresRecordMutationService { // refusals cannot reach a run. | MutationError::AttachmentSlotWriteOnce | MutationError::AttachmentTooLarge + | MutationError::AttachmentLimitReached + | MutationError::AttachmentRequired { .. } + | MutationError::AttachmentVerificationPending { .. } + | MutationError::AttachmentVerificationRejected { .. } | MutationError::AttachmentContentType | MutationError::AttachmentDigestMismatch => { (IngestionAttemptOutcome::Unavailable, None) diff --git a/crates/registry-breg/src/postgres/proposal.rs b/crates/registry-breg/src/postgres/proposal.rs index 3d991c0705..4e9cce5435 100644 --- a/crates/registry-breg/src/postgres/proposal.rs +++ b/crates/registry-breg/src/postgres/proposal.rs @@ -3,10 +3,11 @@ //! Pool orchestration keeps authenticated external review observations outside //! PostgreSQL transactions and connections. The coordinator owns effects. use super::*; +use crate::api::proposals::ReviewDocumentSource; use crate::api::proposals::{ProposalListQuery, ProposalMutationInput}; use crate::api::VerifiedRequestClaims; use crate::model::ProposalOperation; -use crate::mutation::{CheckedProposalTaskAuthority, ProposalApplyPreflight}; +use crate::mutation::{link_readable, CheckedProposalTaskAuthority, ProposalApplyPreflight}; use crate::postgres::{begin_proposal_transaction, ProposalAuthority, ProposalAuthorityOperation}; use crate::proposal_store; use std::collections::{BTreeMap, BTreeSet}; @@ -29,7 +30,7 @@ struct ProposalReviewSnapshot { // are the caller's optional `action` and `state` filters: they only narrow rows // the collection authority already lists, so applying them here spends the scan // budget on candidates that can match without revealing anything further. -const PROPOSAL_LIST_CANDIDATES: &str = "SELECT p.proposal_id,p.action_id FROM registry_internal.registry_proposal_state p +const PROPOSAL_LIST_CANDIDATES: &str = "SELECT p.proposal_id,p.action_id,p.workflow_revision,({open_ask}) AS ask_open FROM registry_internal.registry_proposal_state p WHERE p.action_id=ANY($1) AND ($2::uuid IS NULL OR p.proposal_id>$2) AND ($5::text IS NULL OR p.action_id=$5) AND ($6::text IS NULL OR p.state=$6) @@ -50,6 +51,10 @@ const PROPOSAL_LIST_CANDIDATES: &str = "SELECT p.proposal_id,p.action_id FROM re ))) ORDER BY p.proposal_id LIMIT 9"; +fn proposal_list_candidates_sql() -> String { + PROPOSAL_LIST_CANDIDATES.replace("{open_ask}", proposal_store::OPEN_ASK_SQL) +} + impl PostgresRecordMutationService { #[cfg(feature = "postgres-test")] pub async fn pending_manual_list_plan_for_test( @@ -63,7 +68,10 @@ impl PostgresRecordMutationService { .map_err(|_| MutationError::Unavailable)?; let row = client .query_one( - &format!("EXPLAIN (ANALYZE, FORMAT JSON) {PROPOSAL_LIST_CANDIDATES}"), + &format!( + "EXPLAIN (ANALYZE, FORMAT JSON) {}", + proposal_list_candidates_sql() + ), &[ &actions, &Option::::None, @@ -298,6 +306,7 @@ impl PostgresRecordMutationService { }), rebase_start_authority: None, attachment: None, + answer: None, correlation: &correlation, human_identity: None, claims: None, @@ -320,20 +329,22 @@ impl PostgresRecordMutationService { client.execute("UPDATE registry_internal.registry_proposal_application_jobs SET state=CASE WHEN ($6 OR next_attempt_at<=clock_timestamp()) AND attempt_count, authority: &ProposalAuthority, review: Option<&crate::api::proposals::ReviewContextDocumentRead<'_>>, correlation: &crate::correlation::RequestCorrelation, @@ -375,59 +386,151 @@ impl PostgresRecordMutationService { ) .await?; if review.is_some() { - if authority.operation != ProposalAuthorityOperation::Lifecycle(ProposalOperation::GetReviewContext) { + if authority.operation + != ProposalAuthorityOperation::Lifecycle(ProposalOperation::GetReviewContext) + { return Err(MutationError::PreconditionFailed); } - self.coordinator.authorize_proposal_review_read( - guarded.transaction(), - &self.registry, - &document, - authority, - ).await?; + self.coordinator + .authorize_proposal_review_read( + guarded.transaction(), + &self.registry, + &document, + authority, + ) + .await?; } else { - if authority.operation != ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get) { + if authority.operation + != ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get) + { return Err(MutationError::PreconditionFailed); } - self.coordinator.authorize_proposal_document( - guarded.transaction(), &self.registry, &document, authority, - ).await?; + self.coordinator + .authorize_proposal_document( + guarded.transaction(), + &self.registry, + &document, + authority, + ) + .await?; } if document.header.submission_version != i64::from(version) { return Err(MutationError::PreconditionFailed); } if let Some(review) = review { - let action = self.registry.actions().actions.iter().find(|action| action.id == document.action_id) + let action = self + .registry + .actions() + .actions + .iter() + .find(|action| action.id == document.action_id) .ok_or(MutationError::PreconditionFailed)?; - let crate::model::CompiledActionExecution::Proposal { proposal } = &action.execution else { + let crate::model::CompiledActionExecution::Proposal { proposal } = + &action.execution + else { return Err(MutationError::PreconditionFailed); }; - if !matches!(proposal.review_context.as_ref().and_then(|context| context.fields.get(review.field)), - Some(crate::contract::ProposalContextValueSource::Document { slot: mapped }) if mapped == slot) { + let mapped = match review.source { + ReviewDocumentSource::Ask(_) => { + addition.is_some() && authority.receives_review_answers + } + ReviewDocumentSource::Field(field) => match proposal + .review_context + .as_ref() + .and_then(|context| context.fields.get(field)) + { + Some(crate::contract::ProposalContextValueSource::Document { + slot: mapped, + }) => addition.is_none() && mapped == slot, + Some(crate::contract::ProposalContextValueSource::Additions { + slot: mapped, + }) => addition.is_some() && mapped == slot, + _ => false, + }, + }; + if !mapped { return Err(MutationError::PreconditionFailed); } // Run the entire ordinary context disclosure, including consent // and membership, under this same transaction before any bytes. - let context = self.coordinator.proposal_review_value( - guarded.transaction(), &self.registry, &document, authority, review.records, - None, None, - ).await?; + let context = self + .coordinator + .proposal_review_value( + guarded.transaction(), + &self.registry, + &document, + authority, + review.records, + None, + None, + ) + .await?; + let disclosed = match review.source { + ReviewDocumentSource::Field(field) => { + if let Some(addition) = addition { + let prefix = format!("/v1/proposals/{id}/additions/{addition}?"); + context["context"]["fields"][field] + .as_array() + .is_some_and(|items| { + items.iter().any(|item| { + item["download"]["path"] + .as_str() + .is_some_and(|path| path.starts_with(&prefix)) + }) + }) + } else { + !context["context"]["fields"][field].is_null() + } + } + ReviewDocumentSource::Ask(ask) => addition.is_some_and(|addition| { + let prefix = format!("/v1/proposals/{id}/additions/{addition}?"); + context["context"]["asks"].as_array().is_some_and(|asks| { + asks.iter() + .filter(|item| item["id"] == ask.to_string()) + .any(|ask| { + ask["answer"]["documents"].as_array().is_some_and(|files| { + files.iter().any(|file| { + file["id"] == addition.to_string() + && file["download"]["path"] + .as_str() + .is_some_and(|path| path.starts_with(&prefix)) + }) + }) + }) + }) + }), + }; if context["effectDigest"].as_str() != Some(review.effect_digest) - || context["context"]["contract"]["schemaDigest"].as_str() != Some(review.schema_digest) - || context["context"]["fields"][review.field].is_null() { + || context["context"]["contract"]["schemaDigest"].as_str() + != Some(review.schema_digest) + || !disclosed + { return Err(MutationError::PreconditionFailed); } } self.coordinator .verify_proposal_attachment_binding(guarded.transaction()) .await?; - let attachment = crate::attachment_store::load( - guarded.transaction(), - &document.action_id, - id, - i64::from(version), - slot, - ) - .await? + let attachment = if let Some(addition) = addition { + crate::attachment_store::additions::load( + guarded.transaction(), + &document.action_id, + id, + i64::from(version), + addition, + slot, + ) + .await? + } else { + crate::attachment_store::load( + guarded.transaction(), + &document.action_id, + id, + i64::from(version), + slot, + ) + .await? + } .ok_or(MutationError::PreconditionFailed)?; // Current target, slot, quarantine and deletion-lock admission precede // the configured adapter's exact-hash read. @@ -459,7 +562,20 @@ impl PostgresRecordMutationService { .await .map_err(|_| MutationError::Unavailable)?; self.coordinator - .finish_proposal_read_audit(authority, crate::model::HttpMethod::Get, Some(&document), 1, None, correlation) + .finish_proposal_read_audit_detail( + authority, + crate::model::HttpMethod::Get, + Some(&document), + 1, + crate::mutation::ProposalReadDisclosure { + ask_download: match (review.map(|review| review.source), addition) { + (Some(ReviewDocumentSource::Ask(ask)), Some(file)) => Some((ask, file)), + _ => None, + }, + ..Default::default() + }, + correlation, + ) .await?; Ok((attachment.metadata.content_type, bytes)) }) @@ -517,11 +633,7 @@ impl PostgresRecordMutationService { let _audit = self.coordinator.begin_proposal_audit(&input).await?; let authority = input.authority; let correlation = input.correlation; - let method = match &input.attachment { - Some(attachment) if attachment.bytes.is_some() => crate::model::HttpMethod::Patch, - Some(_) => crate::model::HttpMethod::Delete, - None => crate::model::HttpMethod::Post, - }; + let method = crate::mutation::proposal_http_method(&input); let result = self.proposal_mutation_after_attempt(input, deadline).await; if result.is_err() { self.coordinator @@ -834,15 +946,12 @@ impl PostgresRecordMutationService { .await .map_err(|_| MutationError::Unavailable)?; self.coordinator - .finish_proposal_read_audit( + .finish_proposal_read_audit_detail( authority, crate::model::HttpMethod::Get, Some(&document), 1, - value - .pointer("/decision/publicReason") - .is_some() - .then_some(crate::mutation::PUBLIC_REASON_REFERENCE), + crate::mutation::ProposalReadDisclosure::for_value(&value), correlation, ) .await?; @@ -998,12 +1107,12 @@ impl PostgresRecordMutationService { .await?; let Some(expected) = first.progress_binding else { self.coordinator - .finish_proposal_read_audit( + .finish_proposal_read_audit_detail( authority, crate::model::HttpMethod::Get, Some(&first.document), 1, - None, + crate::mutation::ProposalReadDisclosure::for_value(&first.value), correlation, ) .await?; @@ -1416,7 +1525,7 @@ impl PostgresRecordMutationService { // filter. Row/ownership concealment precedes filtering and counts. let candidates = client .query( - PROPOSAL_LIST_CANDIDATES, + &proposal_list_candidates_sql(), &[ &action_ids, &after, @@ -1451,10 +1560,11 @@ impl PostgresRecordMutationService { ) .await .map_err(|_| MutationError::Unavailable)?; - let document = proposal_store::load_document( + let document = proposal_store::load_document_with_ask( guarded.transaction(), id, proposal_store::DocumentLock::Share, + Some((candidate.get(2), candidate.get(3))), ) .await?; #[cfg(feature = "postgres-test")] @@ -1597,7 +1707,7 @@ impl PostgresRecordMutationService { } for authority in authorities { self.coordinator - .finish_proposal_read_audit( + .finish_proposal_read_audit_detail( authority, crate::model::HttpMethod::Get, None, @@ -1609,15 +1719,10 @@ impl PostgresRecordMutationService { }) .count() }), - value["items"] - .as_array() - .is_some_and(|items| { - items.iter().any(|item| { - item["actionId"].as_str() == Some(authority.common.action_id()) - && item.pointer("/decision/publicReason").is_some() - }) - }) - .then_some(crate::mutation::PUBLIC_REASON_REFERENCE), + crate::mutation::ProposalReadDisclosure::for_list( + &value, + authority.common.action_id(), + ), correlation, ) .await?; @@ -1634,20 +1739,6 @@ impl PostgresRecordMutationService { } } -/// Whether a link check's authorization outcome lets the caller read the -/// Proposal. Only the two refusals a Proposal read gives a caller who may not -/// read it omit the link. A conflict, a retryable conflict or any other -/// failure stays an error, which the revision read answers as unavailable. -fn link_readable(outcome: Result<(), MutationError>) -> Result { - match outcome { - Ok(()) => Ok(true), - Err(MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed) => { - Ok(false) - } - Err(error) => Err(error), - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/registry-breg/src/postgres/proposal_context.rs b/crates/registry-breg/src/postgres/proposal_context.rs index 22d354ccf0..54b88f1d9d 100644 --- a/crates/registry-breg/src/postgres/proposal_context.rs +++ b/crates/registry-breg/src/postgres/proposal_context.rs @@ -29,6 +29,10 @@ pub(crate) struct ProposalAuthority { pub(crate) targets: BTreeMap>, pub(crate) task_grant: Option, pub(crate) proposal_scope: Option>, + /// Whether this caller may receive applicant answers to review asks and + /// download the files they cite. Only Proposal admission of a verified + /// human caller sets it; every other authority is built without it. + pub(crate) receives_review_answers: bool, system: Option, } @@ -123,6 +127,7 @@ impl ProposalAuthority { targets, task_grant: None, proposal_scope: None, + receives_review_answers: false, system: None, }) } @@ -247,6 +252,7 @@ impl ProposalAuthority { targets, task_grant: None, proposal_scope: Some(BTreeSet::from([proposal_id])), + receives_review_answers: false, system: Some(SystemApplyAuthority { grant: grant.clone(), proposal_id, @@ -430,6 +436,8 @@ impl ProposalAuthority { ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get) => "get", ProposalAuthorityOperation::Lifecycle(ProposalOperation::List) => "list", ProposalAuthorityOperation::Lifecycle(ProposalOperation::Edit) => "edit", + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Add) => "add", + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Answer) => "answer", ProposalAuthorityOperation::Lifecycle(ProposalOperation::Submit) => "submit", ProposalAuthorityOperation::Lifecycle(ProposalOperation::Revise) => "revise", ProposalAuthorityOperation::Lifecycle(ProposalOperation::Cancel) => "cancel", diff --git a/crates/registry-breg/src/problem.rs b/crates/registry-breg/src/problem.rs index 0026ac5622..680f8ff7c3 100644 --- a/crates/registry-breg/src/problem.rs +++ b/crates/registry-breg/src/problem.rs @@ -28,8 +28,12 @@ pub enum ProblemCode { ActionRefused, AttachmentContentType, AttachmentDigestMismatch, + AttachmentLimitReached, + AttachmentRequired, AttachmentSlotWriteOnce, AttachmentTooLarge, + AttachmentVerificationPending, + AttachmentVerificationRejected, AuthenticationRefused, ExternalViewIncomplete, IdempotencyConflict, @@ -74,8 +78,12 @@ impl ProblemCode { Self::ActionRefused, Self::AttachmentContentType, Self::AttachmentDigestMismatch, + Self::AttachmentLimitReached, + Self::AttachmentRequired, Self::AttachmentSlotWriteOnce, Self::AttachmentTooLarge, + Self::AttachmentVerificationPending, + Self::AttachmentVerificationRejected, Self::AuthenticationRefused, Self::ExternalViewIncomplete, Self::IdempotencyExpired, @@ -123,8 +131,12 @@ impl ProblemCode { Self::ActionRefused, Self::AttachmentContentType, Self::AttachmentDigestMismatch, + Self::AttachmentLimitReached, + Self::AttachmentRequired, Self::AttachmentSlotWriteOnce, Self::AttachmentTooLarge, + Self::AttachmentVerificationPending, + Self::AttachmentVerificationRejected, Self::AuthenticationRefused, Self::IdempotencyExpired, Self::IdempotencyConflict, @@ -167,6 +179,10 @@ impl ProblemCode { Self::ActionRefused => "action.refused", Self::AttachmentContentType => "attachment.content-type", Self::AttachmentDigestMismatch => "attachment.digest-mismatch", + Self::AttachmentLimitReached => "attachment.limit-reached", + Self::AttachmentRequired => "attachment.required", + Self::AttachmentVerificationPending => "attachment.verification-pending", + Self::AttachmentVerificationRejected => "attachment.verification-rejected", Self::AttachmentSlotWriteOnce => "attachment.slot-write-once", Self::AttachmentTooLarge => "attachment.too-large", Self::AuthenticationRefused => "authentication.refused", @@ -218,6 +234,8 @@ impl ProblemCode { Self::IngestionProfileMismatch | Self::WriteOutsideBoundary => 403, Self::LookupUnresolved | Self::ResourceNotFound => 404, Self::AttachmentSlotWriteOnce + | Self::AttachmentLimitReached + | Self::AttachmentVerificationPending | Self::IdempotencyConflict | Self::IngestionChunkMismatch | Self::IngestionRunBlocked @@ -236,6 +254,8 @@ impl ProblemCode { Self::AttachmentContentType | Self::UnsupportedMediaType => 415, Self::ActionRefused | Self::AttachmentDigestMismatch + | Self::AttachmentRequired + | Self::AttachmentVerificationRejected | Self::StatisticalDatasetReleaseRefused => 422, Self::PreconditionRequired => 428, Self::ActionHandlerFailed | Self::StatisticalDatasetDomainViolation => 500, @@ -292,6 +312,10 @@ impl ProblemCode { "The record attachment slot already holds a file and is write-once." } Self::AttachmentTooLarge => "The file is larger than the attachment slot accepts.", + Self::AttachmentLimitReached => "The supporting document slot has reached its file limit.", + Self::AttachmentRequired => "The required attachment slot is empty.", + Self::AttachmentVerificationPending => "The attachment is awaiting verification. Refresh the Proposal before submitting.", + Self::AttachmentVerificationRejected => "The attachment was rejected by verification. Replace or remove the file before submitting.", Self::AuthenticationRefused => "The bearer token or delivery signature was not accepted.", Self::ExternalViewIncomplete => { "The external view's indexed coverage is incomplete for this request." diff --git a/crates/registry-breg/src/problem_location.rs b/crates/registry-breg/src/problem_location.rs index 5a09f9ef80..0f456d9e8d 100644 --- a/crates/registry-breg/src/problem_location.rs +++ b/crates/registry-breg/src/problem_location.rs @@ -111,6 +111,20 @@ pub struct RequestLocation { } impl RequestLocation { + /// Fixed members of the Proposal ask-answer command. No submitted value is echoed. + pub fn proposal_answer_text() -> Self { + Self { + pointer: "/text".into(), + scope: Scope::Input, + } + } + pub fn proposal_answer_additions() -> Self { + Self { + pointer: "/additions".into(), + scope: Scope::Input, + } + } + /// The `data` member of a create body. #[must_use] pub fn data() -> Self { diff --git a/crates/registry-breg/src/project_sdk.rs b/crates/registry-breg/src/project_sdk.rs index 0f4f1c51e4..94f1aaa314 100644 --- a/crates/registry-breg/src/project_sdk.rs +++ b/crates/registry-breg/src/project_sdk.rs @@ -13,11 +13,11 @@ pub(super) fn generate( let mut ts = String::from( "// Generated by BReg. Edit the project, then regenerate.\nimport type { breg } from '@registrystack/client';\n", ); - ts.push_str(TYPESCRIPT_CONTRACT); + ts.push_str(&lifecycle_contract(TYPESCRIPT_CONTRACT, " | ")); let mut py = String::from( "# Generated by BReg. Edit the project, then regenerate.\nfrom __future__ import annotations\nfrom typing import TypedDict, NotRequired, Literal, Protocol, TypeVar, Generic, Any, Callable, overload, cast\nfrom dataclasses import dataclass\n\n", ); - py.push_str(PYTHON_CONTRACT); + py.push_str(&lifecycle_contract(PYTHON_CONTRACT, ", ")); for entity in entities.values() { let fields = entity .stored_fields @@ -479,9 +479,25 @@ fn schema_type(schema: &Value, python: bool) -> String { .to_owned() } +fn lifecycle_contract(template: &str, separator: &str) -> String { + let reasons = crate::lifecycle::ProposalAvailabilityReason::ALL + .iter() + .map(|value| format!("'{}'", value.as_str())) + .collect::>() + .join(separator); + let recoveries = crate::lifecycle::ProposalLinkRecovery::ALL + .iter() + .map(|value| format!("'{}'", value.as_str())) + .collect::>() + .join(separator); + template + .replace("__ENGINE_REASONS__", &reasons) + .replace("__RECOVERY_HINTS__", &recoveries) +} + const TYPESCRIPT_CONTRACT: &str = r#" -export type EngineReason = 'pending-review' | 'review-rejected' | 'review-changes-requested' | 'review-ended' | 'stale-revision' | 'package-changed' | 'dependency-outage' | 'invalid-input' | 'already-applied'; -export type RecoveryHint = 'refresh' | 'revise' | 'retry' | 'rebase' | 'correct-input' | 'receipt-only'; +export type EngineReason = __ENGINE_REASONS__; +export type RecoveryHint = __RECOVERY_HINTS__; export type Availability = | { readonly available: true; readonly observedRevision: number } | { readonly available: false; readonly observedRevision: number; readonly reason: R; readonly recovery: RecoveryHint }; @@ -578,8 +594,8 @@ export class ProjectClient { } "#; const PYTHON_CONTRACT: &str = r#" -EngineReason = Literal['pending-review', 'review-rejected', 'review-changes-requested', 'review-ended', 'stale-revision', 'package-changed', 'dependency-outage', 'invalid-input', 'already-applied'] -RecoveryHint = Literal['refresh', 'revise', 'retry', 'rebase', 'correct-input', 'receipt-only'] +EngineReason = Literal[__ENGINE_REASONS__] +RecoveryHint = Literal[__RECOVERY_HINTS__] class Availability(TypedDict): available: bool observedRevision: int @@ -699,7 +715,7 @@ class ProjectClient: #[cfg(test)] mod tests { - use super::{PYTHON_CONTRACT, TYPESCRIPT_CLIENT, TYPESCRIPT_CONTRACT}; + use super::{lifecycle_contract, PYTHON_CONTRACT, TYPESCRIPT_CLIENT, TYPESCRIPT_CONTRACT}; #[test] fn typescript_project_client_passes_proposal_objects_to_the_native_client() { @@ -722,7 +738,10 @@ mod tests { #[test] fn recovery_vocabulary_names_rebase_and_omits_terminal() { - for contract in [TYPESCRIPT_CONTRACT, PYTHON_CONTRACT] { + for contract in [ + lifecycle_contract(TYPESCRIPT_CONTRACT, " | "), + lifecycle_contract(PYTHON_CONTRACT, ", "), + ] { assert!(contract.contains("'package-changed'"), "{contract}"); assert!(!contract.contains("'contract-changed'"), "{contract}"); assert!(contract.contains("'rebase'"), "{contract}"); diff --git a/crates/registry-breg/src/proposal_artifacts.rs b/crates/registry-breg/src/proposal_artifacts.rs index cec9295a0e..4d6214b13c 100644 --- a/crates/registry-breg/src/proposal_artifacts.rs +++ b/crates/registry-breg/src/proposal_artifacts.rs @@ -2,13 +2,18 @@ //! First-class Proposal operations derived from the compiled Action policies. use super::*; use crate::model::{CompiledActionExecution, ProposalOperation}; +use crate::problem::ProblemCode; pub(crate) fn append_proposal_openapi( paths: &mut Map, actions: &CompiledActionInventory, entities: &BTreeMap, visible: Option<&BTreeSet<(String, String, ProposalOperation)>>, -) { +) -> Result<(), Diagnostic> { + let additions_enabled = actions.actions.iter().any(|action| { + matches!(&action.execution, + CompiledActionExecution::Proposal { proposal } if proposal.additions.is_some()) + }); let mut permissions: BTreeMap, Vec)> = BTreeMap::new(); // A manual application writes as the applier, so the apply operation may @@ -18,6 +23,10 @@ pub(crate) fn append_proposal_openapi( // Every record slot is write-once, so applying a Proposal that promotes // a file can meet a slot an earlier write already filled. let mut apply_may_fill_written_slot = false; + let mut submit_problems = BTreeSet::new(); + let mut submit_refusals = BTreeMap::new(); + let mut submit_attachment_examples = BTreeMap::new(); + let mut apply_problems = BTreeSet::new(); for action in &actions.actions { let CompiledActionExecution::Proposal { proposal } = &action.execution else { continue; @@ -30,7 +39,12 @@ pub(crate) fn append_proposal_openapi( }) }; for operation in &grant.operations { - if *operation == ProposalOperation::GetApplicationActor { + if matches!( + operation, + ProposalOperation::GetApplicationActor + | ProposalOperation::Add + | ProposalOperation::Answer + ) { continue; } if !permitted(*operation) { @@ -52,6 +66,75 @@ pub(crate) fn append_proposal_openapi( && action_may_refuse_write(action, entities, &grant.profile_id); apply_may_fill_written_slot |= permitted(ProposalOperation::Apply) && !proposal.promotions.is_empty(); + let field_guard = action.requires.iter().any(|guard| !guard.field.is_empty()); + if permitted(ProposalOperation::Apply) { + if field_guard { + apply_problems.insert(ProblemCode::ActionGuardFailed); + } + if matches!( + proposal.review, + crate::model::CompiledProposalReview::Required { .. } + ) { + apply_problems.insert(ProblemCode::ProposalReviewResultMismatch); + } + if !action.evidence.is_empty() || !action.commit_evidence.is_empty() { + apply_problems.insert(ProblemCode::ActionEvidenceFailed); + } + if action + .target_uses + .iter() + .filter(|target| { + matches!(target.operation, Operation::Create | Operation::Patch) + }) + .any(|target| { + entities.get(&target.entity_id).is_some_and(|entity| { + target.fields.iter().any(|field| { + entity + .fields + .get(field) + .is_some_and(|field| field.encryption.is_some()) + }) + }) + }) + { + apply_problems.insert(ProblemCode::RuntimeFieldEncryptionUnavailable); + } + } + if permitted(ProposalOperation::Submit) { + for (slot, definition) in &proposal.attachments { + submit_attachment_examples + .entry(ProblemCode::AttachmentVerificationPending) + .or_insert_with(|| slot.clone()); + let code = if definition.required { + ProblemCode::AttachmentRequired + } else { + ProblemCode::AttachmentVerificationRejected + }; + submit_attachment_examples + .entry(code) + .or_insert_with(|| slot.clone()); + } + if field_guard { + submit_problems.insert(ProblemCode::ActionGuardFailed); + } + if !proposal.attachments.is_empty() { + submit_problems.insert(ProblemCode::AttachmentVerificationPending); + } + if proposal.attachments.values().any(|slot| !slot.required) { + submit_problems.insert(ProblemCode::AttachmentVerificationRejected); + } + + if proposal.attachments.values().any(|slot| slot.required) { + submit_problems.insert(ProblemCode::AttachmentRequired); + } + if let Some(handler) = &action.handler { + submit_problems.insert(ProblemCode::ActionHandlerFailed); + if !handler.refusals.is_empty() { + submit_problems.insert(ProblemCode::ActionRefused); + submit_refusals.extend(handler.refusals.clone()); + } + } + } let document_fields = proposal .review_context .as_ref() @@ -105,6 +188,7 @@ pub(crate) fn append_proposal_openapi( method, &BTreeSet::from([grant.profile_id.clone()]), false, + additions_enabled, ); if method == "get" { operation["parameters"].as_array_mut().unwrap().push(json!({"name":"submissionVersion","in":"query","required":true,"schema":{"type":"integer","minimum":1,"maximum":u32::MAX}})); @@ -125,12 +209,69 @@ pub(crate) fn append_proposal_openapi( operation["parameters"].as_array_mut().unwrap().push(json!({"name":name,"in":"query","required":false,"schema":schema, "description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority."})); } - operation["responses"]["200"]["content"] = json!({"application/octet-stream":{"schema":{"type":"string","format":"binary","maxLength":crate::contract::MAX_ATTACHMENT_BYTES}}}); + // Any type, unlike the record download's slot types: a carried-forward + // file keeps the type it was stored with. + operation["responses"]["200"]["content"] = json!({"*/*":{"schema":{"type":"string","contentMediaType":"application/octet-stream","maxLength":crate::contract::MAX_ATTACHMENT_BYTES}}}); } else if method == "patch" { let content=slot.content_types.iter().map(|mime|(mime.clone(),json!({"schema":{"type":"string","format":"binary","maxLength":slot.maximum_bytes}}))).collect::>(); operation["requestBody"] = json!({"required":true,"content":content}); } - merge_operation(paths, path.clone(), method, operation); + merge_operation(paths, path.clone(), method, operation)?; + } + } + if permitted(ProposalOperation::Answer) { + let mut document = operation_document( + "proposals.answer", + "post", + &BTreeSet::from([grant.profile_id.clone()]), + false, + additions_enabled, + ); + document["parameters"].as_array_mut().expect("parameters").push(json!({ + "name":"ask_id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}})); + document["requestBody"] = json!({"required":true,"content":{"application/json":{"schema":{ + "type":"object","additionalProperties":false, + "anyOf":[{"required":["text"]},{"required":["additions"],"properties":{"additions":{"minItems":1}}}], + "properties":{ + "text":{"type":"string","minLength":1,"maxLength":2000}, + "additions":{"type":"array","maxItems":32,"uniqueItems":true,"items":{"type":"string","format":"uuid"}}}}}}}); + merge_operation( + paths, + "/v1/proposals/{proposal_id}/asks/{ask_id}/answer".to_owned(), + "post", + document, + )?; + } + if let Some(slot) = &proposal.additions { + let profiles = BTreeSet::from([grant.profile_id.clone()]); + if permitted(ProposalOperation::Add) + && grant.writable_attachments.contains(&slot.id) + { + let path = format!("/v1/proposals/{{proposal_id}}/additions/{}", slot.id); + let mut document = operation_document( + &format!("proposals.additions.{}.post", slot.id), + "post", + &profiles, + false, + true, + ); + let content = slot.content_types.iter().map(|media|(media.clone(),json!({"schema":{"type":"string","format":"binary","maxLength":slot.maximum_bytes}}))).collect::>(); + document["requestBody"] = json!({"required":true,"content":content}); + document["responses"]["400"] = + json!({"description":"Empty file body (`request.invalid`)"}); + document["responses"]["409"] = json!({"description":"The slot count limit was reached (`attachment.limit-reached`), the Proposal was rejected (`proposal.rejected`), or the idempotency key is bound to different bytes (`idempotency.key-reused`)"}); + document["responses"]["413"] = json!({"description":"The file exceeds maximumBytes (`attachment.too-large`)"}); + document["responses"]["415"] = json!({"description":"The slot does not accept this media type (`attachment.content-type`)"}); + merge_operation(paths, path, "post", document)?; + } + let reviewer = permitted(ProposalOperation::GetReviewContext) && (matches!(proposal.review, crate::model::CompiledProposalReview::Required { .. }) || proposal.review_context.as_ref().is_some_and(|context| + context.fields.iter().any(|(name, field)| grant.readable_context_fields.contains(name) + && matches!(field, crate::contract::ProposalContextValueSource::Additions { slot: mapped } if mapped == &slot.id)))); + if (permitted(ProposalOperation::Get) + && grant.readable_attachments.contains(&slot.id)) + || reviewer + { + append_addition_download_path(paths, &profiles)?; } } } @@ -162,6 +303,7 @@ pub(crate) fn append_proposal_openapi( method, &profiles, operation == ProposalOperation::List, + additions_enabled, ); if operation == ProposalOperation::List { let parameters = document["parameters"].as_array_mut().unwrap(); @@ -192,7 +334,7 @@ pub(crate) fn append_proposal_openapi( } parameters.push(parameter); } - document["responses"]["200"]["content"]["application/json"]["schema"] = json!({"type":"object","additionalProperties":false,"required":["items"],"properties":{"items":{"type":"array","maxItems":100,"items":proposal_schema()},"nextCursor":{"type":"string"}}}); + document["responses"]["200"]["content"]["application/json"]["schema"] = json!({"type":"object","additionalProperties":false,"required":["items"],"properties":{"items":{"type":"array","maxItems":100,"items":proposal_schema_with_additions(additions_enabled)},"nextCursor":{"type":"string"}}}); } else if matches!( operation, ProposalOperation::GetReviewStatus | ProposalOperation::GetReviewContext @@ -203,6 +345,12 @@ pub(crate) fn append_proposal_openapi( "schema":{"const":"progress"}, "description":"Request the institution's optional applicant-visible progress code. The code is returned only when the selected caller-owned grant enables readableReviewProgress." })); + } else { + document["parameters"].as_array_mut().unwrap().push(json!({ + "name":"include","in":"query","required":false, + "schema":{"const":"answers"}, + "description":"Request live applicant answers for a displayed human review context. Admission and preflight reads omit this option and receive no intrinsic asks." + })); } document["responses"]["200"]["content"]["application/json"]["schema"] = review_document_schema(operation == ProposalOperation::GetReviewContext); @@ -217,17 +365,25 @@ pub(crate) fn append_proposal_openapi( ) }); document["requestBody"] = json!({"required":true,"content":{"application/json":{"schema":task_context_request_schema()}}}); - document["responses"]["200"]["content"]["application/json"]["schema"] = json!({"type":"object","additionalProperties":false,"required":["request","proposal"],"properties":{"request":task_context_request_schema(),"proposal":review_document_schema(true)}}); + document["responses"]["200"]["content"]["application/json"]["schema"] = json!({"type":"object","additionalProperties":false,"required":["request","proposal"],"properties":{"request":task_context_request_schema(),"proposal":task_review_document_schema()}}); document["responses"] .as_object_mut() .expect("operation responses") .remove("409"); } else if method == "post" { + if operation == ProposalOperation::Apply { + append_problem_codes( + &mut document, + &apply_problems.iter().copied().collect::>(), + ); + } if operation == ProposalOperation::Apply && apply_may_refuse_write { document["responses"]["403"] = json!({"description":"The application writes outside what the selected access profile may write: a disclosure condition binds it on a record type the plan patches (`write.outside-boundary`)"}); + append_problem_codes(&mut document, &[ProblemCode::WriteOutsideBoundary]); } if operation == ProposalOperation::Apply && apply_may_fill_written_slot { document["responses"]["409"] = json!({"description":"The Proposal was rejected, the idempotency key was reused with a different request, or the plan promotes a file into a record slot that already holds one (`attachment.slot-write-once`)"}); + append_problem_codes(&mut document, &[ProblemCode::AttachmentSlotWriteOnce]); } let schema = match operation { ProposalOperation::Apply => proposal_apply_input_schema(), @@ -241,10 +397,36 @@ pub(crate) fn append_proposal_openapi( }; document["requestBody"] = json!({"required":true,"content":{"application/json":{"schema":schema}}}); + if operation == ProposalOperation::Submit { + append_problem_codes( + &mut document, + &submit_problems.iter().copied().collect::>(), + ); + for (code, slot) in &submit_attachment_examples { + document["responses"][code.status().to_string()]["content"] + ["application/problem+json"]["examples"][code.code()]["value"] + ["fieldPath"] = json!(format!("/attachments/{slot}")); + } + if !submit_refusals.is_empty() { + let examples = &mut document["responses"]["422"]["content"] + ["application/problem+json"]["examples"]; + for (code, label) in &submit_refusals { + let mut example = + problem_example("422", ProblemCode::ActionRefused.code(), label); + example["refusalCode"] = json!(code); + examples[format!("action.refused/{code}")] = json!({"value":example}); + } + } + } } if operation == ProposalOperation::Get { - let mut submission = - operation_document("proposals.get-submission", "get", &profiles, false); + let mut submission = operation_document( + "proposals.get-submission", + "get", + &profiles, + false, + additions_enabled, + ); submission["parameters"].as_array_mut().unwrap().push(json!({"name":"submission_version","in":"path","required":true,"schema":{"type":"integer","minimum":1,"maximum":u32::MAX}})); submission["responses"]["200"]["content"]["application/json"]["schema"] = proposal_submission_schema(); @@ -254,11 +436,16 @@ pub(crate) fn append_proposal_openapi( "/v1/proposals/{proposal_id}/submissions/{submission_version}".to_owned(), "get", submission, - ); + )?; } if operation == ProposalOperation::GetReviewContext { - let mut batch = - operation_document("proposals.get-review-context-batch", "get", &profiles, true); + let mut batch = operation_document( + "proposals.get-review-context-batch", + "get", + &profiles, + true, + additions_enabled, + ); batch["description"] = json!("One bounded transport exchange under each item's current get-review-context authority. Ordered visible or concealed results; operational failures refuse the whole batch. Maximum response is 8 MiB."); batch["parameters"].as_array_mut().unwrap().push(json!({"name":"ids","in":"query","required":true, "description":"One to 100 distinct canonical Proposal UUIDs, in response order.", @@ -267,7 +454,7 @@ pub(crate) fn append_proposal_openapi( "type":"object","additionalProperties":false,"required":["items"],"properties":{"items":{ "type":"array","minItems":1,"maxItems":100,"items":{"oneOf":[ {"type":"object","additionalProperties":false,"required":["id","status","context"],"properties":{ - "id":{"type":"string","format":"uuid"},"status":{"const":"visible"},"context":review_document_schema(true)}}, + "id":{"type":"string","format":"uuid"},"status":{"const":"visible"},"context":task_review_document_schema()}}, {"type":"object","additionalProperties":false,"required":["id","status"],"properties":{ "id":{"type":"string","format":"uuid"},"status":{"const":"concealed"}}} ]}}}}); @@ -276,10 +463,11 @@ pub(crate) fn append_proposal_openapi( "/v1/proposals/review-context".to_owned(), "get", batch, - ); + )?; } - merge_operation(paths, path, method, document); + merge_operation(paths, path, method, document)?; } + Ok(()) } fn task_context_request_schema() -> Value { @@ -340,19 +528,33 @@ fn append_application_actor_schema(application: &mut Value) { application["dependentRequired"] = json!({"appliedBy":["appliedAt"],"appliedAt":["appliedBy"]}); } +fn openapi_merge_error() -> Diagnostic { + Diagnostic::error( + "breg.artifact.openapi-merge-failed", + "artifacts.openapi", + "the generated Proposal OpenAPI operations could not be merged", + ) +} + fn merge_operation( paths: &mut Map, path: String, method: &str, mut operation: Value, -) { +) -> Result<(), Diagnostic> { + append_operation_problems(&mut operation, method); let entry = paths.entry(path).or_insert_with(|| json!({})); + let entry = entry.as_object_mut().ok_or_else(openapi_merge_error)?; if let Some(current) = entry.get(method) { let profiles = current["x-registry-accessProfiles"] .as_array() - .unwrap() + .ok_or_else(openapi_merge_error)? .iter() - .chain(operation["x-registry-accessProfiles"].as_array().unwrap()) + .chain( + operation["x-registry-accessProfiles"] + .as_array() + .ok_or_else(openapi_merge_error)?, + ) .cloned() .collect::>(); let mut profiles = profiles @@ -379,8 +581,203 @@ fn merge_operation( } } } + // Profile-specific Actions can contribute different refusal codes. + // Preserve every response and example when the shared route is merged. + for (status, previous) in current["responses"] + .as_object() + .ok_or_else(openapi_merge_error)? + { + if status.starts_with('2') { + continue; + } + let responses = operation["responses"] + .as_object_mut() + .ok_or_else(openapi_merge_error)?; + if let Some(next) = responses.get_mut(status) { + if let Some(examples) = + previous["content"]["application/problem+json"]["examples"].as_object() + { + next["content"]["application/problem+json"]["examples"] + .as_object_mut() + .ok_or_else(openapi_merge_error)? + .extend(examples.clone()); + } + } else { + responses.insert(status.clone(), previous.clone()); + } + } + } + for (status, response) in operation["responses"] + .as_object_mut() + .ok_or_else(openapi_merge_error)? + { + if status.starts_with('2') { + continue; + } + let problem = &mut response["content"]["application/problem+json"]; + let codes = problem["examples"] + .as_object() + .ok_or_else(openapi_merge_error)? + .values() + .map(|example| { + example["value"]["code"] + .as_str() + .map(str::to_owned) + .ok_or_else(openapi_merge_error) + }) + .collect::, _>>()?; + if codes.is_empty() { + return Err(openapi_merge_error()); + } + problem["schema"] = problem_code_schema(&codes); + } + entry.insert(method.to_owned(), operation); + Ok(()) +} + +fn problem_code_schema(codes: &BTreeSet) -> Value { + json!({"allOf":[{"$ref":"#/components/schemas/Problem"}, + {"type":"object","properties":{"code":{"enum":codes}}}]}) +} + +fn append_problem_codes(operation: &mut Value, codes: &[ProblemCode]) { + for code in codes { + let status = code.status().to_string(); + let response = operation["responses"] + .as_object_mut() + .expect("responses") + .entry(status.clone()) + .or_insert_with(|| json!({"description":"Problem response"})); + response["headers"] = json!({"traceparent":traceparent_header("Trace context for this problem response."),"Cache-Control":no_store_header()}); + let content = response + .as_object_mut() + .expect("response") + .entry("content") + .or_insert_with(|| json!({})); + let problem = content + .as_object_mut() + .expect("content") + .entry("application/problem+json") + .or_insert_with( + || json!({"schema":{"$ref":"#/components/schemas/Problem"},"examples":{}}), + ); + let mut example = problem_example(&status, code.code(), code.description()); + let mut allowed = problem["schema"]["allOf"][1]["properties"]["code"]["enum"] + .as_array() + .into_iter() + .flatten() + .filter_map(|value| value.as_str().map(str::to_owned)) + .collect::>(); + allowed.insert(code.code().to_owned()); + problem["schema"] = problem_code_schema(&allowed); + if matches!( + code, + ProblemCode::AttachmentRequired + | ProblemCode::AttachmentVerificationPending + | ProblemCode::AttachmentVerificationRejected + ) { + example["fieldPath"] = json!("/attachments/file"); + } else if *code == ProblemCode::ActionRefused { + // The caller adds examples using the Action's declared codes and labels. + continue; + } + problem["examples"][code.code()] = json!({"value":example}); + } +} + +pub(super) fn append_operation_problems(operation: &mut Value, method: &str) { + let id = operation["operationId"] + .as_str() + .expect("operation id") + .to_owned(); + let upload = method == "patch" && id.starts_with("proposals.attachments.") + || method == "post" && id.starts_with("proposals.additions."); + let addition = method == "post" && id.starts_with("proposals.additions."); + let start = id.ends_with(".start"); + let read_body = id == "proposals.get-task-grant-context"; + let mutation = method != "get" && !read_body; + let mut codes = vec![ + ProblemCode::AuthenticationRefused, + ProblemCode::ResourceNotFound, + ProblemCode::ServiceUnavailable, + ProblemCode::SourceUnavailable, + ProblemCode::RequestTimeout, + ]; + if id == "proposals.list" { + codes.push(ProblemCode::QueryInvalid); + } + if read_body { + codes.extend([ + ProblemCode::RequestInvalid, + ProblemCode::UnsupportedMediaType, + ]); + } + if mutation { + codes.extend([ + ProblemCode::RequestInvalid, + ProblemCode::PreconditionFailed, + ProblemCode::MutationConflict, + ProblemCode::IdempotencyConflict, + ProblemCode::IdempotencyExpired, + ]); + if !start { + codes.extend([ + ProblemCode::ProposalRejected, + ProblemCode::PreconditionRequired, + ]); + } + if upload { + codes.extend([ + ProblemCode::AttachmentTooLarge, + ProblemCode::AttachmentContentType, + ]); + } else if method != "delete" { + codes.push(ProblemCode::UnsupportedMediaType); + } + if addition { + codes.push(ProblemCode::AttachmentLimitReached); + } + } + if id == "proposals.get-submission" { + codes.push(ProblemCode::ProposalSubmissionExpired); + } + append_problem_codes(operation, &codes); +} + +fn append_addition_download_path( + paths: &mut Map, + profiles: &BTreeSet, +) -> Result<(), Diagnostic> { + let mut operation = + operation_document("proposals.additions.download", "get", profiles, false, true); + operation["parameters"].as_array_mut().expect("parameters").push(json!({"name":"addition_id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}})); + operation["parameters"].as_array_mut().expect("parameters").push(json!({"name":"submissionVersion","in":"query","required":true,"schema":{"type":"integer","minimum":1,"maximum":u32::MAX}})); + for (name, schema) in [ + ("reviewAskId", json!({"type":"string","format":"uuid"})), + ( + "reviewContextField", + json!({"type":"string","pattern":"^[a-z][a-zA-Z0-9]{0,63}$"}), + ), + ( + "effectDigest", + json!({"type":"string","pattern":"^sha256:[a-f0-9]{64}$"}), + ), + ( + "contextSchemaDigest", + json!({"type":"string","pattern":"^sha256:[a-f0-9]{64}$"}), + ), + ] { + operation["parameters"].as_array_mut().expect("parameters").push(json!({"name":name,"in":"query","required":false,"schema":schema, + "description":"Use exactly one of reviewContextField or reviewAskId together with effectDigest and contextSchemaDigest for get-review-context authority. reviewAskId admits only a file cited by an answer in the current review binding. Omit all four for Get authority."})); } - entry[method] = operation; + operation["responses"]["200"]["content"] = json!({"*/*":{"schema":{"type":"string","contentMediaType":"application/octet-stream","maxLength":crate::contract::MAX_ATTACHMENT_BYTES}}}); + merge_operation( + paths, + "/v1/proposals/{proposal_id}/additions/{addition_id}".to_owned(), + "get", + operation, + )?; + Ok(()) } fn operation_document( @@ -388,6 +785,7 @@ fn operation_document( method: &str, profiles: &BTreeSet, collection: bool, + additions: bool, ) -> Value { let mut parameters = vec![ json!({"name":"accessProfile","in":"query","required":true,"schema":{"type":"string","enum":profiles}}), @@ -401,13 +799,20 @@ fn operation_document( ); parameters.push(json!({"name":"Idempotency-Key","in":"header","required":true,"schema":{"type":"string"}})); } - let response_schema = if id == "proposals.get" { + let mut response_schema = if id == "proposals.get" { proposal_get_schema() } else { proposal_schema() }; + if additions { + append_proposal_additions_schema(&mut response_schema); + } let mut document = json!({"operationId":id,"x-registry-accessProfiles":profiles,"parameters":parameters, - "responses":{"200":{"description":"Authorized Proposal operation","content":{"application/json":{"schema":response_schema}}},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}}}); + "responses":{"200":{"description":"Authorized Proposal operation","content":{"application/json":{"schema":response_schema}}},"404":{"description":"Resource unavailable to this caller"}}}); + if method != "get" && id != "proposals.get-task-grant-context" { + document["responses"]["412"] = + json!({"description":"Observed authority or lifecycle condition changed"}); + } if matches!(id, "proposals.submit" | "proposals.apply") { document["responses"]["412"]["description"] = json!("Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it"); } @@ -417,6 +822,15 @@ fn operation_document( document } +fn task_review_document_schema() -> Value { + let mut schema = review_document_schema(true); + schema["properties"]["context"]["properties"] + .as_object_mut() + .expect("context properties") + .remove("asks"); + schema +} + fn review_document_schema(context: bool) -> Value { let mut properties = json!({"id":{"type":"string","format":"uuid"},"actionId":{"type":"string"},"actionRevision":{"type":"string"},"submissionVersion":{"type":"integer","minimum":1},"revision":{"type":"integer","minimum":1},"effectDigest":{"type":"string"},"subject":{"type":"object","additionalProperties":false,"required":["source","subjectType","id","version","digest"],"properties":{"source":{"type":"string"},"subjectType":{"const":"proposal"},"id":{"type":"string","format":"uuid"},"version":{"type":"string"},"digest":{"type":"string"}}},"context":{"type":"object","additionalProperties":false,"required":["reference"],"properties":{"reference":{"type":"string"}}},"authority":{"type":"string"},"policy":{"type":"object","additionalProperties":false,"required":["id","version","digest"],"properties":{"id":{"type":"string"},"version":{"type":"string"},"digest":{"type":"string"}}},"reviewable":{"type":"boolean"},"result":{"type":"object","additionalProperties":false,"required":["state"],"properties":{"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]},"resultId":{"type":"string","format":"uuid"},"completedAt":{"type":"string","format":"date-time"},"availableUntil":{"type":"string","format":"date-time"}}}}); properties["context"]["properties"]["contract"] = json!({ @@ -430,6 +844,7 @@ fn review_document_schema(context: bool) -> Value { }); if context { properties["context"]["properties"]["fields"] = json!({"type":"object"}); + properties["context"]["properties"]["asks"] = proposal_asks_schema(true); properties["context"]["required"] = json!(["reference", "contract", "fields"]); } else { properties["requestId"] = json!({"type":"string","format":"uuid"}); @@ -452,6 +867,36 @@ fn review_document_schema(context: bool) -> Value { mod tests { use super::*; + #[test] + fn malformed_problem_example_merge_returns_without_panicking() { + let mut paths = Map::new(); + paths.insert( + "/test".into(), + json!({"post":{ + "x-registry-accessProfiles":["clerk"], + "requestBody":{},"responses":{"422":{"content":{"application/problem+json":{ + "examples":{"action.refused":{"value":{"code":"action.refused"}}} + }}}} + }}), + ); + let mut incoming = operation_document( + "proposals.edit", + "post", + &BTreeSet::from(["officer".into()]), + false, + false, + ); + incoming["responses"]["422"] = json!({"description":"missing examples"}); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + merge_operation(&mut paths, "/test".into(), "post", incoming) + })); + assert!( + result.is_ok(), + "a malformed merge must return an error instead of panicking" + ); + assert!(result.unwrap().is_err()); + } + fn application_actor_document() -> Value { let digest = format!("sha256:{}", "a".repeat(64)); json!({ @@ -492,8 +937,8 @@ mod tests { fn application_actor_schema_is_limited_to_get_and_submission() { let profiles = BTreeSet::from(["reader".to_owned()]); let disclosed = application_actor_document(); - let get = operation_document("proposals.get", "get", &profiles, false); - let apply = operation_document("proposals.apply", "post", &profiles, false); + let get = operation_document("proposals.get", "get", &profiles, false, false); + let apply = operation_document("proposals.apply", "post", &profiles, false, false); assert!(accepts(&response_schema(&get), &disclosed)); assert!(!accepts(&proposal_schema(), &disclosed)); diff --git a/crates/registry-breg/src/proposal_ddl.rs b/crates/registry-breg/src/proposal_ddl.rs index e5b662ae8f..8b70753088 100644 --- a/crates/registry-breg/src/proposal_ddl.rs +++ b/crates/registry-breg/src/proposal_ddl.rs @@ -52,6 +52,8 @@ pub(super) fn target_policies( ProposalOperation::Get => "get", ProposalOperation::List => "list", ProposalOperation::Edit => "edit", + ProposalOperation::Add => "add", + ProposalOperation::Answer => "answer", ProposalOperation::Submit => "submit", ProposalOperation::Revise => "revise", ProposalOperation::Rebase => "rebase", diff --git a/crates/registry-breg/src/proposal_events.rs b/crates/registry-breg/src/proposal_events.rs index 01aeab1dd0..cee46b35c5 100644 --- a/crates/registry-breg/src/proposal_events.rs +++ b/crates/registry-breg/src/proposal_events.rs @@ -50,6 +50,9 @@ pub(crate) async fn insert_proposal_lifecycle_event( || !matches!( event.transition, "started" + | "added" + | "asked" + | "answered" | "edited" | "submitted" | "revised" diff --git a/crates/registry-breg/src/proposal_hooks.rs b/crates/registry-breg/src/proposal_hooks.rs index 59eb470606..ccc015add8 100644 --- a/crates/registry-breg/src/proposal_hooks.rs +++ b/crates/registry-breg/src/proposal_hooks.rs @@ -39,7 +39,7 @@ pub fn proposal_event_schema() -> Value { "submissionVersion":{"type":"integer","minimum":1,"maximum":4294967295u64}, "revision":{"type":"integer","minimum":1,"maximum":9007199254740991u64}, "fromState":{"anyOf":[states.clone(),{"const":"none"}]},"state":states, - "transition":{"type":"string","enum":["started","edited","submitted","revised","rebased","retried","cancelled","applied","rejected","review-returned"]}, + "transition":{"type":"string","enum":["started","edited","submitted","revised","rebased","retried","cancelled","applied","rejected","review-returned","added","asked","answered"]}, "effectDigest":nullable_digest.clone(),"authorityKind":{"enum":["caller","system","review"]}, "systemApplyGrantRevision":nullable_digest, "turn":{"type":"string","enum":["party","official","nobody"]}}}) @@ -332,6 +332,9 @@ pub fn matching_transitions( ProposalEventTransition::Applied, ProposalEventTransition::Rejected, ProposalEventTransition::ReviewReturned, + ProposalEventTransition::Added, + ProposalEventTransition::Asked, + ProposalEventTransition::Answered, ] .into_iter() .filter(|transition| transitions.is_empty() || transitions.contains(transition)) diff --git a/crates/registry-breg/src/proposal_retention.rs b/crates/registry-breg/src/proposal_retention.rs index d5213a3ec7..1c6a7f1af4 100644 --- a/crates/registry-breg/src/proposal_retention.rs +++ b/crates/registry-breg/src/proposal_retention.rs @@ -137,6 +137,9 @@ pub struct ProposalDetailErasure { pub idempotency_results: u64, pub draft_inputs: u64, pub attachment_references: u64, + pub review_asks: u64, + pub review_answers: u64, + pub review_answer_files: u64, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] @@ -763,6 +766,8 @@ impl ProposalRetentionOperatorService { OR (state='staged' AND created_at < transaction_timestamp()-interval '10 minutes')) AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_attachments a WHERE a.sha256=b.sha256 AND a.erased_at IS NULL) + AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_additions a + WHERE a.sha256=b.sha256 AND a.erased_at IS NULL) AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_record_attachments r WHERE r.sha256=b.sha256 AND r.erased_at IS NULL)", &[&hash, &backend], @@ -970,8 +975,8 @@ pub(crate) async fn mark_incompatible_proposals( WHERE s.action_id=$1 AND s.state IN ('draft','submitted') FOR UPDATE OF s) UPDATE registry_internal.registry_proposal_state s - SET blocked_reason=CASE WHEN s.blocked_reason='application-refused' - THEN 'application-refused' WHEN c.compatible THEN NULL ELSE 'package-changed' END, + SET blocked_reason=CASE WHEN s.blocked_reason IN ('application-refused','application-rebase') + THEN s.blocked_reason WHEN c.compatible THEN NULL ELSE 'package-changed' END, updated_at=transaction_timestamp() FROM compatibility c WHERE s.action_id=c.action_id AND s.proposal_id=c.proposal_id @@ -1260,9 +1265,12 @@ async fn count_request_detail_erasure( AND proposal_id = $2 AND submission_version = $3 AND reason IS NOT NULL), - (SELECT count(*) FROM registry_internal.registry_proposal_attachments + ((SELECT count(*) FROM registry_internal.registry_proposal_attachments + WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 + AND erased_at IS NULL) + + (SELECT count(*) FROM registry_internal.registry_proposal_additions WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 - AND erased_at IS NULL), + AND erased_at IS NULL)), (SELECT count(*) FROM registry_internal.registry_proposal_review_submissions s WHERE s.action_id=$1 AND s.proposal_id=$2 AND s.submission_version=$3 @@ -1292,7 +1300,10 @@ async fn count_request_detail_erasure( ))), (SELECT count(*) FROM registry_internal.registry_proposal_review_results WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 - AND result <> '{}'::jsonb)", + AND result <> '{}'::jsonb), + (SELECT count(*) FROM registry_internal.registry_proposal_review_asks WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND text IS NOT NULL), + (SELECT count(*) FROM registry_internal.registry_proposal_review_ask_answers WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND detail_erased_at IS NULL), + (SELECT count(*) FROM registry_internal.registry_proposal_review_ask_files WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3)", &[ &scope.action_id, &scope.proposal_id, @@ -1311,6 +1322,9 @@ async fn count_request_detail_erasure( review_submission_requests: count_to_u64(row.get(5))?, review_accepted_bindings: count_to_u64(row.get(6))?, review_result_payloads: count_to_u64(row.get(7))?, + review_asks: count_to_u64(row.get(8))?, + review_answers: count_to_u64(row.get(9))?, + review_answer_files: count_to_u64(row.get(10))?, }) } @@ -1335,6 +1349,11 @@ async fn erase_proposal_detail_in_transaction( ) .await .map_err(map_retention_error)?; + // Remove citation references with their source-owned answer detail before + // attachment erasure considers whether any bytes are still referenced. + let review_answer_files=transaction.execute("DELETE FROM registry_internal.registry_proposal_review_ask_files WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3",&[&scope.action_id,&scope.proposal_id,&scope.submission_version]).await.map_err(map_retention_error)?; + let review_answers=transaction.execute("UPDATE registry_internal.registry_proposal_review_ask_answers SET text=NULL,answered_by=NULL,detail_erased_at=transaction_timestamp(),claim_token=NULL,lease_until=NULL,delivery_state=CASE WHEN delivery_state='pending' THEN 'superseded' ELSE delivery_state END WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND detail_erased_at IS NULL",&[&scope.action_id,&scope.proposal_id,&scope.submission_version]).await.map_err(map_retention_error)?; + let review_asks=transaction.execute("UPDATE registry_internal.registry_proposal_review_asks SET text=NULL,detail_erased_at=transaction_timestamp() WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND text IS NOT NULL",&[&scope.action_id,&scope.proposal_id,&scope.submission_version]).await.map_err(map_retention_error)?; let proposal_snapshots = transaction .execute( "UPDATE registry_internal.registry_proposal_submissions @@ -1509,6 +1528,9 @@ async fn erase_proposal_detail_in_transaction( idempotency_results, draft_inputs, attachment_references, + review_asks, + review_answers, + review_answer_files, }; if erasure != plan.erasure { return Err(ProposalRetentionError::Unavailable); @@ -1594,6 +1616,9 @@ fn retention_terminal_entry( .and_then(|count| count.checked_add(erasure.idempotency_results)) .and_then(|count| count.checked_add(erasure.draft_inputs)) .and_then(|count| count.checked_add(erasure.attachment_references)) + .and_then(|count| count.checked_add(erasure.review_asks)) + .and_then(|count| count.checked_add(erasure.review_answers)) + .and_then(|count| count.checked_add(erasure.review_answer_files)) .ok_or(ProposalRetentionError::Unavailable)?; terminal_entry( profile, diff --git a/crates/registry-breg/src/proposal_store.rs b/crates/registry-breg/src/proposal_store.rs index a02c390a20..91068e69cf 100644 --- a/crates/registry-breg/src/proposal_store.rs +++ b/crates/registry-breg/src/proposal_store.rs @@ -26,6 +26,7 @@ pub(crate) const PROPOSAL_TABLES: &[(&str, &[&str])] = &[ ("registry_proposal_activation_compatibility", &["SELECT"]), ("registry_proposal_state", &["INSERT", "SELECT", "UPDATE"]), ("registry_proposal_submissions", &["INSERT", "SELECT"]), + ("registry_proposal_additions", &["INSERT", "SELECT"]), ("registry_proposal_task_authority", &["INSERT", "SELECT"]), ("registry_proposal_targets", &["INSERT", "SELECT"]), ("registry_proposal_applications", &["INSERT", "SELECT"]), @@ -54,7 +55,7 @@ pub(crate) async fn install( blocked_reason text CONSTRAINT registry_proposal_state_blocked_reason_values CHECK (blocked_reason IS NULL OR blocked_reason IN - ('package-changed','application-refused')), + ('package-changed','application-refused','application-rebase')), detail_erased_at timestamptz, created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), @@ -73,6 +74,15 @@ pub(crate) async fn install( ALTER TABLE registry_internal.registry_proposal_state DROP CONSTRAINT registry_proposal_state_blocked_reason_check; END IF; + IF EXISTS ( + SELECT 1 FROM pg_catalog.pg_constraint + WHERE conname = 'registry_proposal_state_blocked_reason_values' + AND conrelid = 'registry_internal.registry_proposal_state'::regclass + AND position('application-rebase' IN pg_get_constraintdef(oid)) = 0 + ) THEN + ALTER TABLE registry_internal.registry_proposal_state + DROP CONSTRAINT registry_proposal_state_blocked_reason_values; + END IF; IF NOT EXISTS ( SELECT 1 FROM pg_catalog.pg_constraint WHERE conname = 'registry_proposal_state_blocked_reason_values' @@ -81,7 +91,7 @@ pub(crate) async fn install( ALTER TABLE registry_internal.registry_proposal_state ADD CONSTRAINT registry_proposal_state_blocked_reason_values CHECK (blocked_reason IS NULL OR blocked_reason IN - ('package-changed','application-refused')); + ('package-changed','application-refused','application-rebase')); END IF; END; $proposal_state_blocked_reason$; @@ -465,17 +475,23 @@ pub(crate) async fn block_manual_application_refusal( action_id: &str, proposal_id: Uuid, previous_revision: i64, + refusal: crate::mutation::ApplicationRefusal, ) -> Result<(), MutationError> { let changed = transaction .execute( "UPDATE registry_internal.registry_proposal_state - SET blocked_reason='application-refused', + SET blocked_reason=$4, workflow_revision=workflow_revision+1, updated_at=transaction_timestamp() WHERE action_id=$1 AND proposal_id=$2 AND state='submitted' AND blocked_reason IS NULL AND detail_erased_at IS NULL AND workflow_revision=$3", - &[&action_id, &proposal_id, &previous_revision], + &[ + &action_id, + &proposal_id, + &previous_revision, + &refusal.storage_code(), + ], ) .await .map_err(map_store_error)?; @@ -485,6 +501,21 @@ pub(crate) async fn block_manual_application_refusal( Ok(()) } +/// Correlated with the Proposal row `p`. Shared by document reads and the +/// collection's one-page ask observation, without a remote lookup. +pub(crate) const OPEN_ASK_SQL: &str = "p.state='submitted' AND EXISTS ( + SELECT 1 FROM registry_internal.registry_proposal_review_asks a + JOIN registry_internal.registry_proposal_review_submissions s + USING(action_id,proposal_id,submission_version) + WHERE a.action_id=p.action_id AND a.proposal_id=p.proposal_id + AND a.submission_version=p.submission_version AND a.state='open' + AND a.detail_erased_at IS NULL AND NOT s.withdrawn + AND s.accepted_binding->>'requestId'=a.review_request_id::text + AND s.authority=a.authority + AND (a.due_at IS NULL OR a.due_at>statement_timestamp()) + AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_review_ask_answers x + WHERE x.authority=a.authority AND x.review_request_id=a.review_request_id AND x.ask_id=a.ask_id))"; + pub(crate) struct ProposalDocument { pub action_id: String, pub proposal_id: Uuid, @@ -493,6 +524,7 @@ pub(crate) struct ProposalDocument { pub input: Option>, pub input_targets: Vec<(String, Uuid)>, pub blocked_reason: Option, + pub ask_open: bool, /// When the draft was started, as RFC 3339 UTC text. pub created_at: String, pub header: ProposalWorkflowHeader, @@ -515,11 +547,23 @@ pub(crate) async fn load_document( transaction: &Transaction<'_>, proposal_id: Uuid, lock: DocumentLock, +) -> Result { + load_document_with_ask(transaction, proposal_id, lock, None).await +} + +/// Reuse the page's ask observation while its Proposal revision still matches. +/// A changed revision is reobserved inside this existing locked document query. +pub(crate) async fn load_document_with_ask( + transaction: &Transaction<'_>, + proposal_id: Uuid, + lock: DocumentLock, + observed: Option<(i64, bool)>, ) -> Result { let sql = format!( "SELECT action_id, action_revision, action_title, input, blocked_reason, input_targets, - to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') - FROM registry_internal.registry_proposal_state WHERE proposal_id=$1{}", + to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'), + CASE WHEN $2::bigint=p.workflow_revision THEN $3::boolean ELSE ({OPEN_ASK_SQL}) END + FROM registry_internal.registry_proposal_state p WHERE proposal_id=$1{}", match lock { DocumentLock::None => "", DocumentLock::Share => " FOR SHARE", @@ -527,7 +571,14 @@ pub(crate) async fn load_document( }, ); let row = transaction - .query_opt(&sql, &[&proposal_id]) + .query_opt( + &sql, + &[ + &proposal_id, + &observed.map(|value| value.0), + &observed.map(|value| value.1), + ], + ) .await .map_err(map_store_error)? .ok_or(MutationError::PreconditionFailed)?; @@ -545,6 +596,7 @@ pub(crate) async fn load_document( input, blocked_reason: row.get(4), created_at: row.get(6), + ask_open: row.get(7), header, input_targets: serde_json::from_value(row.get(5)) .map_err(|_| MutationError::Unavailable)?, @@ -1348,6 +1400,26 @@ mod tests { .get::<_, i64>(0); assert_eq!(legacy_constraints, 0); + // Upgrade an already named constraint from a package that predates + // the persisted Rebase recovery, preserving its existing refusal row. + migration.batch_execute( + "ALTER TABLE registry_internal.registry_proposal_state + DROP CONSTRAINT registry_proposal_state_blocked_reason_values; + ALTER TABLE registry_internal.registry_proposal_state + ADD CONSTRAINT registry_proposal_state_blocked_reason_values + CHECK (blocked_reason IS NULL OR blocked_reason IN ('package-changed','application-refused'))" + ).await.unwrap(); + install_mutation_schema(&migration, &database.runtime_role) + .await + .unwrap(); + migration.execute( + "UPDATE registry_internal.registry_proposal_state SET blocked_reason='application-rebase' WHERE proposal_id=$1", + &[&proposal_id], + ).await.expect("the named constraint upgrades without losing the submitted Proposal"); + install_mutation_schema(&migration, &database.runtime_role) + .await + .unwrap(); + migration_task.abort(); database.cleanup().await; } diff --git a/crates/registry-breg/src/proposal_workflow.rs b/crates/registry-breg/src/proposal_workflow.rs index fd80bc3f51..04a02bc258 100644 --- a/crates/registry-breg/src/proposal_workflow.rs +++ b/crates/registry-breg/src/proposal_workflow.rs @@ -246,6 +246,52 @@ impl ProposalWorkflow { }) } + /// Record supporting information without changing the frozen submission. + pub fn record_addition( + mut self, + _context: TrustedTransitionContext, + ) -> Result { + self.refuse_rejected()?; + if self.state != ProposalState::Submitted { + return Err(WorkflowError::InvalidTransition); + } + self.workflow_revision = self.workflow_revision.next()?; + Ok(WorkflowTransition { + workflow: self, + effect: TransitionEffect::Added, + }) + } + + /// Record an arriving review ask without changing the submission. + pub fn record_ask( + self, + context: TrustedTransitionContext, + ) -> Result { + let mut transition = self.record_addition(context)?; + transition.effect = TransitionEffect::Asked; + Ok(transition) + } + + /// Record a mirrored ask's state change without changing the submission. + pub fn record_ask_change( + self, + context: TrustedTransitionContext, + ) -> Result { + let mut transition = self.record_addition(context)?; + transition.effect = TransitionEffect::AskChanged; + Ok(transition) + } + + /// Record the applicant's answer without changing the submission. + pub fn record_answer( + self, + context: TrustedTransitionContext, + ) -> Result { + let mut transition = self.record_addition(context)?; + transition.effect = TransitionEffect::Answered; + Ok(transition) + } + /// Records the review authority's rejection of the current submission. /// A rejection is terminal: the review policy's changes-requested outcome, /// not this state, is how a reviewer allows another attempt. @@ -1690,6 +1736,10 @@ impl WorkflowTransition { #[derive(Clone, PartialEq)] pub enum TransitionEffect { + Added, + Asked, + AskChanged, + Answered, RetryScheduled, Submitted { version: SubmissionVersion, @@ -2320,6 +2370,10 @@ impl fmt::Debug for WorkflowTransition { impl fmt::Debug for TransitionEffect { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + Self::Added => formatter.write_str("Added"), + Self::Asked => formatter.write_str("Asked"), + Self::AskChanged => formatter.write_str("AskChanged"), + Self::Answered => formatter.write_str("Answered"), Self::RetryScheduled => formatter.write_str("RetryScheduled"), Self::Submitted { version, .. } => formatter .debug_struct("Submitted") @@ -3111,6 +3165,119 @@ mod source_owned_review_tests { ); } + #[test] + fn addition_changes_only_the_submitted_workflow_revision() { + let now = context("submitter", "2026-09-19T00:00:00Z"); + assert_eq!( + workflow().record_addition(now.clone()).err(), + Some(WorkflowError::InvalidTransition) + ); + let submitted = workflow() + .submit(now.clone(), proposal(required_review())) + .unwrap() + .into_workflow(); + let before = submitted.clone(); + let added = submitted + .record_addition(now.clone()) + .unwrap() + .into_workflow(); + assert_eq!(added.state(), ProposalState::Submitted); + assert_eq!(added.current_version(), before.current_version()); + assert_eq!(added.current_proposal(), before.current_proposal()); + assert_eq!( + added.workflow_revision(), + before.workflow_revision().next().unwrap() + ); + let revised = before.clone().revise(now.clone()).unwrap().into_workflow(); + assert_eq!( + revised.record_addition(now.clone()).err(), + Some(WorkflowError::InvalidTransition) + ); + let rejected = before.clone().reject(now.clone()).unwrap().into_workflow(); + assert_eq!( + rejected.record_addition(now.clone()).err(), + Some(WorkflowError::Rejected) + ); + let cancelled = before.cancel(now.clone()).unwrap().into_workflow(); + assert_eq!( + cancelled.record_addition(now).err(), + Some(WorkflowError::InvalidTransition) + ); + } + + fn assert_ask_transition(answer: bool) { + let now = context("submitter", "2026-09-19T00:00:00Z"); + let run = |state: ProposalWorkflow| { + if answer { + state.record_answer(now.clone()) + } else { + state.record_ask(now.clone()) + } + }; + assert_eq!( + run(workflow()).err(), + Some(WorkflowError::InvalidTransition) + ); + let before = workflow() + .submit(now.clone(), proposal(required_review())) + .unwrap() + .into_workflow(); + let transition = run(before.clone()).unwrap(); + assert_eq!( + format!("{:?}", transition.effect()), + if answer { "Answered" } else { "Asked" } + ); + let after = transition.into_workflow(); + assert_eq!(after.state(), ProposalState::Submitted); + assert_eq!(after.current_version(), before.current_version()); + assert_eq!(after.current_proposal(), before.current_proposal()); + assert_eq!( + after.workflow_revision(), + before.workflow_revision().next().unwrap() + ); + assert_eq!( + run(before.clone().cancel(now.clone()).unwrap().into_workflow()).err(), + Some(WorkflowError::InvalidTransition) + ); + assert_eq!( + run(before.reject(now.clone()).unwrap().into_workflow()).err(), + Some(WorkflowError::Rejected) + ); + } + + #[test] + fn ask_changes_only_the_submitted_workflow_revision() { + assert_ask_transition(false); + } + + #[test] + fn answer_changes_only_the_submitted_workflow_revision() { + assert_ask_transition(true); + } + + #[test] + fn an_ask_state_change_advances_only_the_submitted_revision() { + let now = context("authority", "2026-09-19T00:00:00Z"); + assert_eq!( + workflow().record_ask_change(now.clone()).err(), + Some(WorkflowError::InvalidTransition) + ); + let before = workflow() + .submit(now.clone(), proposal(required_review())) + .unwrap() + .into_workflow(); + let transition = before.clone().record_ask_change(now).unwrap(); + assert!(matches!(transition.effect(), TransitionEffect::AskChanged)); + let after = transition.into_workflow(); + assert_eq!(after.state(), before.state()); + assert_eq!(after.current_version(), before.current_version()); + assert_eq!(after.current_proposal(), before.current_proposal()); + assert_eq!( + after.workflow_revision(), + before.workflow_revision().next().unwrap() + ); + } + #[test] fn proposal_digest_binds_attachment_hash_type_size_and_slot() { let manifest = BTreeMap::from([( diff --git a/crates/registry-breg/src/review_recovery.rs b/crates/registry-breg/src/review_recovery.rs index 4d448198d4..3ef6f2a625 100644 --- a/crates/registry-breg/src/review_recovery.rs +++ b/crates/registry-breg/src/review_recovery.rs @@ -581,7 +581,7 @@ fn eligibility( /// The refusal for a Proposal whose lifecycle row carries `blocked_reason`. fn block_refusal(blocked_reason: &str) -> ReviewRecoveryRefusal { - if blocked_reason == "application-refused" { + if matches!(blocked_reason, "application-refused" | "application-rebase") { ReviewRecoveryRefusal::ApplicationRefused } else { ReviewRecoveryRefusal::PackageChanged @@ -664,6 +664,10 @@ mod tests { #[test] fn a_refused_apply_block_is_its_own_refusal_not_a_package_change() { + assert_eq!( + block_refusal("application-rebase"), + ReviewRecoveryRefusal::ApplicationRefused + ); assert_eq!( block_refusal("application-refused"), ReviewRecoveryRefusal::ApplicationRefused diff --git a/crates/registry-breg/src/review_store.rs b/crates/registry-breg/src/review_store.rs index 40e05347a5..434c0e865c 100644 --- a/crates/registry-breg/src/review_store.rs +++ b/crates/registry-breg/src/review_store.rs @@ -6,6 +6,8 @@ //! A claimed job is committed before I/O and every response is written through //! an exact proposal and submission-digest comparison. +pub(crate) mod asks; + use chrono::{DateTime, Utc}; use registry_platform_authcommon::FailedCheck; use registry_platform_crypto::delivery_signature::{ @@ -560,7 +562,7 @@ impl ReviewAuthorityRegistry { self.authorities.contains_key(authority) } - fn contains_binding(&self, authority: &str, producer_id: &str) -> bool { + pub(crate) fn contains_binding(&self, authority: &str, producer_id: &str) -> bool { self.authorities .get(authority) .is_some_and(|configured| configured.producer_id == producer_id) @@ -572,7 +574,7 @@ impl ReviewAuthorityRegistry { .map(|configured| (configured.producer_id.as_str(), configured.recovery_days)) } - fn recovery_days(&self, authority: &str) -> Option { + pub(crate) fn recovery_days(&self, authority: &str) -> Option { self.authorities .get(authority) .map(|configured| configured.recovery_days) @@ -679,12 +681,44 @@ impl ReviewAuthorityRegistry { client: &mut tokio_postgres::Client, mutations: &crate::postgres::PostgresRecordMutationService, ) -> Result { - let erased_completions = erase_expired_review_completions(client).await?; - if erased_completions > 0 { - tracing::debug!( - erased = erased_completions, - "BReg review completion retention pass erased expired rows" - ); + // Both feeds get a turn even when ordinary work completed or failed. + let review = self.run_one_review(client, mutations).await; + let mut changed = review.as_ref().copied().unwrap_or(false); + let mut unavailable = review.is_err(); + for authority in self.authorities.values() { + let key = format!("asks:{}", authority.authority); + if self.feed_due(&key) { + let outcome = asks::consume_feed(client, authority, mutations).await; + self.record_feed_outcome(&key, outcome.is_ok()); + match outcome { + Ok(work) => changed |= work, + Err(_) => { + crate::startup::OperationalEvent::ReviewResultLookupsUnavailable.emit(); + unavailable = true; + } + } + } + match asks::deliver_one(client, authority).await { + Ok(work) => changed |= work, + Err(_) => unavailable = true, + } + } + if changed { + Ok(true) + } else if unavailable { + Err(MutationError::Unavailable) + } else { + Ok(false) + } + } + + async fn run_one_review( + &self, + client: &mut tokio_postgres::Client, + mutations: &crate::postgres::PostgresRecordMutationService, + ) -> Result { + let cleanup = maintain_review_receipts(client).await?; + if cleanup.worked() { return Ok(true); } let correlated_completions = correlate_stored_review_completions(client).await?; @@ -993,17 +1027,54 @@ fn terminal_submission_problem_status(status: u16) -> bool { (400..=499).contains(&status) && status != 429 } -async fn erase_expired_review_completions( +struct ReviewReceiptCleanup { + completions_pruned: u64, + ask_feed_events_pruned: u64, +} + +impl ReviewReceiptCleanup { + fn worked(&self) -> bool { + self.completions_pruned > 0 || self.ask_feed_events_pruned > 0 + } +} + +async fn maintain_review_receipts( client: &impl GenericClient, -) -> Result { - client +) -> Result { + let completions_pruned = client .execute( "DELETE FROM registry_internal.registry_proposal_review_completions WHERE expires_at <= transaction_timestamp()", &[], ) .await - .map_err(|_| MutationError::Unavailable) + .map_err(|_| MutationError::Unavailable)?; + let ask_feed_events_pruned=client.execute( + "WITH expired AS ( + SELECT authority,event_id FROM registry_internal.registry_proposal_review_ask_feed_events + WHERE observed_at <= transaction_timestamp()-interval '1 day' + AND observed_at + (recovery_days*interval '1 day') <= transaction_timestamp() + ORDER BY observed_at,authority,event_id LIMIT 1000 + ) DELETE FROM registry_internal.registry_proposal_review_ask_feed_events e USING expired x + WHERE e.authority=x.authority AND e.event_id=x.event_id", + &[]).await.map_err(|_|MutationError::Unavailable)?; + let cleanup = ReviewReceiptCleanup { + completions_pruned, + ask_feed_events_pruned, + }; + if completions_pruned > 0 { + tracing::debug!( + erased = completions_pruned, + "BReg review completion retention pass erased expired rows" + ); + } + if ask_feed_events_pruned > 0 { + tracing::debug!( + ask_feed_events_pruned, + "BReg review receipt maintenance pruned expired rows" + ); + } + Ok(cleanup) } async fn correlate_stored_review_completions( @@ -1210,14 +1281,13 @@ impl ReviewWorker { let mut failed = false; let worked = match self.pool.get().await { Ok(mut client) => { - let housekeeping_worked = - match erase_expired_review_completions(&**client).await { - Ok(erased) => erased > 0, - Err(_) => { - failed = true; - false - } - }; + let housekeeping_worked = match maintain_review_receipts(&**client).await { + Ok(cleanup) => cleanup.worked(), + Err(_) => { + failed = true; + false + } + }; // Authority recovery keeps a fair turn on every iteration: // a sustained application backlog must not starve // submissions, cancellations, result feeds, and polls. @@ -1577,6 +1647,27 @@ pub(crate) async fn load_accepted_binding( } pub(crate) const REVIEW_TABLES: &[(&str, &[&str])] = &[ + ( + "registry_proposal_review_ask_announcements", + &["INSERT", "SELECT", "DELETE"], + ), + ( + "registry_proposal_review_asks", + &["INSERT", "SELECT", "UPDATE"], + ), + ( + "registry_proposal_review_ask_answers", + &["INSERT", "SELECT", "UPDATE"], + ), + ("registry_proposal_review_ask_files", &["INSERT", "SELECT"]), + ( + "registry_proposal_review_ask_feed_events", + &["INSERT", "SELECT", "DELETE"], + ), + ( + "registry_proposal_review_ask_feed_checkpoints", + &["INSERT", "SELECT", "UPDATE"], + ), ( "registry_proposal_review_submissions", &["INSERT", "SELECT", "UPDATE"], @@ -1753,6 +1844,7 @@ pub(crate) async fn install( ) .await .map_err(|_| MutationError::Unavailable)?; + asks::install(client).await?; let revoke_grantees = crate::postgres::RuntimeRevoke::detect(client, runtime_role) .await .map_err(|_| MutationError::Unavailable)? @@ -2043,6 +2135,7 @@ pub(crate) async fn schedule_cancellation( proposal_id: Uuid, submission_version: i64, ) -> Result<(), MutationError> { + asks::close_submission(transaction, action_id, proposal_id, submission_version).await?; transaction .execute( &format!( @@ -2095,6 +2188,9 @@ pub(crate) async fn withdraw_incompatible_proposals( ) .await .map_err(|_| MutationError::Unavailable)?; + for row in transaction.query("SELECT proposal_id,submission_version FROM registry_internal.registry_proposal_state WHERE action_id=$1 AND proposal_id=ANY($2::uuid[])",&[&action_id,&proposal_ids]).await.map_err(|_|MutationError::Unavailable)? { + asks::close_submission(transaction,action_id,row.get(0),row.get(1)).await?; + } Ok(()) } @@ -2774,7 +2870,7 @@ pub async fn reconcile_result( } if !withdrawn && current { mutations - .record_review_result( + .record_review_change( transaction, authority, &entity_id, diff --git a/crates/registry-breg/src/review_store/asks.rs b/crates/registry-breg/src/review_store/asks.rs new file mode 100644 index 0000000000..e5a32ccd20 --- /dev/null +++ b/crates/registry-breg/src/review_store/asks.rs @@ -0,0 +1,314 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Source-owned ask detail and answer delivery. Remote calls never hold a transaction. +use super::*; +mod delivery; +mod feed; +pub(super) use delivery::deliver_one; +pub(super) use feed::consume_feed; + +pub(super) async fn install(client: &impl GenericClient) -> Result<(), MutationError> { + client.batch_execute( + "CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_review_asks ( + authority text NOT NULL, + review_request_id uuid NOT NULL, + ask_id uuid NOT NULL, + action_id text NOT NULL, + proposal_id uuid NOT NULL, + submission_version bigint NOT NULL, + text text CHECK (text IS NULL OR octet_length(text) BETWEEN 1 AND 2000), + wants jsonb NOT NULL CHECK (jsonb_typeof(wants)='array' AND jsonb_array_length(wants)<=8), + asked_at timestamptz NOT NULL, + asked_at_wire text NOT NULL CHECK (octet_length(asked_at_wire)<=64), + due_at timestamptz, + due_at_wire text CHECK (due_at_wire IS NULL OR octet_length(due_at_wire)<=64), + state text NOT NULL CHECK (state IN ('open','answered','expired','closed')), + answered_at timestamptz, + closed_at timestamptz, + detail_erased_at timestamptz, + PRIMARY KEY (authority,review_request_id,ask_id), + UNIQUE (authority,review_request_id,ask_id,action_id,proposal_id,submission_version), + FOREIGN KEY (action_id,proposal_id,submission_version) + REFERENCES registry_internal.registry_proposal_review_submissions + ); + ALTER TABLE registry_internal.registry_proposal_review_asks + ADD COLUMN IF NOT EXISTS last_feed_changed_at_wire text + CHECK (last_feed_changed_at_wire IS NULL OR octet_length(last_feed_changed_at_wire)<=64); + CREATE INDEX IF NOT EXISTS registry_proposal_review_asks_version + ON registry_internal.registry_proposal_review_asks(action_id,proposal_id,submission_version,asked_at DESC,ask_id); + CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_review_ask_answers ( + authority text NOT NULL, + review_request_id uuid NOT NULL, + ask_id uuid NOT NULL, + action_id text NOT NULL, + proposal_id uuid NOT NULL, + submission_version bigint NOT NULL, + text text CHECK (text IS NULL OR octet_length(text)<=2000), + answered_by text, + answered_at timestamptz NOT NULL, + delivery_key text NOT NULL UNIQUE CHECK (octet_length(delivery_key) BETWEEN 1 AND 128), + delivery_state text NOT NULL CHECK (delivery_state IN ('pending','delivered','refused','superseded')), + attempt_count integer NOT NULL DEFAULT 0 CHECK (attempt_count BETWEEN 0 AND 1000), + next_attempt_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + lease_until timestamptz, + claim_token uuid, + delivery_deadline timestamptz NOT NULL CHECK (delivery_deadline>answered_at), + delivered_at timestamptz, + last_error_code text CHECK (last_error_code IS NULL OR octet_length(last_error_code) BETWEEN 1 AND 128), + detail_erased_at timestamptz, + PRIMARY KEY (authority,review_request_id,ask_id), + UNIQUE (authority,review_request_id,ask_id,action_id,proposal_id,submission_version), + FOREIGN KEY (authority,review_request_id,ask_id,action_id,proposal_id,submission_version) + REFERENCES registry_internal.registry_proposal_review_asks + (authority,review_request_id,ask_id,action_id,proposal_id,submission_version) + ); + CREATE INDEX IF NOT EXISTS registry_proposal_review_ask_answer_jobs + ON registry_internal.registry_proposal_review_ask_answers(next_attempt_at,answered_at) + WHERE delivery_state='pending'; + CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_review_ask_files ( + authority text NOT NULL, + review_request_id uuid NOT NULL, + ask_id uuid NOT NULL, + action_id text NOT NULL, + proposal_id uuid NOT NULL, + submission_version bigint NOT NULL, + addition_id uuid NOT NULL, + PRIMARY KEY (action_id,proposal_id,submission_version,addition_id), + FOREIGN KEY (authority,review_request_id,ask_id,action_id,proposal_id,submission_version) + REFERENCES registry_internal.registry_proposal_review_ask_answers + (authority,review_request_id,ask_id,action_id,proposal_id,submission_version), + FOREIGN KEY (action_id,proposal_id,submission_version,addition_id) + REFERENCES registry_internal.registry_proposal_additions + (action_id,proposal_id,submission_version,addition_id) + ); + CREATE INDEX IF NOT EXISTS registry_proposal_review_submissions_request + ON registry_internal.registry_proposal_review_submissions + (authority, producer_id, (accepted_binding->>'requestId')) + WHERE accepted_binding IS NOT NULL; + CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_review_ask_announcements ( + authority text NOT NULL CHECK (octet_length(authority) BETWEEN 1 AND 128), + producer_id text NOT NULL CHECK (octet_length(producer_id) BETWEEN 1 AND 128), + review_request_id uuid NOT NULL, + ask_id uuid NOT NULL, + event_id uuid NOT NULL, + announcement jsonb NOT NULL CHECK (jsonb_typeof(announcement)='object' AND octet_length(announcement::text)<=1024), + expires_at timestamptz NOT NULL, + PRIMARY KEY (authority,review_request_id,ask_id) + ); + CREATE INDEX IF NOT EXISTS registry_proposal_review_ask_announcements_expiry + ON registry_internal.registry_proposal_review_ask_announcements(authority,expires_at); + CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_review_ask_feed_checkpoints ( + authority text PRIMARY KEY CHECK (octet_length(authority) BETWEEN 1 AND 128), + cursor uuid, + updated_at timestamptz NOT NULL DEFAULT transaction_timestamp() + ); + CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_review_ask_feed_events ( + authority text NOT NULL CHECK (octet_length(authority) BETWEEN 1 AND 128), + event_id uuid NOT NULL, + review_request_id uuid NOT NULL, + ask_id uuid NOT NULL, + state text NOT NULL CHECK (state IN ('mirrored','unknown','refused')), + error_code text CHECK (error_code IS NULL OR octet_length(error_code) BETWEEN 1 AND 128), + observed_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + PRIMARY KEY (authority,event_id) + ); + -- Receipts without an observed policy retain the maximum recovery window. + -- New receipts store the configured authority window explicitly. + ALTER TABLE registry_internal.registry_proposal_review_ask_feed_events + ADD COLUMN IF NOT EXISTS recovery_days integer NOT NULL DEFAULT 3650 + CHECK (recovery_days BETWEEN 1 AND 3650); + CREATE INDEX IF NOT EXISTS registry_proposal_review_ask_feed_events_observed + ON registry_internal.registry_proposal_review_ask_feed_events(observed_at);" + ).await.map_err(|_| MutationError::Unavailable) +} + +#[derive(Clone, serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct AnswerBody { + pub(crate) text: Option, + #[serde(default)] + pub(crate) additions: Vec, +} + +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct AnswerMutation { + pub(crate) ask_id: Uuid, + pub(crate) body: AnswerBody, +} + +impl AnswerBody { + pub(crate) fn validate( + &self, + wants: &[registry_review_client::ReviewAskWant], + ) -> Result<(), &'static str> { + let requires_text = wants + .iter() + .any(|want| matches!(want, registry_review_client::ReviewAskWant::Answer {})); + if self + .text + .as_ref() + .is_some_and(|text| text.trim().is_empty() || text.len() > 2000 || text.contains('\0')) + || (requires_text && self.text.is_none()) + { + return Err("text"); + } + let distinct = self + .additions + .iter() + .collect::>(); + if self.additions.len() > 32 + || distinct.len() != self.additions.len() + || self.additions.iter().any(Uuid::is_nil) + || (wants + .iter() + .any(|want| matches!(want, registry_review_client::ReviewAskWant::Document {})) + && self.additions.is_empty()) + { + return Err("additions"); + } + if self.text.is_none() && self.additions.is_empty() { + return Err("text"); + } + Ok(()) + } +} + +pub(crate) fn answer_time(now: DateTime, asked: DateTime) -> Option> { + let asked = asked.timestamp_micros().checked_add(i64::from( + !asked.timestamp_subsec_nanos().is_multiple_of(1000), + ))?; + DateTime::from_timestamp_micros(now.timestamp_micros().max(asked)) +} + +fn retryable_status(status: u16) -> bool { + status == 429 || status >= 500 +} + +/// Lifecycle commands hold the Proposal parent lock before closing this version. +pub(super) async fn close_submission( + client: &impl GenericClient, + action: &str, + proposal: Uuid, + version: i64, +) -> Result<(), MutationError> { + client.execute("UPDATE registry_internal.registry_proposal_review_asks SET state='closed',closed_at=GREATEST(transaction_timestamp(),asked_at) WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND state='open'",&[&action,&proposal,&version]).await.map_err(|_|MutationError::Unavailable)?; + client.execute("UPDATE registry_internal.registry_proposal_review_ask_answers SET delivery_state='superseded',claim_token=NULL,lease_until=NULL,last_error_code=NULL WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND delivery_state='pending'",&[&action,&proposal,&version]).await.map_err(|_|MutationError::Unavailable)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use registry_review_client::ReviewAskWant; + use serde_json::json; + + #[test] + fn answer_text_is_required_nonblank_and_bounded_in_utf8_bytes() { + let wants = [ReviewAskWant::Answer {}]; + for text in [ + None, + Some(" ".to_owned()), + Some("é".repeat(1001)), + Some("\0".to_owned()), + ] { + let body = AnswerBody { + text, + additions: vec![], + }; + assert_eq!(body.validate(&wants), Err("text")); + } + let body = AnswerBody { + text: Some("A multiline\nanswer".to_owned()), + additions: vec![], + }; + assert_eq!(body.validate(&wants), Ok(())); + assert!(serde_json::from_value::(json!({"other":"private"})).is_err()); + } + + #[test] + fn empty_wants_still_require_an_answer_content() { + assert_eq!( + AnswerBody { + text: None, + additions: vec![] + } + .validate(&[]), + Err("text") + ); + assert!(AnswerBody { + text: Some("explanation".into()), + additions: vec![] + } + .validate(&[]) + .is_ok()); + assert!(AnswerBody { + text: None, + additions: vec![Uuid::new_v4()] + } + .validate(&[]) + .is_ok()); + } + + #[test] + fn document_answers_require_distinct_non_nil_addition_ids() { + let wants = [ReviewAskWant::Document {}]; + let id = Uuid::new_v4(); + for additions in [ + vec![], + vec![Uuid::nil()], + vec![id, id], + (0..33).map(|_| Uuid::new_v4()).collect(), + ] { + assert_eq!( + AnswerBody { + text: None, + additions + } + .validate(&wants), + Err("additions") + ); + } + assert_eq!( + AnswerBody { + text: None, + additions: vec![id] + } + .validate(&wants), + Ok(()) + ); + assert_eq!( + AnswerBody { + text: None, + additions: vec![] + } + .validate(&[]), + Err("text") + ); + } + + #[test] + fn answer_time_never_precedes_a_future_nanosecond_ask() { + let asked = "2026-11-27T10:00:00.123456001Z" + .parse::>() + .unwrap(); + let now = asked - chrono::Duration::hours(1); + let stored = answer_time(now, asked).unwrap(); + assert!(stored >= asked); + assert_eq!(stored.timestamp_subsec_nanos() % 1000, 0); + assert_eq!(stored.timestamp_micros(), asked.timestamp_micros() + 1); + let later = asked + chrono::Duration::hours(1); + assert_eq!( + answer_time(later, asked).unwrap().timestamp_micros(), + later.timestamp_micros() + ); + } + + #[test] + fn delivery_retries_rate_limits_and_server_errors_but_not_other_client_refusals() { + assert!(retryable_status(429)); + assert!(retryable_status(503)); + for status in [400, 401, 403, 404, 409, 422] { + assert!(!retryable_status(status)); + } + } +} diff --git a/crates/registry-breg/src/review_store/asks/delivery.rs b/crates/registry-breg/src/review_store/asks/delivery.rs new file mode 100644 index 0000000000..bdcaae1ce0 --- /dev/null +++ b/crates/registry-breg/src/review_store/asks/delivery.rs @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Lease a value-free answer notification before I/O, then fence its receipt. +use super::*; +use registry_review_client::{ + ReviewAsk, ReviewAskAnswer, ReviewAskAnswerResponse, ReviewAskResponse, +}; +use serde_json::json; + +enum Outcome { + Delivered(Box), + Refused(String), + Retry, +} + +fn outcome(reply: Result) -> Outcome { + match reply { + Ok(ReviewAskAnswerResponse::Answered(answer)) => Outcome::Delivered(Box::new(answer.value)), + Ok(ReviewAskAnswerResponse::NotOpen { .. }) => { + Outcome::Refused("review.ask-not-open".into()) + } + Ok(ReviewAskAnswerResponse::ConcealedOrUnknown { .. }) => { + Outcome::Refused("ask-concealed-or-unknown".into()) + } + Err(ReviewClientError::Problem { status, problem }) + if (400..500).contains(&status) && !matches!(status, 408 | 429) => + { + Outcome::Refused(problem.code.as_str().into()) + } + Err(ReviewClientError::Protocol { status, .. }) + if (400..500).contains(&status) && !matches!(status, 408 | 429) => + { + Outcome::Refused("answer-delivery-refused".into()) + } + Err(ReviewClientError::Configuration { .. }) => { + Outcome::Refused("answer-delivery-configuration".into()) + } + Err(ReviewClientError::InvalidRequest { .. }) => { + Outcome::Refused("answer-delivery-invalid-request".into()) + } + Err(_) => Outcome::Retry, + } +} + +pub(crate) async fn deliver_one( + client: &mut tokio_postgres::Client, + authority: &ReviewAuthorityClient, +) -> Result { + let expired = client.execute("UPDATE registry_internal.registry_proposal_review_ask_answers SET delivery_state='refused',last_error_code=CASE WHEN delivery_deadline<=transaction_timestamp() THEN 'answer-delivery-expired' ELSE 'answer-delivery-attempts-exhausted' END,claim_token=NULL,lease_until=NULL WHERE authority=$1 AND delivery_state='pending' AND (delivery_deadline<=transaction_timestamp() OR attempt_count>=1000) AND (lease_until IS NULL OR lease_until>'requestId'=j.review_request_id::text AND s.state='accepted' AND NOT s.withdrawn AND p.state='submitted' AND p.blocked_reason IS NULL AND j.delivery_state='pending' AND j.delivery_deadline>transaction_timestamp() AND j.attempt_count<1000 AND j.next_attempt_at<=transaction_timestamp() AND (j.lease_until IS NULL OR j.lease_until 0); + }; + let action: String = row.get(0); + let proposal: Uuid = row.get(1); + let version: i64 = row.get(2); + let request: Uuid = row.get(3); + let ask: Uuid = row.get(4); + let answered_at: DateTime = row.get(5); + let key: String = row.get(6); + let attempts: i32 = row.get(7); + // The claim is committed before token acquisition or authority calls. + let accepted: ReviewRequestAccepted=serde_json::from_value(client.query_one("SELECT accepted_binding FROM registry_internal.registry_proposal_review_submissions WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3",&[&action,&proposal,&version]).await.map_err(|_| MutationError::Unavailable)?.get(0)).map_err(|_| MutationError::Unavailable)?; + let token = authority.token_provider.bearer_token().await.ok(); + let delivery = match &token { + Some(token) => outcome( + authority + .client + .answer_ask( + ReviewAuth::new(token, &authority.profile), + &key, + &accepted, + ask, + &ReviewAskAnswer { + subject: accepted.subject.clone(), + answered_at, + }, + ) + .await, + ), + None => Outcome::Retry, + }; + let mut observed = None; + if matches!(&delivery,Outcome::Refused(code) if code=="review.ask-not-open") { + if let Some(token) = &token { + if let Ok(ReviewAskResponse::Available(ask)) = authority + .client + .ask(ReviewAuth::new(token, &authority.profile), &accepted, ask) + .await + { + observed = Some(Box::new(ask.value)); + } + } + } + let tx = client + .transaction() + .await + .map_err(|_| MutationError::Unavailable)?; + tx.query_one("SELECT 1 FROM registry_internal.registry_proposal_state WHERE action_id=$1 AND proposal_id=$2 FOR UPDATE",&[&action,&proposal]).await.map_err(|_| MutationError::Unavailable)?; + let current = tx.query_opt("SELECT 1 FROM registry_internal.registry_proposal_review_ask_answers a JOIN registry_internal.registry_proposal_review_submissions s USING(action_id,proposal_id,submission_version) JOIN registry_internal.registry_proposal_state p USING(action_id,proposal_id,submission_version) WHERE a.authority=$1 AND a.review_request_id=$2 AND a.ask_id=$3 AND a.claim_token=$4 AND a.delivery_state='pending' AND s.accepted_binding=$5 AND s.authority=a.authority AND s.producer_id=$6 AND NOT s.withdrawn AND s.state='accepted' AND p.state='submitted' AND p.blocked_reason IS NULL",&[&authority.authority,&request,&ask,&claim,&json!(accepted),&authority.producer_id]).await.map_err(|_| MutationError::Unavailable)?.is_some(); + if !current { + return Ok(false); + } + let (state, code, remote) = match delivery { + Outcome::Delivered(ask) => ("delivered", None, Some(ask)), + Outcome::Refused(code) => ("refused", Some(code), observed), + Outcome::Retry => ("pending", Some("answer-delivery-unavailable".into()), None), + }; + let delay = i64::try_from(feed_backoff_delay(attempts as u32).as_secs()) + .map_err(|_| MutationError::Unavailable)?; + tx.execute("UPDATE registry_internal.registry_proposal_review_ask_answers SET delivery_state=$5,last_error_code=$6,claim_token=NULL,lease_until=NULL,next_attempt_at=transaction_timestamp()+($7::bigint*interval '1 second'),delivered_at=CASE WHEN $5='delivered' THEN transaction_timestamp() ELSE delivered_at END WHERE authority=$1 AND review_request_id=$2 AND ask_id=$3 AND claim_token=$4",&[&authority.authority,&request,&ask,&claim,&state,&code,&delay]).await.map_err(|_| MutationError::Unavailable)?; + if let Some(remote) = remote { + let incoming = + serde_json::to_value(remote.state).map_err(|_| MutationError::Unavailable)?; + let incoming = incoming.as_str().ok_or(MutationError::Unavailable)?; + if incoming != "open" { + // A stored on-time notification can settle an expired provider ask. + tx.execute("UPDATE registry_internal.registry_proposal_review_asks SET state=$4,answered_at=$5,closed_at=$6 WHERE authority=$1 AND review_request_id=$2 AND ask_id=$3 AND detail_erased_at IS NULL",&[&authority.authority,&request,&ask,&incoming,&remote.answered_at,&remote.closed_at]).await.map_err(|_| MutationError::Unavailable)?; + } + } + tx.commit().await.map_err(|_| MutationError::Unavailable)?; + if code.as_deref() == Some("review.ask-answer-time-invalid") { + crate::startup::OperationalEvent::ReviewResultLookupsUnavailable.emit(); + } + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + use registry_review_client::{ReviewComplete, ReviewProtocolFailure}; + + #[test] + fn local_answer_errors_stop_but_request_timeouts_retry() { + for (error, expected) in [ + ( + ReviewClientError::Configuration { + reason: "synthetic", + }, + "answer-delivery-configuration", + ), + ( + ReviewClientError::InvalidRequest { + reason: "synthetic", + }, + "answer-delivery-invalid-request", + ), + ] { + assert!(matches!(outcome(Err(error)), Outcome::Refused(code) if code==expected)); + } + assert!(matches!( + outcome(Err(ReviewClientError::Protocol { + status: 408, + failure: ReviewProtocolFailure::Status, + trace_id: None + })), + Outcome::Retry + )); + } + + #[test] + fn delivery_outcomes_separate_receipts_refusals_and_ambiguous_exchanges() { + let ask: ReviewAsk = serde_json::from_value(json!({ + "askId":Uuid::new_v4(),"requestId":Uuid::new_v4(), + "subject":{"source":"source","type":"proposal","id":Uuid::new_v4().to_string(),"version":"1","digest":format!("sha256:{}","a".repeat(64))}, + "text":"Why?","wants":[],"askedAt":"2026-11-27T00:00:00Z","state":"answered","answeredAt":"2026-11-27T01:00:00Z" + })).unwrap(); + assert!(matches!( + outcome(Ok(ReviewAskAnswerResponse::Answered(Box::new( + ReviewComplete { + value: ask, + trace_id: "trace".into() + } + )))), + Outcome::Delivered(_) + )); + assert!( + matches!(outcome(Ok(ReviewAskAnswerResponse::NotOpen{trace_id:"trace".into()})),Outcome::Refused(code) if code=="review.ask-not-open") + ); + assert!( + matches!(outcome(Ok(ReviewAskAnswerResponse::ConcealedOrUnknown{trace_id:"trace".into()})),Outcome::Refused(code) if code=="ask-concealed-or-unknown") + ); + for status in [200, 201, 429, 500, 503] { + assert!(matches!( + outcome(Err(ReviewClientError::Protocol { + status, + failure: ReviewProtocolFailure::Body, + trace_id: None + })), + Outcome::Retry + )); + } + for status in [400, 401, 403, 409, 422] { + assert!( + matches!(outcome(Err(ReviewClientError::Protocol {status,failure:ReviewProtocolFailure::Body,trace_id:None})),Outcome::Refused(code) if code=="answer-delivery-refused") + ); + } + } +} diff --git a/crates/registry-breg/src/review_store/asks/feed.rs b/crates/registry-breg/src/review_store/asks/feed.rs new file mode 100644 index 0000000000..45373d229d --- /dev/null +++ b/crates/registry-breg/src/review_store/asks/feed.rs @@ -0,0 +1,323 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Stage remote observations before committing a complete, cursor-fenced page. +use super::*; +use registry_review_client::{ReviewAsk, ReviewAskFeedEntry, ReviewAskResponse}; +use serde_json::json; + +struct Binding { + action: String, + proposal: Uuid, + version: i64, + accepted: ReviewRequestAccepted, +} +struct Observation { + entry: ReviewAskFeedEntry, + binding: Option, + ask: Option, + state: &'static str, + error: Option<&'static str>, + park_until: Option>, + parked: bool, +} + +fn transient(error: &ReviewClientError) -> bool { + match error { + ReviewClientError::Problem { status, .. } | ReviewClientError::Protocol { status, .. } => { + matches!(status, 401 | 403 | 408) || retryable_status(*status) + } + ReviewClientError::Transport { .. } => true, + _ => false, + } +} + +pub(crate) async fn consume_feed( + client: &mut tokio_postgres::Client, + authority: &ReviewAuthorityClient, + mutations: &crate::postgres::PostgresRecordMutationService, +) -> Result { + // Deadline cleanup must not depend on credentials or authority availability. + let expired = + expire_announcements(client, &authority.authority, authority.recovery_days).await?; + let token = authority + .token_provider + .bearer_token() + .await + .map_err(|_| MutationError::Unavailable)?; + let cursor = checkpoint(client, &authority.authority).await?; + let page = match authority + .client + .ask_feed( + ReviewAuth::new(&token, &authority.profile), + cursor, + Some(100), + ) + .await + { + Ok(page) => page.value, + Err(ReviewClientError::Problem { status: 410, .. }) if cursor.is_some() => { + // Compare the old cursor so a late reset cannot erase another worker's progress. + client.execute("UPDATE registry_internal.registry_proposal_review_ask_feed_checkpoints SET cursor=NULL,updated_at=transaction_timestamp() WHERE authority=$1 AND cursor=$2",&[&authority.authority,&cursor]).await.map_err(|_| MutationError::Unavailable)?; + return Ok(true); + } + Err(_) => return Err(MutationError::Unavailable), + }; + let next = page + .next_cursor + .or_else(|| page.items.last().map(|entry| entry.event_id)) + .or(cursor); + let mut entries = page + .items + .into_iter() + .map(|entry| (entry, false, false)) + .collect::>(); + // Unbound announcements contain only transport identifiers and time, never a question. + // Unmatched rows wait without I/O until a binding appears or their deadline passes. + for row in client.query("SELECT announcement,expires_at<=transaction_timestamp() FROM registry_internal.registry_proposal_review_ask_announcements a WHERE a.authority=$1 AND a.producer_id=$2 AND (a.expires_at<=transaction_timestamp() OR EXISTS(SELECT 1 FROM registry_internal.registry_proposal_review_submissions s WHERE s.authority=a.authority AND s.producer_id=a.producer_id AND s.accepted_binding->>'requestId'=a.review_request_id::text)) ORDER BY a.expires_at,a.ask_id LIMIT 100",&[&authority.authority,&authority.producer_id]).await.map_err(|_| MutationError::Unavailable)? { + entries.push((serde_json::from_value(row.get(0)).map_err(|_| MutationError::Unavailable)?, true, row.get(1))); + } + let changed = expired > 0 || !entries.is_empty(); + let mut staged = Vec::with_capacity(entries.len()); + for (entry, parked, expired) in entries { + if client.query_opt("SELECT 1 FROM registry_internal.registry_proposal_review_ask_feed_events WHERE authority=$1 AND event_id=$2",&[&authority.authority,&entry.event_id]).await.map_err(|_|MutationError::Unavailable)?.is_some() { + continue; + } + if let Some(row)=client.query_opt("SELECT state,asked_at_wire,last_feed_changed_at_wire FROM registry_internal.registry_proposal_review_asks WHERE authority=$1 AND review_request_id=$2 AND ask_id=$3",&[&authority.authority,&entry.request_id,&entry.ask_id]).await.map_err(|_|MutationError::Unavailable)? { + // Terminal mirrors never change through the feed. For a legacy + // open mirror, its opening event has the provider's askedAt time. + let last=row.get::<_,Option>(2).unwrap_or_else(||row.get(1)); + let last=last.parse::>().map_err(|_|MutationError::Unavailable)?; + if row.get::<_,String>(0)!="open" || entry.changed_at<=last { + continue; + } + } + let mut observation = Observation { + entry, + binding: None, + ask: None, + state: "unknown", + error: Some("ask-request-unknown"), + park_until: None, + parked, + }; + if expired { + staged.push(observation); + continue; + } + // A nonunique index permits upgrading a database that already contains duplicates. + // Ambiguous authority output is counted and skipped rather than stalling the page. + let rows = client.query("SELECT action_id,proposal_id,submission_version,accepted_binding,recovery_deadline<=transaction_timestamp() FROM registry_internal.registry_proposal_review_submissions WHERE authority=$1 AND producer_id=$2 AND accepted_binding->>'requestId'=$3 LIMIT 2",&[&authority.authority,&authority.producer_id,&observation.entry.request_id.to_string()]).await.map_err(|_| MutationError::Unavailable)?; + if rows.len() > 1 { + observation.error = Some("ask-request-ambiguous"); + } else if let Some(row) = rows.first() { + if parked && row.get::<_, bool>(4) { + staged.push(observation); + continue; + } + let binding = Binding { + action: row.get(0), + proposal: row.get(1), + version: row.get(2), + accepted: serde_json::from_value(row.get(3)) + .map_err(|_| MutationError::Unavailable)?, + }; + let (ask, state, error) = match authority + .client + .ask( + ReviewAuth::new(&token, &authority.profile), + &binding.accepted, + observation.entry.ask_id, + ) + .await + { + Ok(ReviewAskResponse::Available(ask)) => (Some(ask.value), "mirrored", None), + Ok(ReviewAskResponse::ConcealedOrUnknown { .. }) => { + (None, "refused", Some("ask-concealed-or-unknown")) + } + Err(error) if transient(&error) => return Err(MutationError::Unavailable), + Err(ReviewClientError::Configuration { .. }) => { + (None, "refused", Some("ask-read-configuration")) + } + Err(ReviewClientError::InvalidRequest { .. }) => { + (None, "refused", Some("ask-read-invalid-request")) + } + Err(_) => (None, "refused", Some("ask-protocol-refused")), + }; + observation.binding = Some(binding); + observation.ask = ask; + observation.state = state; + observation.error = error; + } else { + // Before acceptance there is no trustworthy request-to-submission mapping. + // Retain only the announcement, no longer than any candidate hand-off can recover. + observation.park_until = client.query_one("SELECT max(s.recovery_deadline) FROM registry_internal.registry_proposal_review_submissions s JOIN registry_internal.registry_proposal_submissions p USING(action_id,proposal_id,submission_version) WHERE s.authority=$1 AND s.producer_id=$2 AND s.accepted_binding IS NULL AND s.state IN ('pending','submitting','uncertain') AND NOT s.withdrawn AND p.erased_at IS NULL AND s.recovery_deadline>transaction_timestamp()",&[&authority.authority,&authority.producer_id]).await.map_err(|_| MutationError::Unavailable)?.get(0); + } + staged.push(observation); + } + // No outbound I/O below this point. A page commits all observations and its cursor together. + let tx = client + .transaction() + .await + .map_err(|_| MutationError::Unavailable)?; + tx.query_one( + "SELECT pg_advisory_xact_lock(hashtext('breg-ask-feed'),hashtext($1))", + &[&authority.authority], + ) + .await + .map_err(|_| MutationError::Unavailable)?; + if checkpoint(&tx, &authority.authority).await? != cursor { + return Ok(false); + } + for observation in staged { + let Observation { + entry, + mut binding, + mut ask, + mut state, + mut error, + park_until, + parked, + } = observation; + let recorded = tx.query_opt("SELECT 1 FROM registry_internal.registry_proposal_review_ask_feed_events WHERE authority=$1 AND event_id=$2",&[&authority.authority,&entry.event_id]).await.map_err(|_| MutationError::Unavailable)?; + if recorded.is_some() { + remove_parked(&tx, &authority.authority, &entry).await?; + continue; + } + if parked && tx.query_opt("SELECT 1 FROM registry_internal.registry_proposal_review_ask_announcements WHERE authority=$1 AND review_request_id=$2 AND ask_id=$3 AND expires_at>transaction_timestamp()",&[&authority.authority,&entry.request_id,&entry.ask_id]).await.map_err(|_|MutationError::Unavailable)?.is_none() { + // An observation fetched before expiry cannot restore question detail afterward. + binding=None; + ask=None; + state="unknown"; + error=Some("ask-request-unknown"); + } + if let Some(deadline) = park_until { + let count:i64 = tx.query_one("SELECT count(*) FROM registry_internal.registry_proposal_review_ask_announcements WHERE authority=$1 AND review_request_id=$2",&[&authority.authority,&entry.request_id]).await.map_err(|_| MutationError::Unavailable)?.get(0); + let already_parked=tx.query_opt("SELECT 1 FROM registry_internal.registry_proposal_review_ask_announcements WHERE authority=$1 AND review_request_id=$2 AND ask_id=$3",&[&authority.authority,&entry.request_id,&entry.ask_id]).await.map_err(|_|MutationError::Unavailable)?.is_some(); + if count < crate::contract::MAX_MIRRORED_REVIEW_ASKS as i64 || already_parked { + let inserted = tx.execute("INSERT INTO registry_internal.registry_proposal_review_ask_announcements(authority,producer_id,review_request_id,ask_id,event_id,announcement,expires_at) SELECT $1,$2,$3,$4,$5,$6,$7 WHERE $7>transaction_timestamp() ON CONFLICT(authority,review_request_id,ask_id) DO NOTHING",&[&authority.authority,&authority.producer_id,&entry.request_id,&entry.ask_id,&entry.event_id,&json!(entry),&deadline]).await.map_err(|_| MutationError::Unavailable)?; + if inserted > 0 || already_parked { + continue; + } + } + error = Some( + if count >= crate::contract::MAX_MIRRORED_REVIEW_ASKS as i64 { + "ask-limit-reached" + } else { + "ask-request-unknown" + }, + ); + } + if let (Some(binding), Some(ask)) = (binding, ask) { + // Parent first, matching lifecycle commands, delivery and operator erasure. + let row = tx.query_opt("SELECT state,submission_version,blocked_reason FROM registry_internal.registry_proposal_state WHERE action_id=$1 AND proposal_id=$2 FOR UPDATE",&[&binding.action,&binding.proposal]).await.map_err(|_| MutationError::Unavailable)?.ok_or(MutationError::Unavailable)?; + let current = row.get::<_, String>(0) == "submitted" + && row.get::<_, i64>(1) == binding.version + && row.get::<_, Option>(2).is_none(); + let retained = tx.query_opt("SELECT NOT s.withdrawn,p.erased_at IS NOT NULL FROM registry_internal.registry_proposal_review_submissions s JOIN registry_internal.registry_proposal_submissions p USING(action_id,proposal_id,submission_version) WHERE s.authority=$1 AND s.action_id=$2 AND s.proposal_id=$3 AND s.submission_version=$4 AND s.accepted_binding=$5 AND s.producer_id=$6",&[&authority.authority,&binding.action,&binding.proposal,&binding.version,&json!(binding.accepted),&authority.producer_id]).await.map_err(|_| MutationError::Unavailable)?; + if let Some(retained) = retained { + if retained.get::<_, bool>(1) { + state = "unknown"; + error = Some("ask-submission-erased"); + } else { + let existing = tx.query_opt("SELECT 1 FROM registry_internal.registry_proposal_review_asks WHERE authority=$1 AND review_request_id=$2 AND ask_id=$3",&[&authority.authority,&entry.request_id,&entry.ask_id]).await.map_err(|_| MutationError::Unavailable)?.is_some(); + let count:i64 = tx.query_one("SELECT count(*) FROM registry_internal.registry_proposal_review_asks WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3",&[&binding.action,&binding.proposal,&binding.version]).await.map_err(|_| MutationError::Unavailable)?.get(0); + if !existing && count >= crate::contract::MAX_MIRRORED_REVIEW_ASKS as i64 { + state = "unknown"; + error = Some("ask-limit-reached"); + } else { + let open = current && retained.get::<_, bool>(0); + let remote = serde_json::to_value(ask.state) + .map_err(|_| MutationError::Unavailable)?; + let incoming = if open { + remote.as_str().ok_or(MutationError::Unavailable)? + } else { + "closed" + }; + let inserted = tx.execute("INSERT INTO registry_internal.registry_proposal_review_asks (authority,review_request_id,ask_id,action_id,proposal_id,submission_version,text,wants,asked_at,asked_at_wire,due_at,due_at_wire,state,answered_at,closed_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,CASE WHEN $13='closed' THEN GREATEST(transaction_timestamp(),$9) ELSE $15 END) ON CONFLICT(authority,review_request_id,ask_id) DO NOTHING",&[&authority.authority,&entry.request_id,&entry.ask_id,&binding.action,&binding.proposal,&binding.version,&ask.text,&json!(ask.wants),&ask.asked_at,&ask.asked_at.to_rfc3339(),&ask.due_at,&ask.due_at.map(|at|at.to_rfc3339()),&incoming,&ask.answered_at,&ask.closed_at]).await.map_err(|_| MutationError::Unavailable)?; + if inserted == 0 && incoming != "open" { + let updated = tx.execute("UPDATE registry_internal.registry_proposal_review_asks SET state=$4,answered_at=$5,closed_at=CASE WHEN $4='closed' THEN GREATEST(transaction_timestamp(),asked_at) ELSE $6 END WHERE authority=$1 AND review_request_id=$2 AND ask_id=$3 AND state='open' AND detail_erased_at IS NULL",&[&authority.authority,&entry.request_id,&entry.ask_id,&incoming,&ask.answered_at,&ask.closed_at]).await.map_err(|_| MutationError::Unavailable)?; + if updated > 0 && current { + mutations + .record_review_change( + &tx, + &authority.authority, + &binding.action, + binding.proposal, + binding.version, + "ask-state-changed", + ) + .await?; + } + } else if inserted > 0 && incoming == "open" { + mutations + .record_review_change( + &tx, + &authority.authority, + &binding.action, + binding.proposal, + binding.version, + "asked", + ) + .await?; + } + } + } + } else { + state = "unknown"; + error = Some("ask-binding-changed"); + } + } + if parked { + remove_parked(&tx, &authority.authority, &entry).await?; + } + if state == "mirrored" { + tx.execute("UPDATE registry_internal.registry_proposal_review_asks SET last_feed_changed_at_wire=$4 WHERE authority=$1 AND review_request_id=$2 AND ask_id=$3",&[&authority.authority,&entry.request_id,&entry.ask_id,&entry.changed_at.to_rfc3339()]).await.map_err(|_|MutationError::Unavailable)?; + } + tx.execute("INSERT INTO registry_internal.registry_proposal_review_ask_feed_events(authority,event_id,review_request_id,ask_id,state,error_code,recovery_days) VALUES($1,$2,$3,$4,$5,$6,$7)",&[&authority.authority,&entry.event_id,&entry.request_id,&entry.ask_id,&state,&error,&(authority.recovery_days as i32)]).await.map_err(|_| MutationError::Unavailable)?; + if state != "mirrored" { + tracing::debug!( + outcome = state, + code = error, + "BReg skipped an ask announcement" + ); + } + } + tx.execute("INSERT INTO registry_internal.registry_proposal_review_ask_feed_checkpoints(authority,cursor) VALUES($1,$2) ON CONFLICT(authority) DO UPDATE SET cursor=EXCLUDED.cursor,updated_at=transaction_timestamp()",&[&authority.authority,&next]).await.map_err(|_| MutationError::Unavailable)?; + tx.commit().await.map_err(|_| MutationError::Unavailable)?; + Ok(changed) +} + +async fn expire_announcements( + client: &mut tokio_postgres::Client, + authority: &str, + recovery_days: u32, +) -> Result { + let tx = client + .transaction() + .await + .map_err(|_| MutationError::Unavailable)?; + tx.query_one( + "SELECT pg_advisory_xact_lock(hashtext('breg-ask-feed'),hashtext($1))", + &[&authority], + ) + .await + .map_err(|_| MutationError::Unavailable)?; + let count=tx.execute("WITH expired AS (DELETE FROM registry_internal.registry_proposal_review_ask_announcements WHERE authority=$1 AND expires_at<=transaction_timestamp() RETURNING event_id,review_request_id,ask_id) INSERT INTO registry_internal.registry_proposal_review_ask_feed_events(authority,event_id,review_request_id,ask_id,state,error_code,recovery_days) SELECT $1,event_id,review_request_id,ask_id,'unknown','ask-request-unknown',$2 FROM expired ON CONFLICT(authority,event_id) DO NOTHING",&[&authority,&(recovery_days as i32)]).await.map_err(|_|MutationError::Unavailable)?; + tx.commit().await.map_err(|_| MutationError::Unavailable)?; + Ok(count) +} + +async fn remove_parked( + client: &impl GenericClient, + authority: &str, + entry: &ReviewAskFeedEntry, +) -> Result<(), MutationError> { + client.execute("DELETE FROM registry_internal.registry_proposal_review_ask_announcements WHERE authority=$1 AND review_request_id=$2 AND ask_id=$3",&[&authority,&entry.request_id,&entry.ask_id]).await.map_err(|_|MutationError::Unavailable)?; + Ok(()) +} + +async fn checkpoint( + client: &impl GenericClient, + authority: &str, +) -> Result, MutationError> { + Ok(client.query_opt("SELECT cursor FROM registry_internal.registry_proposal_review_ask_feed_checkpoints WHERE authority=$1",&[&authority]).await.map_err(|_|MutationError::Unavailable)?.and_then(|row|row.get(0))) +} diff --git a/crates/registry-breg/src/tests/action_evidence_fixture.rs b/crates/registry-breg/src/tests/action_evidence_fixture.rs index d319c1274f..0e1629b4bf 100644 --- a/crates/registry-breg/src/tests/action_evidence_fixture.rs +++ b/crates/registry-breg/src/tests/action_evidence_fixture.rs @@ -25,6 +25,28 @@ pub(crate) fn registry(evidence: bool) -> crate::CompiledRegistry { source["evidenceProviders"] = json!({"farmer-registry": {"contracts":"evidence/contracts.json","subjectResolution":"trusted-provider-exact-selector"}}); let action = &mut source["actions"]["correct-address"]; action["inputs"].as_array_mut().unwrap().push(json!({"id":"subject","type":"string","required":true,"minimumLength":3,"maximumLength":77,"classification":"restricted"})); + // The added input is writable through edit, so every grant that edits must read it. + for profile in source["accessProfiles"] + .as_object_mut() + .unwrap() + .values_mut() + { + let grants = profile + .pointer_mut("/permissions/proposals") + .and_then(Value::as_array_mut); + for grant in grants.into_iter().flatten() { + if grant["action"] != "correct-address" { + continue; + } + if let Some(readable) = grant + .get_mut("readableInputs") + .and_then(Value::as_array_mut) + { + readable.push(json!("subject")); + } + } + } + let action = &mut source["actions"]["correct-address"]; action["commitGuards"]["evidence"] = json!([{ "id":"status","provider":"farmer-registry","requirement":"urn:example:farmer:status-v1", "subjects":{"farmer":{"profile":"farmer-number-v1","selectors":{"farmer-number":{"type":"input","input":"subject"}}}}, diff --git a/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs b/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs index 00797af48e..b28300e283 100644 --- a/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs +++ b/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs @@ -1067,7 +1067,8 @@ fn a_caller_document_declares_the_workflow_write_refusal_only_to_a_bound_writer( registry.actions(), registry.entities(), Some(&visible), - ); + ) + .unwrap(); assert_eq!( paths["/v1/proposals/{proposal_id}/apply"]["post"]["responses"]["403"].is_object(), declared, @@ -1101,7 +1102,7 @@ fn compiled_bound_writer_registry() -> CompiledRegistry { {"action": "propose-person-phone", "operations": ["start"], "targets": targets}], "proposals": [{"action": "propose-person-phone", "ownership": "caller", "operations": ["get", "list", "edit", "submit", "cancel", "apply"], - "targets": targets}]}}) + "readableInputs": ["person", "phone"], "targets": targets}]}}) }; let source = json!({"datasets": {"test-dataset": {}}, "apiVersion": "id.registrystack.org/formats/breg/project/v1alpha1", "kind": "BRegProject", @@ -1168,7 +1169,8 @@ fn a_caller_document_declares_a_record_condition_write_refusal_to_a_bound_writer registry.actions(), registry.entities(), Some(&visible), - ); + ) + .unwrap(); assert_eq!( paths["/v1/proposals/{proposal_id}/apply"]["post"]["responses"]["403"].is_object(), declared, @@ -1216,6 +1218,7 @@ fn compiled_record_condition_writer_registry(effect: &str) -> CompiledRegistry { {"action": "propose-person", "operations": ["start"], "targets": targets}], "proposals": [{"action": "propose-person", "ownership": "caller", "operations": ["get", "list", "edit", "submit", "cancel", "apply"], + "readableInputs": if effect == "patch" { json!(["person", "phone"]) } else { json!(["phone"]) }, "targets": targets}]}}) }; let source = json!({"datasets": {"test-dataset": {}}, diff --git a/crates/registry-breg/tests/action_evidence_compiler.rs b/crates/registry-breg/tests/action_evidence_compiler.rs index e0ab40e136..bb83ff0f78 100644 --- a/crates/registry-breg/tests/action_evidence_compiler.rs +++ b/crates/registry-breg/tests/action_evidence_compiler.rs @@ -133,6 +133,53 @@ fn commit_evidence_binds_typed_selectors_predicates_and_final_revision() { json!(1); assert!(compile(source, Some(reviewed)).is_err()); } + +#[test] +fn proposal_apply_declares_commit_evidence_failure_but_submit_does_not() { + let mut source = configured(); + let action = &mut source["actions"]["register-person"]; + action.as_object_mut().unwrap().remove("evidence"); + action["execution"] = json!({"mode":"proposal","proposal":{ + "review":{"type":"none"},"application":{"mode":"manual"},"retention":{"mode":"operator-erase"} + }}); + action["inputs"][0]["minimumLength"] = json!(1); + action["commitGuards"] = json!({ + "targets":[{"input":"person","revision":"unchanged"}], + "evidence":[{ + "id":"commit-status","provider":"provider","requirement":"urn:example:client:requirement:status:v1", + "subjects":{"subject":{"profile":"record-lookup-v1","selectors":{"record_reference":{"type":"input","input":"given-name"}}}}, + "requires":[{"output":"status-holds","equals":true}],"maximumObservationAgeSeconds":60 + }] + }); + source["functions"]["register-plan"]["capabilities"] = json!([]); + let permissions = &mut source["accessProfiles"]["registrar"]["permissions"]; + permissions["actions"][0]["operations"] = json!(["start"]); + permissions["actions"][0] + .as_object_mut() + .unwrap() + .remove("results"); + permissions["proposals"] = json!([{"action":"register-person","operations":["get","submit","apply"], + "ownership":"caller","readableInputs":["given-name","family-name","person"], + "targets":[{"recordType":"person","rowBoundaries":"unrestricted"}]}]); + let mut contract = contracts(); + contract["definitions"][0]["subjects"][0]["selector"]["fields"] = + json!([{"type":"string","name":"record_reference","minimumBytes":1,"maximumBytes":200}]); + let registry = compile(source, Some(contract)).unwrap(); + let api: Value = + serde_json::from_slice(®istry.artifacts().entries()["generated/openapi.json"].bytes) + .unwrap(); + assert_eq!( + api["paths"]["/v1/proposals/{proposal_id}/apply"]["post"]["responses"]["503"]["content"] + ["application/problem+json"]["examples"]["action.evidence_failed"]["value"]["code"], + "action.evidence_failed" + ); + assert!( + api["paths"]["/v1/proposals/{proposal_id}/submit"]["post"]["responses"]["503"]["content"] + ["application/problem+json"]["examples"] + .get("action.evidence_failed") + .is_none() + ); +} #[test] fn refuses_origin_profile_output_ambiguity_and_budget_widening() { for change in [ diff --git a/crates/registry-breg/tests/attachment_promotion_compiler.rs b/crates/registry-breg/tests/attachment_promotion_compiler.rs index 7d0107fbc4..c8472d5dc7 100644 --- a/crates/registry-breg/tests/attachment_promotion_compiler.rs +++ b/crates/registry-breg/tests/attachment_promotion_compiler.rs @@ -45,11 +45,227 @@ fn source() -> Value { "actions":[{"action":"amend","operations":["start"],"targets":[ {"recordType":"application","rowBoundaries":"unrestricted"}]}], "proposals":[{"action":"amend","operations":["get","list","edit","submit","apply"], - "ownership":"caller","readableAttachments":["document"], + "ownership":"caller","readableInputs":["target","name"],"readableAttachments":["document"], "writableAttachments":["document"],"targets":[ {"recordType":"application","rowBoundaries":"unrestricted"}]}]}}}}) } +fn addition_source() -> Value { + mutated(|source| { + source["reviewAuthorities"] = + json!({"local-review":{"protocol":"id.registrystack.org/protocols/review/v1"}}); + source["actions"]["amend"]["execution"]["proposal"]["review"] = json!({ + "type":"required","authority":"local-review","source":"promotion-compiler","policy":{"id":"addition-review"}}); + source["actions"]["amend"]["execution"]["proposal"]["additions"] = json!({ + "id":"supporting","maximumBytes":64,"maximumCount":2, + "contentTypes":["text/plain"],"classification":"restricted"}); + let grant = &mut source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]; + grant["operations"] + .as_array_mut() + .unwrap() + .push(json!("add")); + grant["readableAttachments"] + .as_array_mut() + .unwrap() + .push(json!("supporting")); + grant["writableAttachments"] + .as_array_mut() + .unwrap() + .push(json!("supporting")); + }) +} + +#[test] +fn additions_require_a_review_that_can_accept_supporting_files() { + let mut source = addition_source(); + source["actions"]["amend"]["execution"]["proposal"]["review"] = json!({"type":"none"}); + let failure = compile(&source).expect_err("an additions slot requires review"); + assert!( + failure + .diagnostics() + .iter() + .any( + |diagnostic| diagnostic.code == "breg.addition.review-required" + && diagnostic.path == "actions[id=amend].execution.proposal.additions" + ), + "{:?}", + failure.diagnostics() + ); +} + +#[test] +fn additions_declaration_and_slot_changes_advance_the_action_revision() { + let mut declared = addition_source(); + let grant = &mut declared["accessProfiles"]["clerk"]["permissions"]["proposals"][0]; + grant["operations"] = json!(["get", "list", "edit", "submit", "apply"]); + grant["readableAttachments"] = json!(["document"]); + grant["writableAttachments"] = json!(["document"]); + let mut absent = declared.clone(); + absent["actions"]["amend"]["execution"]["proposal"] + .as_object_mut() + .unwrap() + .remove("additions"); + let before = compile(&absent).unwrap().actions().actions[0] + .definition_revision + .clone(); + let current = compile(&declared).unwrap().actions().actions[0] + .definition_revision + .clone(); + assert_ne!( + before, current, + "declaring the slot changes the Action revision" + ); + declared["actions"]["amend"]["execution"]["proposal"]["additions"]["maximumCount"] = json!(1); + assert_ne!( + current, + compile(&declared).unwrap().actions().actions[0].definition_revision, + "changing the slot changes the Action revision" + ); +} + +#[test] +fn additions_compile_as_an_optional_bounded_slot() { + let compiled = compile(&addition_source()).expect("declared additions compile"); + let execution = serde_json::to_value(&compiled.actions().actions[0].execution).unwrap(); + assert_eq!(execution["proposal"]["additions"]["maximumCount"], 2); + let plain = compile(&source()).unwrap(); + let execution = serde_json::to_value(&plain.actions().actions[0].execution).unwrap(); + assert!(execution["proposal"].get("additions").is_none()); +} + +#[test] +fn additions_refuse_invalid_bounds_types_and_collisions() { + for (member, value, code) in [ + ( + "maximumBytes", + json!(0), + "breg.addition.maximum-bytes-bounds-invalid", + ), + ( + "maximumBytes", + json!(16777217), + "breg.addition.maximum-bytes-bounds-invalid", + ), + ( + "maximumCount", + json!(0), + "breg.addition.maximum-count-bounds-invalid", + ), + ( + "maximumCount", + json!(33), + "breg.addition.maximum-count-bounds-invalid", + ), + ( + "contentTypes", + json!([]), + "breg.addition.content-types-bounds-invalid", + ), + ( + "contentTypes", + json!(["text/*"]), + "breg.addition.content-type-invalid", + ), + ( + "contentTypes", + json!(["text/plain", "text/plain"]), + "breg.addition.content-type-duplicate", + ), + ("id", json!("document"), "breg.addition.id-collision"), + ] { + let mut source = addition_source(); + source["actions"]["amend"]["execution"]["proposal"]["additions"][member] = value; + let failure = compile(&source).expect_err("invalid addition slot"); + assert!( + failure.diagnostics().iter().any(|d| d.code == code), + "{code}: {:?}", + failure.diagnostics() + ); + } +} + +#[test] +fn additions_grants_require_the_declared_slot_and_add_authority() { + for missing_slot in [true, false] { + let mut source = addition_source(); + if missing_slot { + source["actions"]["amend"]["execution"]["proposal"] + .as_object_mut() + .unwrap() + .remove("additions"); + } else { + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["operations"] = + json!(["get", "edit", "submit", "apply"]); + } + let failure = compile(&source).expect_err("invalid addition authority"); + assert!( + failure + .diagnostics() + .iter() + .any(|d| d.code == "breg.proposal.attachment-grant-invalid"), + "{:?}", + failure.diagnostics() + ); + } +} + +#[test] +fn additions_review_context_compiles_a_bounded_document_array() { + let mut source = addition_source(); + source["actions"]["amend"]["execution"]["proposal"]["reviewContext"] = json!({ + "id":"review","fields":{"otherDocuments":{"type":"additions","slot":"supporting"}}}); + let compiled = compile(&source).expect("additions context compiles"); + let schema = registry_breg::compiler::review_context::compile_schema( + &compiled, + &compiled.actions().actions[0], + ) + .unwrap() + .unwrap(); + let field = &schema.schema["properties"]["otherDocuments"]; + assert_eq!(field["type"], "array"); + assert_eq!(field["maxItems"], 2); + assert_eq!(field["items"]["properties"]["type"]["const"], "document"); + assert!( + field["items"]["properties"]["download"]["properties"]["path"]["pattern"] + .as_str() + .unwrap() + .contains("/additions/") + ); +} + +#[test] +fn additions_publish_only_the_declared_slots_paths_and_document_schema() { + for declared in [false, true] { + let compiled = compile(&if declared { + addition_source() + } else { + source() + }) + .unwrap(); + let openapi: Value = serde_json::from_slice( + &compiled + .artifacts() + .get("generated/openapi.json") + .unwrap() + .bytes, + ) + .unwrap(); + let paths = openapi["paths"].as_object().unwrap(); + assert_eq!( + paths.contains_key("/v1/proposals/{proposal_id}/additions/supporting"), + declared + ); + assert_eq!( + paths.contains_key("/v1/proposals/{proposal_id}/additions/{addition_id}"), + declared + ); + let schema = &paths["/v1/proposals/{proposal_id}"]["get"]["responses"]["200"]["content"] + ["application/json"]["schema"]; + assert_eq!(schema["properties"].get("additions").is_some(), declared); + assert!(!paths.contains_key("/v1/proposals/{proposal_id}/add")); + } +} + fn compile_bytes(bytes: &[u8]) -> Result { let project = parse_project_json(bytes)?; compile_project(&project, &[], CompileProfile::Authoring) diff --git a/crates/registry-breg/tests/disclosure/fixture.rs b/crates/registry-breg/tests/disclosure/fixture.rs index 999c47c04b..3b33a40b6e 100644 --- a/crates/registry-breg/tests/disclosure/fixture.rs +++ b/crates/registry-breg/tests/disclosure/fixture.rs @@ -9,6 +9,40 @@ use serde_json::{json, Map, Value}; +/// Grants every Proposal grant that edits, revises or rebases the read of the +/// inputs it may write, which the compiler requires. +#[allow(dead_code)] +pub fn grant_readable_inputs(source: &mut Value) { + let actions = source["actions"].clone(); + let Some(profiles) = source["accessProfiles"].as_object_mut() else { + return; + }; + for profile in profiles.values_mut() { + let Some(grants) = profile + .pointer_mut("/permissions/proposals") + .and_then(Value::as_array_mut) + else { + continue; + }; + for grant in grants { + let writes = grant["operations"].as_array().is_some_and(|operations| { + operations.iter().any(|operation| { + matches!(operation.as_str(), Some("edit" | "revise" | "rebase")) + }) + }); + if !writes || grant.get("readableInputs").is_some() { + continue; + } + let inputs: Vec = actions[grant["action"].as_str().unwrap_or_default()] + ["inputs"] + .as_array() + .map(|inputs| inputs.iter().map(|input| input["id"].clone()).collect()) + .unwrap_or_default(); + grant["readableInputs"] = Value::Array(inputs); + } + } +} + use super::postgres_harness::TestDatabase; use registry_breg::compiler::{compile_project, CompileProfile}; use registry_breg::contract::parse_project_json; diff --git a/crates/registry-breg/tests/disclosure/history.rs b/crates/registry-breg/tests/disclosure/history.rs index af3abe61db..5b354ad52d 100644 --- a/crates/registry-breg/tests/disclosure/history.rs +++ b/crates/registry-breg/tests/disclosure/history.rs @@ -117,6 +117,7 @@ fn history_source() -> Value { "plan": {"type": "fixed", "effects": [ {"id": "correct", "target": {"fromInput": "person"}, "operation": "patch", "set": {"family-name": {"fromInput": "name"}}}]}}}); + super::fixture::grant_readable_inputs(&mut source); source } diff --git a/crates/registry-breg/tests/disclosure/proposals.rs b/crates/registry-breg/tests/disclosure/proposals.rs index 32e736fa64..285aa26542 100644 --- a/crates/registry-breg/tests/disclosure/proposals.rs +++ b/crates/registry-breg/tests/disclosure/proposals.rs @@ -134,6 +134,7 @@ fn proposal_project() -> Value { profile["permissions"]["actions"] = json!(actions); profile["permissions"]["proposals"] = json!(proposals); } + super::fixture::grant_readable_inputs(&mut source); source } diff --git a/crates/registry-breg/tests/disclosure/writes.rs b/crates/registry-breg/tests/disclosure/writes.rs index 1c4287c1a1..7857b0688e 100644 --- a/crates/registry-breg/tests/disclosure/writes.rs +++ b/crates/registry-breg/tests/disclosure/writes.rs @@ -89,6 +89,7 @@ fn writes_source() -> Value { "operations": lifecycle, "targets": targets}), ]); } + crate::fixture::grant_readable_inputs(&mut source); source } @@ -1170,6 +1171,7 @@ fn residence_source() -> Value { "operations": proposal_lifecycle(), "targets": targets}), ]); } + crate::fixture::grant_readable_inputs(&mut source); source } diff --git a/crates/registry-breg/tests/disclosure_exposure.rs b/crates/registry-breg/tests/disclosure_exposure.rs index 7902a167cd..c71be4ef56 100644 --- a/crates/registry-breg/tests/disclosure_exposure.rs +++ b/crates/registry-breg/tests/disclosure_exposure.rs @@ -214,7 +214,8 @@ fn acting(bound_by: Option<&str>) -> Value { {"action": "propose-person-phone", "operations": ["start"], "targets": targets}]); registrar["permissions"]["proposals"] = json!([ {"action": "propose-person-phone", "ownership": "caller", - "operations": ["get", "list", "edit", "submit", "cancel", "apply"], "targets": targets}]); + "operations": ["get", "list", "edit", "submit", "cancel", "apply"], + "readableInputs": ["person", "phone"], "targets": targets}]); value } diff --git a/crates/registry-breg/tests/fixtures/event-record/shapes.yaml b/crates/registry-breg/tests/fixtures/event-record/shapes.yaml index 118f9d45e0..3a79eaba91 100644 --- a/crates/registry-breg/tests/fixtures/event-record/shapes.yaml +++ b/crates/registry-breg/tests/fixtures/event-record/shapes.yaml @@ -215,5 +215,6 @@ accessProfiles: proposals: - action: correct-grant-number operations: [get, list, edit, submit, revise, rebase, retry, cancel, apply] + readableInputs: [grant-ref, value] ownership: caller targets: [{recordType: grant, rowBoundaries: unrestricted}] diff --git a/crates/registry-breg/tests/migration_review_permission_order.rs b/crates/registry-breg/tests/migration_review_permission_order.rs index 636d007491..c8a4c06fd0 100644 --- a/crates/registry-breg/tests/migration_review_permission_order.rs +++ b/crates/registry-breg/tests/migration_review_permission_order.rs @@ -69,7 +69,8 @@ fn reversed(action: &CompiledAction) -> CompiledAction { #[test] fn reordering_grants_keeps_the_migration_review_revision() { - let action = compile_action(&project(json!(["edit"]), json!(["get"]))); + // Submit, not Edit: an Edit grant must hold Get, which would overlap the other default's Get. + let action = compile_action(&project(json!(["submit"]), json!(["get"]))); let CompiledActionExecution::Proposal { proposal } = &action.execution else { panic!("Proposal") }; @@ -87,7 +88,7 @@ fn reordering_grants_keeps_the_migration_review_revision() { #[test] fn reordering_start_grants_keeps_the_migration_review_revision() { - let mut value = project(json!(["edit"]), json!(["get"])); + let mut value = project(json!(["submit"]), json!(["get"])); value["accessProfiles"]["second"]["default"] = json!(false); value["accessProfiles"]["second"]["permissions"]["actions"] = json!([ {"action":"correct-case","operations":["start"],"targets":[{"recordType":"case","rowBoundaries":"unrestricted"}]}]); @@ -101,7 +102,7 @@ fn reordering_start_grants_keeps_the_migration_review_revision() { #[test] fn a_changed_default_flag_or_operation_still_changes_the_revision() { - let base = project(json!(["edit"]), json!(["get"])); + let base = project(json!(["submit"]), json!(["get"])); let before = migration_review_revision(&compile_action(&base)); let mut no_default = base.clone(); diff --git a/crates/registry-breg/tests/postgres_native_retention.rs b/crates/registry-breg/tests/postgres_native_retention.rs index 663b8a3563..79db5ef2de 100644 --- a/crates/registry-breg/tests/postgres_native_retention.rs +++ b/crates/registry-breg/tests/postgres_native_retention.rs @@ -80,7 +80,7 @@ fn registry_source(automatic: bool) -> Value { "actions":[{"action":"correct-name","operations":["start"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}], "proposals":[{"action":"correct-name","operations":["get","list","edit","submit","revise","rebase","retry","cancel","apply"], - "ownership":"caller","readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", + "ownership":"caller","readableInputs":["target","value"],"readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}}}); source } diff --git a/crates/registry-breg/tests/postgres_proposal.rs b/crates/registry-breg/tests/postgres_proposal.rs index b05edc889a..7d918a8063 100644 --- a/crates/registry-breg/tests/postgres_proposal.rs +++ b/crates/registry-breg/tests/postgres_proposal.rs @@ -7,6 +7,17 @@ mod client_http; #[path = "support/postgres_harness.rs"] #[allow(dead_code)] mod postgres_harness; +#[path = "support/proposal_additions.rs"] +mod proposal_additions; + +#[path = "support/proposal_status.rs"] +mod proposal_status; + +#[path = "support/proposal_required_attachment.rs"] +mod proposal_required_attachment; + +#[path = "support/proposal_final.rs"] +mod proposal_final; use registry_breg::api::{VerifiedClaimValue, VerifiedRequestClaims}; use registry_breg::compiler::{compile_project, compile_project_with_assets, CompileProfile}; @@ -119,7 +130,7 @@ fn registry_source(automatic: bool) -> Value { "actions":[{"action":"correct-name","operations":["start"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}], "proposals":[{"action":"correct-name","operations":["get","list","edit","submit","revise","rebase","retry","cancel","apply"], - "ownership":"caller","readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", + "ownership":"caller","readableInputs":["target","value"],"readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}}}); source } @@ -141,6 +152,8 @@ async fn holder_identity_is_a_draft_value_but_submit_authority_remains_server_ow .remove("mutationPolicy"); source["recordTypes"]["target"]["fields"][1]["id"] = json!("applicant"); source["actions"]["correct-name"]["inputs"][0] = json!({"id":"applicant","type":"string","maximumLength":64,"required":true,"classification":"internal"}); + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] = + json!(["applicant", "value"]); source["actions"]["correct-name"]["commitGuards"] = json!({}); source["actions"]["correct-name"]["plan"] = json!({"type":"fixed","effects":[{"id":"application","operation":"create","target":{"recordType":"target"},"set":{"name":{"fromInput":"value"},"applicant":{"fromInput":"applicant"}}}]}); source["accessProfiles"]["clerk"]["permissions"]["records"] = json!([{"recordType":"target","operations":["get","list"],"readableFields":["name","applicant"],"rowBoundaries":[{"field":"applicant","claim":"sub","operator":"equals"}]}]); @@ -283,8 +296,8 @@ async fn required_inputs_are_completed_at_submit_and_supplied_draft_values_stay_ let mut source = registry_source(false); source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] = json!(["target", "value"]); - let fixture = - client_http::ClientFixture::start(compile(source), claims("author", "zone-a")).await; + proposal_status::require_review(&mut source); + let fixture = proposal_status::pending_review_fixture(compile(source)).await; let client = &fixture.http.client; let metadata = client.registry_contract(Some("clerk")).await.unwrap(); let action = metadata @@ -880,6 +893,7 @@ async fn retain_queue_review( fixture.database.admin.execute("INSERT INTO registry_internal.registry_proposal_review_results (action_id,proposal_id,submission_version,authority,result_id,result,status,completed_at,available_until) VALUES ('correct-name',$1,$2,'local-review',$3,$4,$5,$6,$7)", &[&id,&version,&result.result_id,&serde_json::to_value(&result).unwrap(),&status,&result.completed_at,&result.available_until]).await.unwrap(); } +// Observe relation locks rather than pg_stat_activity SQL text, which PostgreSQL truncates. async fn proposal_state_lock_wait(fixture: &client_http::ClientFixture, minimum: i64) -> bool { tokio::time::timeout(std::time::Duration::from_secs(5), async { loop { @@ -887,10 +901,13 @@ async fn proposal_state_lock_wait(fixture: &client_http::ClientFixture, minimum: .database .admin .query_one( - "SELECT count(*) FROM pg_stat_activity + "SELECT count(*) FROM pg_stat_activity waiter WHERE datname=current_database() AND wait_event_type='Lock' - AND query LIKE '%registry_proposal_state%' - AND (query LIKE '%FOR UPDATE%' OR query LIKE '%FOR SHARE%')", + AND wait_event IN ('transactionid','tuple') + AND EXISTS (SELECT 1 FROM pg_locks held + WHERE held.pid=waiter.pid AND held.granted + AND held.relation='registry_internal.registry_proposal_state'::regclass + AND held.mode='RowShareLock')", &[], ) .await @@ -1493,7 +1510,7 @@ async fn proposal_list_pages_valid_large_inputs_without_losing_later_proposals() .push(json!({"id":"memo","type":"text","required":true, "maximumLength":320_000,"classification":"internal"})); source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] = - json!(["memo"]); + json!(["target", "value", "memo"]); let fixture = client_http::ClientFixture::start(compile(source), claims("author", "zone-a")).await; // JSON encoding makes this legal text input nearly 2 MiB on the wire. @@ -1573,7 +1590,7 @@ async fn proposal_list_pages_valid_large_inputs_without_losing_later_proposals() } #[tokio::test] -async fn manual_apply_unique_conflict_blocks_apply_while_stale_revision_stays_rebasable() { +async fn manual_apply_unique_conflict_and_stale_revision_offer_party_recovery() { let mut source = registry_source(false); source["recordTypes"]["target"]["constraints"] = json!([{"id":"unique-name","type":"unique","fields":["name"]}]); @@ -1699,7 +1716,7 @@ async fn manual_apply_unique_conflict_blocks_apply_while_stale_revision_stays_re assert_eq!( blocked_json["links"]["apply"]["availability"], json!({"available":false,"observedRevision":blocked.revision(), - "reason":"invalid-input","recovery":"correct-input"}) + "reason":"invalid-input","recovery":"revise"}) ); assert!( blocked @@ -1740,6 +1757,10 @@ async fn manual_apply_unique_conflict_blocks_apply_while_stale_revision_stays_re json!({"id":"activation-note","type":"string","maximumLength":32, "required":false,"classification":"internal"}), ); + incompatible["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] + .as_array_mut() + .unwrap() + .push(json!("activation-note")); let mut registry = (*fixture.registry).clone(); let mut identity = fixture.identity.clone(); let mut activated = None; @@ -1849,20 +1870,28 @@ async fn manual_apply_unique_conflict_blocks_apply_while_stale_revision_stays_re ) .unwrap(); let stale_submitted = client.execute_proposal(&stale_submit).await.unwrap().value; - let entity = &fixture.registry.entities()["target"]; - let stale_id = uuid::Uuid::parse_str(&stale_record.data.record_identifier).unwrap(); - fixture - .database - .admin - .execute( - &format!( - "UPDATE registry_data.\"{}\" SET record_revision=record_revision+1 WHERE record_id=$1", - entity.physical_table - ), - &[&stale_id], + let competing = client + .start_proposal(&action, &stale_input, &key("stale-competing-start")) + .await + .unwrap() + .value; + let competing = client + .execute_proposal( + &client + .prepare_proposal( + &competing, + "submit", + json!({}), + &key("stale-competing-submit"), + ) + .unwrap(), ) .await - .unwrap(); + .unwrap() + .value; + client.execute_proposal(&client.prepare_proposal(&competing, "apply", + json!({"submissionVersion":competing.submission_version(),"effectDigest":competing.effect_digest().unwrap()}), + &key("stale-competing-apply")).unwrap()).await.unwrap(); let stale_apply = client .prepare_proposal( &stale_submitted, @@ -1882,8 +1911,12 @@ async fn manual_apply_unique_conflict_blocks_apply_while_stale_revision_stays_re ); let stale_current = client.read_proposal(&stale_submitted).await.unwrap().value; assert!(stale_current.blocked_reason().is_none()); + assert_eq!( + stale_current.status(), + Some(registry_breg_client::BRegProposalStatus::AwaitingParty) + ); assert!( - stale_current + !stale_current .link("apply") .unwrap() .availability() @@ -1898,6 +1931,37 @@ async fn manual_apply_unique_conflict_blocks_apply_while_stale_revision_stays_re .unwrap() .available ); + assert_eq!( + stale_current + .link("rebase") + .unwrap() + .availability() + .unwrap() + .reason, + None + ); + let value = serde_json::to_value(&stale_current).unwrap(); + assert_eq!(value["applicationStatus"]["recovery"], "rebase"); + assert_eq!( + value["links"]["apply"]["availability"]["reason"], + "stale-revision" + ); + let rebased = client.execute_proposal(&client.prepare_proposal(&stale_current,"rebase", + json!({"input":{"target":stale_record.data.record_identifier,"value":"Rebased"}}), + &key("stale-rebase")).unwrap()).await.unwrap().value; + let resubmitted = client + .execute_proposal( + &client + .prepare_proposal(&rebased, "submit", json!({}), &key("stale-resubmit")) + .unwrap(), + ) + .await + .unwrap() + .value; + let applied = client.execute_proposal(&client.prepare_proposal(&resubmitted,"apply", + json!({"submissionVersion":resubmitted.submission_version(),"effectDigest":resubmitted.effect_digest().unwrap()}), + &key("stale-reapply")).unwrap()).await.unwrap().value; + assert_eq!(applied.state(), BRegProposalState::Applied); fixture.finish().await; } @@ -1969,6 +2033,106 @@ async fn proposal_list_pages_by_limit_and_refuses_top_naming_limit() { fixture.finish().await; } +#[tokio::test] +async fn admitted_apply_outside_the_callers_write_boundary_persists_nothing() { + let caller = |zones: &[&str]| { + VerifiedRequestClaims::authenticated_with_actor_kind( + "sub", + "author", + BTreeSet::from(["proposal:manage".into()]), + Some("registry-administration".into()), + BTreeMap::from([( + "jurisdiction".into(), + VerifiedClaimValue::direct_string_set(zones.iter().copied()).unwrap(), + )]), + registry_platform_oidc::ActorKind::Human, + ) + .unwrap() + }; + let mut source = registry_source(false); + for grant in ["records", "actions", "proposals"] { + let permission = &mut source["accessProfiles"]["clerk"]["permissions"][grant][0]; + let boundary = if grant == "records" { + &mut permission["rowBoundaries"][0] + } else { + &mut permission["targets"][0]["rowBoundaries"][0] + }; + boundary["operator"] = json!("in"); + } + source["actions"]["correct-name"]["plan"]["effects"][0]["set"] = + json!({"jurisdiction":{"fromInput":"value"}}); + let fixture = + client_http::ClientFixture::start(compile(source), caller(&["zone-a", "zone-b"])).await; + let client = &fixture.http.client; + let draft = start(&fixture, "zone-b", "boundary-start").await; + let submitted = client + .execute_proposal( + &client + .prepare_proposal(&draft, "submit", json!({}), &key("boundary-submit")) + .unwrap(), + ) + .await + .unwrap() + .value; + let narrow = client_http::ClientHttp::start( + registry_breg::api::router(fixture.service()), + caller(&["zone-a"]), + ) + .await; + let metadata = narrow + .client + .registry_contract(Some("clerk")) + .await + .unwrap() + .value; + let current = narrow + .client + .get_proposal( + &metadata.select_proposal_get("clerk").unwrap(), + submitted.id(), + ) + .await + .unwrap() + .value; + let refusal = narrow.client.execute_proposal(&narrow.client.prepare_proposal(¤t,"apply", + json!({"submissionVersion":current.submission_version(),"effectDigest":current.effect_digest().unwrap()}),&key("boundary-apply")).unwrap()).await.unwrap_err(); + assert_eq!( + refusal.problem_code(), + Some(BRegProblemCode::WriteOutsideBoundary) + ); + // The boundary belongs to the applying caller, not to the Proposal: the + // refusal persists no block and no revision change. + let after = narrow.client.read_proposal(¤t).await.unwrap().value; + assert_eq!( + serde_json::to_value(&after).unwrap(), + serde_json::to_value(¤t).unwrap() + ); + let wide = client.read_proposal(&submitted).await.unwrap().value; + let wide_value = serde_json::to_value(&wide).unwrap(); + assert!(wide_value["applicationStatus"].get("recovery").is_none()); + assert_eq!( + wide_value["links"]["apply"]["availability"]["available"], true, + "{wide_value}" + ); + let applied = client + .execute_proposal( + &client + .prepare_proposal( + &wide, + "apply", + json!({"submissionVersion":wide.submission_version(),"effectDigest":wide.effect_digest().unwrap()}), + &key("boundary-wide-apply"), + ) + .unwrap(), + ) + .await + .unwrap() + .value; + assert_eq!(applied.state(), BRegProposalState::Applied); + drop(narrow); + fixture.finish().await; +} + #[tokio::test] async fn proposal_list_query_refusals_follow_authority_and_audit_concealment() { let fixture = @@ -2371,7 +2535,8 @@ async fn manual_no_review_attachments_cas_concealment_and_exact_receipt() { let client = &fixture.http.client; let draft = start(&fixture, "After", "manual-start").await; assert_eq!(draft.state(), BRegProposalState::Draft); - assert!(serde_json::to_value(&draft).unwrap().get("input").is_none()); + // The clerk grant reads the inputs it may write, so the draft serves them. + assert!(serde_json::to_value(&draft).unwrap().get("input").is_some()); let uploaded = client .upload_proposal_attachment( &draft, @@ -3050,15 +3215,15 @@ async fn cancel_closes_the_queued_automatic_application_job() { fixture.finish().await; } -/// Revise closes the superseded version's queued automatic application job, -/// which the worker could otherwise never claim again. +/// Processing preserves its queued job. A correction recovery permits Revise, +/// which closes the superseded version's blocked job. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn revise_closes_the_superseded_versions_queued_automatic_application_job() { - let fixture = client_http::ClientFixture::start( - compile(registry_source(true)), - claims("author", "zone-a"), - ) - .await; +async fn revise_preserves_queued_work_and_closes_a_superseded_blocked_application_job() { + let mut source = registry_source(true); + source["recordTypes"]["target"]["constraints"] = + json!([{"id":"unique-name","type":"unique","fields":["name"]}]); + let fixture = + client_http::ClientFixture::start(compile(source), claims("author", "zone-a")).await; let client = &fixture.http.client; let draft = start(&fixture, "Revised", "revise-job-start").await; let submit = client @@ -3082,6 +3247,42 @@ async fn revise_closes_the_superseded_versions_queued_automatic_application_job( .collect::>() }; assert_eq!(job_states().await, [(1, "queued".to_owned())]); + assert_eq!( + proposal_status::raw_command(&fixture, &submitted, "revise") + .await + .status(), + 412 + ); + assert_eq!(job_states().await, [(1, "queued".to_owned())]); + let metadata = client.registry_contract(Some("clerk")).await.unwrap(); + let BRegDirectWrite::Create(create) = metadata + .value + .select_direct_write("records.target.create", "clerk") + .unwrap() + else { + panic!("create") + }; + client + .create_record( + &create, + &BRegCreateRequest::new(map(json!({"name":"Revised","jurisdiction":"zone-a"}))) + .unwrap(), + &key("revise-job-conflict"), + BRegRecordFormat::Json, + ) + .await + .unwrap(); + assert!(fixture + .mutations + .run_automatic_proposal_once_for_test() + .await + .unwrap()); + assert_eq!(job_states().await, [(1, "blocked".to_owned())]); + let submitted = client.read_proposal(&submitted).await.unwrap().value; + assert_eq!( + submitted.status(), + Some(registry_breg_client::BRegProposalStatus::AwaitingParty) + ); let revise = client .prepare_proposal(&submitted, "revise", json!({}), &key("revise-job-revise")) .unwrap(); @@ -3183,7 +3384,6 @@ async fn proposal_lifecycle_writer_waits(admin: &tokio_postgres::Client, pid: Op JOIN pg_locks pending ON pending.pid=writer.pid AND NOT pending.granted WHERE writer.datname=current_database() AND ($1::integer IS NULL OR writer.pid=$1) - AND writer.query LIKE '%registry_proposal_state%' AND EXISTS ( SELECT 1 FROM pg_locks reader WHERE reader.pid=ANY(pg_blocking_pids(writer.pid)) @@ -4493,6 +4693,327 @@ async fn review_rejection_is_terminal_and_changes_requested_returns_to_the_party } } +/// A Proposal source whose review authority is the injected local one, with +/// the inputs readable so a response's `input` member is observable. +fn reviewed_source() -> (Value, Value) { + let mut source = registry_source(false); + source["reviewAuthorities"] = + json!({"local-review": {"protocol":"id.registrystack.org/protocols/review/v1"}}); + let policy = + json!({"id":"name-correction","version":"1","digest":format!("sha256:{}","b".repeat(64))}); + source["actions"]["correct-name"]["execution"]["proposal"]["review"] = json!({"type":"required","authority":"local-review","source":"proposal-test","policy":policy}); + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] = + json!(["target", "value"]); + (source, policy) +} + +/// Records the review authority's decision on the one submitted Proposal, as +/// the reconciler does when the authority answers. +async fn inject_review_decision( + fixture: &client_http::ClientFixture, + review: &LocalReview, + policy: Value, + outcome: &str, +) { + let row=fixture.database.admin.query_one("SELECT create_request,expected_submission_digest FROM registry_internal.registry_proposal_review_submissions",&[]).await.unwrap(); + let create: registry_review_client::ReviewCreateRequest = + serde_json::from_value(row.get(0)).unwrap(); + let accepted = registry_review_client::ReviewRequestAccepted { + request_id: uuid::Uuid::new_v4(), + subject: create.subject, + policy: serde_json::from_value(policy).unwrap(), + submission_digest: serde_json::from_value(json!(row.get::<_, String>(1))).unwrap(), + }; + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_submissions SET state='accepted',accepted_binding=$1", + &[&serde_json::to_value(&accepted).unwrap()]).await.unwrap(); + let mut result = review.result(&accepted); + result.status = serde_json::from_value(json!(outcome)).unwrap(); + result.outcome = Some(outcome.to_owned()); + result.public_reason = Some("Public reason canary".to_owned()); + let (mut migration, task) = fixture.database.connect_migration().await; + let tx = migration.transaction().await.unwrap(); + registry_breg::review_store::reconcile_result( + &tx, + "local-review", + &accepted, + &result, + &fixture.mutations, + ) + .await + .unwrap(); + tx.commit().await.unwrap(); + drop(migration); + task.abort(); +} + +async fn post_command_link(base_url: &str, link: &Value, key_name: &str) -> Value { + let response = reqwest::Client::new() + .post(format!( + "{}{}", + base_url.trim_end_matches('/'), + link["path"].as_str().unwrap() + )) + .query(&[("accessProfile", link["accessProfile"].as_str().unwrap())]) + .header("content-type", "application/json") + .header("if-match", link["ifMatch"].as_str().unwrap()) + .header("idempotency-key", key_name) + .body("{}") + .send() + .await + .unwrap(); + let status = response.status(); + let body: Value = response.json().await.unwrap(); + assert_eq!(status, reqwest::StatusCode::OK, "{key_name}: {body}"); + body +} + +/// A lifecycle command answers with the document a Get by the same caller +/// would serve right after it: the decision with its public reason, and the +/// readable inputs. Serving the public reason is audited with the same fixed +/// marker a Get records, and a replay returns the stored body. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn command_response_carries_the_decision_a_get_would_serve() { + let (source, policy) = reviewed_source(); + let review = std::sync::Arc::new(LocalReview { + calls: 0.into(), + mode: 0.into(), + result_id: uuid::Uuid::new_v4(), + }); + let injected = review.clone(); + let fixture = client_http::ClientFixture::start_with_mutations( + compile(source), + claims("author", "zone-a"), + move |mutations| { + mutations.with_proposal_review_substitute_for_test(local_review_binding(), injected) + }, + ) + .await; + let client = &fixture.http.client; + let draft = start(&fixture, "Reviewed", "decision-command-start").await; + let submit = client + .prepare_proposal(&draft, "submit", json!({}), &key("decision-command-submit")) + .unwrap(); + let submitted = client.execute_proposal(&submit).await.unwrap().value; + inject_review_decision(&fixture, &review, policy, "changes-requested").await; + + let current = + serde_json::to_value(client.read_proposal(&submitted).await.unwrap().value).unwrap(); + assert_eq!(current["decision"]["publicReason"], "Public reason canary"); + let before = fixture.audit_capture.entries().len(); + let cancelled = post_command_link( + &fixture.http.base_url, + ¤t["links"]["cancel"], + "decision-command-cancel", + ) + .await; + assert_eq!(cancelled["state"], "cancelled", "{cancelled}"); + assert_eq!(cancelled["decision"], current["decision"], "{cancelled}"); + assert_eq!(cancelled["input"], current["input"], "{cancelled}"); + let entries = fixture.audit_capture.entries(); + assert!( + entries[before..].iter().any(|entry| { + entry["record"]["phase"] == "terminal" + && entry["record"]["operationId"] == "proposals.correct-name.cancel" + && entry["record"]["fieldSetReference"] == "proposal-review-public-reason" + }), + "{:?}", + &entries[before..] + ); + assert!(!entries[before..] + .iter() + .any(|entry| entry.to_string().contains("Public reason canary"))); + // A replay returns the stored body, decision included, and audits the + // public reason it serves again with the same marker. + let before_replay = fixture.audit_capture.entries().len(); + let replay = post_command_link( + &fixture.http.base_url, + ¤t["links"]["cancel"], + "decision-command-cancel", + ) + .await; + assert_eq!(replay, cancelled); + assert_replay_marks_the_public_reason(&fixture, before_replay, "cancel"); + fixture.finish().await; +} + +/// The replay's terminal audit entry carries the public-reason marker and +/// never the reason's text. +fn assert_replay_marks_the_public_reason( + fixture: &client_http::ClientFixture, + before: usize, + operation: &str, +) { + let entries = fixture.audit_capture.entries(); + assert!( + entries[before..].iter().any(|entry| { + entry["record"]["phase"] == "terminal" + && entry["record"]["outcome"] == "replayed" + && entry["record"]["operationId"] == format!("proposals.correct-name.{operation}") + && entry["record"]["fieldSetReference"] == "proposal-review-public-reason" + }), + "{:?}", + &entries[before..] + ); + assert!(!entries[before..] + .iter() + .any(|entry| entry.to_string().contains("Public reason canary"))); +} + +/// An Apply replay is answered from its receipt before any review evidence is +/// fetched, and audits the approved decision's public reason as the first +/// response did. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn apply_replay_marks_the_public_reason_it_serves() { + let (source, policy) = reviewed_source(); + let review = std::sync::Arc::new(LocalReview { + calls: 0.into(), + mode: 0.into(), + result_id: uuid::Uuid::new_v4(), + }); + let injected = review.clone(); + let fixture = client_http::ClientFixture::start_with_mutations( + compile(source), + claims("author", "zone-a"), + move |mutations| { + mutations.with_proposal_review_substitute_for_test(local_review_binding(), injected) + }, + ) + .await; + let client = &fixture.http.client; + let draft = start(&fixture, "Reviewed", "decision-apply-start").await; + let submit = client + .prepare_proposal(&draft, "submit", json!({}), &key("decision-apply-submit")) + .unwrap(); + let submitted = client.execute_proposal(&submit).await.unwrap().value; + inject_review_decision(&fixture, &review, policy, "approved").await; + let current = client.read_proposal(&submitted).await.unwrap().value; + let apply = client + .prepare_proposal( + ¤t, + "apply", + json!({"submissionVersion":1,"effectDigest":current.effect_digest().unwrap()}), + &key("decision-apply"), + ) + .unwrap(); + let applied = + serde_json::to_value(client.execute_proposal(&apply).await.unwrap().value).unwrap(); + assert_eq!(applied["state"], "applied", "{applied}"); + assert_eq!(applied["decision"]["publicReason"], "Public reason canary"); + let before_replay = fixture.audit_capture.entries().len(); + let replay = client.execute_proposal(&apply).await.unwrap(); + assert_eq!(serde_json::to_value(replay.value).unwrap(), applied); + assert_replay_marks_the_public_reason(&fixture, before_replay, "apply"); + fixture.finish().await; +} + +/// A caller whose profile may run a command but not Get on the Proposal gets +/// the command response without `decision` and `input`: command authority is +/// not read authority. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn command_response_withholds_the_decision_from_a_profile_without_get() { + let (mut source, policy) = reviewed_source(); + let mut filer = source["accessProfiles"]["clerk"].clone(); + filer["default"] = json!(false); + filer["permissions"]["proposals"][0]["operations"] = json!(["submit", "cancel"]); + // Input and attachment disclosure require Get, so the profile has none. + filer["permissions"]["proposals"][0]["readableInputs"] = json!([]); + filer["permissions"]["proposals"][0]["readableAttachments"] = json!([]); + filer["permissions"]["proposals"][0]["writableAttachments"] = json!([]); + source["accessProfiles"]["filer"] = filer; + let review = std::sync::Arc::new(LocalReview { + calls: 0.into(), + mode: 0.into(), + result_id: uuid::Uuid::new_v4(), + }); + let injected = review.clone(); + let fixture = client_http::ClientFixture::start_with_mutations( + compile(source), + claims("author", "zone-a"), + move |mutations| { + mutations.with_proposal_review_substitute_for_test(local_review_binding(), injected) + }, + ) + .await; + let client = &fixture.http.client; + let metadata = client.registry_contract(Some("filer")).await.unwrap(); + let BRegDirectWrite::Create(create) = metadata + .value + .select_direct_write("records.target.create", "filer") + .unwrap() + else { + panic!("create"); + }; + let record = client + .create_record( + &create, + &BRegCreateRequest::new(map(json!({"name":"Before","jurisdiction":"zone-a"}))).unwrap(), + &key("filer-record"), + BRegRecordFormat::Json, + ) + .await + .unwrap(); + let action = metadata + .value + .select_action("correct-name", "filer") + .unwrap(); + let invocation = BRegActionInvocationRequest::new( + &action, + map(json!({"target":record.value.data.record_identifier,"value":"Reviewed"})), + None, + ) + .unwrap(); + let draft = client + .start_proposal(&action, &invocation, &key("filer-start")) + .await + .unwrap() + .value; + let submit = client + .prepare_proposal(&draft, "submit", json!({}), &key("filer-submit")) + .unwrap(); + let submitted = + serde_json::to_value(client.execute_proposal(&submit).await.unwrap().value).unwrap(); + assert!(submitted.get("input").is_none(), "{submitted}"); + inject_review_decision(&fixture, &review, policy, "changes-requested").await; + + // The decision exists: the clerk, who holds Get, reads it. + let clerk_read = reqwest::get(format!( + "{}/v1/proposals/{}?accessProfile=clerk", + fixture.http.base_url, + submitted["id"].as_str().unwrap() + )) + .await + .unwrap(); + let clerk_view: Value = clerk_read.json().await.unwrap(); + assert_eq!( + clerk_view["decision"]["publicReason"], + "Public reason canary" + ); + assert!(clerk_view.get("input").is_some(), "{clerk_view}"); + + let before = fixture.audit_capture.entries().len(); + let cancelled = post_command_link( + &fixture.http.base_url, + &submitted["links"]["cancel"], + "filer-cancel", + ) + .await; + assert_eq!(cancelled["state"], "cancelled", "{cancelled}"); + // No command leaves a Proposal `submitted` with a refused hand-off, so + // `handoffRefusal` cannot appear on a command response at all. + for member in ["decision", "input"] { + assert!(cancelled.get(member).is_none(), "{member}: {cancelled}"); + } + assert!(!cancelled.to_string().contains("Public reason canary")); + let entries = fixture.audit_capture.entries(); + assert!( + !entries[before..] + .iter() + .any(|entry| entry["record"]["fieldSetReference"] == "proposal-review-public-reason"), + "no public reason was served, so none is marked" + ); + fixture.finish().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn submission_read_reports_each_version_separately_and_is_gone_after_its_windows() { let mut source = registry_source(false); @@ -4996,7 +5517,14 @@ async fn proposal_inputs_require_an_explicit_selected_profile_allowlist() { reader["permissions"]["proposals"][0]["operations"] = json!(["get", "list"]); reader["permissions"]["proposals"][0]["writableAttachments"] = json!([]); reader["permissions"]["proposals"][0]["readableInputs"] = json!(["target"]); + // A Get grant that cannot write may name no inputs, and then reads none. + let mut blind_reader = reader.clone(); + blind_reader["permissions"]["proposals"][0] + .as_object_mut() + .unwrap() + .remove("readableInputs"); source["accessProfiles"]["input-reader"] = reader; + source["accessProfiles"]["blind-reader"] = blind_reader; let fixture = client_http::ClientFixture::start(compile(source), claims("author", "zone-a")).await; let client = &fixture.http.client; @@ -5035,7 +5563,8 @@ async fn proposal_inputs_require_an_explicit_selected_profile_allowlist() { .await .unwrap() .value; - assert!(serde_json::to_value(&draft).unwrap().get("input").is_none()); + // The clerk grant reads the inputs it may write, so the draft serves them. + assert!(serde_json::to_value(&draft).unwrap().get("input").is_some()); let metadata = client .registry_contract(Some("input-reader")) .await @@ -5051,6 +5580,18 @@ async fn proposal_inputs_require_an_explicit_selected_profile_allowlist() { assert!(!serde_json::to_string(&value) .unwrap() .contains("input-secret-canary")); + let blind = reqwest::get(format!( + "{}/v1/proposals/{}?accessProfile=blind-reader", + fixture.http.base_url, + draft.id() + )) + .await + .unwrap(); + assert_eq!(blind.status(), reqwest::StatusCode::OK); + let blind: Value = blind.json().await.unwrap(); + assert_eq!(blind["state"], "draft", "{blind}"); + assert!(blind.get("input").is_none(), "{blind}"); + assert!(!blind.to_string().contains("input-secret-canary")); fixture.finish().await; } @@ -5398,16 +5939,17 @@ async fn prepared_lifecycle_recovery_uses_current_authority_and_the_original_exa let mut source = registry_source(false); source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] = json!(["target", "value"]); - let fixture = - client_http::ClientFixture::start(compile(source), claims("author", "zone-a")).await; + proposal_status::require_review(&mut source); + let fixture = proposal_status::pending_review_fixture(compile(source)).await; let client = &fixture.http.client; let draft = start(&fixture, "Recover lifecycle", "recover-start").await; - assert!( - draft.input().is_none(), - "mutation receipts retain no optional input disclosure" - ); let current = client.read_proposal(&draft).await.unwrap().value; let original_input = current.input().unwrap().clone(); + assert_eq!( + draft.input(), + Some(&original_input), + "a command response discloses the input a read by the same caller does" + ); let submit = client .prepare_proposal(¤t, "submit", json!({}), &key("recover-submit")) .unwrap(); @@ -5464,6 +6006,10 @@ async fn prepared_lifecycle_recovery_uses_current_authority_and_the_original_exa async fn reference_only_targets_are_locked_and_readmitted_at_submit_and_apply() { let mut source = registry_source(false); source["actions"]["correct-name"]["inputs"].as_array_mut().unwrap().push(json!({"id":"linked","type":"reference","target":"target","required":true,"classification":"internal"})); + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] + .as_array_mut() + .unwrap() + .push(json!("linked")); let mut fixture = client_http::ClientFixture::start(compile(source), claims("author", "zone-a")).await; let client = &fixture.http.client; @@ -6193,6 +6739,106 @@ async fn narrowed_attachment_disclosure_refuses_the_old_exact_receipt_without_re fixture.finish().await; } +/// A command receipt holds the inputs its caller could read. Once a later +/// package narrows that grant's `readableInputs`, the old key conflicts +/// instead of replaying an input a Get now withholds. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn narrowed_input_disclosure_refuses_the_old_exact_receipt() { + let mut source = registry_source(false); + let mut canceller = source["accessProfiles"]["clerk"].clone(); + canceller["default"] = json!(false); + canceller["permissions"]["actions"] = json!([]); + canceller["permissions"]["records"] = json!([]); + canceller["permissions"]["proposals"][0]["operations"] = json!(["get", "list", "cancel"]); + canceller["permissions"]["proposals"][0]["writableAttachments"] = json!([]); + source["accessProfiles"]["canceller"] = canceller; + let fixture = + client_http::ClientFixture::start(compile(source.clone()), claims("author", "zone-a")) + .await; + let draft = start(&fixture, "Narrowed input canary", "narrow-input-start").await; + let read = reqwest::get(format!( + "{}/v1/proposals/{}?accessProfile=canceller", + fixture.http.base_url, + draft.id() + )) + .await + .unwrap(); + assert_eq!(read.status(), reqwest::StatusCode::OK); + let view: Value = read.json().await.unwrap(); + let link = view["links"]["cancel"].clone(); + let cancelled = post_command_link(&fixture.http.base_url, &link, "narrow-input-cancel").await; + assert_eq!(cancelled["input"]["value"], "Narrowed input canary"); + + let mut next = source; + next["accessProfiles"]["canceller"]["permissions"]["proposals"][0]["readableInputs"] = + json!(["target"]); + assert_eq!( + fixture.registry.actions().actions[0].definition_revision, + compile(next.clone()).actions().actions[0].definition_revision + ); + let (registry, identity) = proposal_activation::activate_successor(&fixture, &next).await; + let current = successor_client(&fixture, registry, identity).await; + let response = reqwest::Client::new() + .post(format!( + "{}{}", + current.base_url.trim_end_matches('/'), + link["path"].as_str().unwrap() + )) + .query(&[("accessProfile", "canceller")]) + .header("content-type", "application/json") + .header("if-match", link["ifMatch"].as_str().unwrap()) + .header("idempotency-key", "narrow-input-cancel") + .body("{}") + .send() + .await + .unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::CONFLICT); + assert!(!response + .text() + .await + .unwrap() + .contains("Narrowed input canary")); + drop(current); + fixture.finish().await; +} + +/// An attachment upload or removal is an Edit, and its response carries the +/// readable inputs as a Get would. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn attachment_upload_and_removal_responses_carry_the_readable_inputs() { + let fixture = + client_http::ClientFixture::start(registry(false), claims("author", "zone-a")).await; + let client = &fixture.http.client; + let draft = start( + &fixture, + "Attachment input canary", + "attachment-input-start", + ) + .await; + let expected = serde_json::to_value(&draft).unwrap()["input"].clone(); + assert_eq!(expected["value"], "Attachment input canary"); + let uploaded = client + .upload_proposal_attachment( + &draft, + "support", + "text/plain", + b"synthetic-support", + &key("attachment-input-upload"), + ) + .await + .unwrap() + .value; + assert_eq!(serde_json::to_value(&uploaded).unwrap()["input"], expected); + let removed = client + .delete_proposal_attachment(&uploaded, "support", &key("attachment-input-remove")) + .await + .unwrap() + .value; + assert!(removed.revision() > uploaded.revision()); + assert_eq!(serde_json::to_value(&removed).unwrap()["input"], expected); + fixture.finish().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[cfg(feature = "tooling")] async fn review_context_refuses_active_action_mapping_for_a_retained_submission() { @@ -6340,6 +6986,10 @@ async fn review_context_projects_an_omitted_optional_input_as_null() { .push(json!("get-review-context")); source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableContextFields"] = json!(["proposedName", "note", "relatedName"]); + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] + .as_array_mut() + .unwrap() + .extend([json!("note"), json!("related")]); let fixture = client_http::ClientFixture::start(compile(source), claims("author", "zone-a")).await; // The shared helper supplies only the required inputs. @@ -6718,16 +7368,18 @@ async fn retained_attachment_download_survives_tighter_current_upload_policy() { .await .unwrap() .value; - for (content_type, upload, expected) in [ + for (content_type, upload, expected, code) in [ ( "application/octet-stream", bytes.as_slice(), - reqwest::StatusCode::BAD_REQUEST, + reqwest::StatusCode::PAYLOAD_TOO_LARGE, + "attachment.too-large", ), ( "text/plain", b"ok".as_slice(), reqwest::StatusCode::UNSUPPORTED_MEDIA_TYPE, + "attachment.content-type", ), ] { assert!(current @@ -6761,6 +7413,7 @@ async fn retained_attachment_download_survives_tighter_current_upload_policy() { .await .unwrap(); assert_eq!(response.status(), expected); + assert_eq!(response.json::().await.unwrap()["code"], code); } current .client @@ -7261,20 +7914,20 @@ async fn compatible_legacy_review_closure_survives_status_apply_successors_and_r ); assert_eq!( availability.reason, - Some(registry_breg_client::BRegAvailabilityReason::PackageChanged) + Some(registry_breg_client::BRegAvailabilityReason::ApplicationPending) ); assert_eq!( availability.recovery, - Some(registry_breg_client::BRegRecoveryHint::Rebase) + Some(registry_breg_client::BRegRecoveryHint::Refresh) ); assert!( - current + !current .link("rebase") .unwrap() .availability() .unwrap() .available, - "explicit Rebase remains available with current Start authority" + "approved work preserves its original reviewed submission despite current Start authority" ); let response = reqwest::Client::new() .post(format!( @@ -8216,6 +8869,7 @@ fn writable_inputs_source() -> Value { fn nullable_writable_inputs_registry() -> registry_breg::CompiledRegistry { let mut source = writable_inputs_source(); + proposal_status::require_review(&mut source); source["functions"] = json!({"nullable-note-plan": {"runtime":"rhai", "source":"plans/nullable-note.rhai", "entrypoint":"plan", "abi":"registry.action-plan/v1" }}); @@ -8288,11 +8942,8 @@ async fn assert_input_write_refused( #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn writable_inputs_treat_explicit_null_as_a_write() { - let fixture = client_http::ClientFixture::start( - nullable_writable_inputs_registry(), - claims("author", "zone-a"), - ) - .await; + let fixture = + proposal_status::pending_review_fixture(nullable_writable_inputs_registry()).await; let client = &fixture.http.client; let metadata = client.registry_contract(Some("clerk")).await.unwrap(); let BRegDirectWrite::Create(create) = metadata @@ -8514,11 +9165,9 @@ async fn writable_inputs_treat_explicit_null_as_a_write() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn writable_inputs_bound_start_edit_revise_and_rebase_to_the_named_inputs() { - let fixture = client_http::ClientFixture::start( - compile(writable_inputs_source()), - claims("author", "zone-a"), - ) - .await; + let mut source = writable_inputs_source(); + proposal_status::require_review(&mut source); + let fixture = proposal_status::pending_review_fixture(compile(source)).await; let client = &fixture.http.client; let metadata = client.registry_contract(Some("clerk")).await.unwrap(); let BRegDirectWrite::Create(create) = metadata diff --git a/crates/registry-breg/tests/postgres_proposal_generated_identifiers.rs b/crates/registry-breg/tests/postgres_proposal_generated_identifiers.rs index 96947d597d..330129f79a 100644 --- a/crates/registry-breg/tests/postgres_proposal_generated_identifiers.rs +++ b/crates/registry-breg/tests/postgres_proposal_generated_identifiers.rs @@ -134,11 +134,13 @@ fn registry() -> registry_breg::CompiledRegistry { "proposals":[ {"action":"register-target", "operations":["get","submit","revise","retry","apply"],"ownership":"caller", + "readableInputs":["name","jurisdiction"], "targets":[{"recordType":"target","rowBoundaries":[{ "field":"jurisdiction","claim":"jurisdiction","operator":"equals" }]}]}, {"action":"register-target-with-document", "operations":["get","edit","submit"],"ownership":"caller", + "readableInputs":["name","jurisdiction"], "readableAttachments":["support"],"writableAttachments":["support"], "targets":[{"recordType":"target","rowBoundaries":[{ "field":"jurisdiction","claim":"jurisdiction","operator":"equals" diff --git a/crates/registry-breg/tests/postgres_proposal_guard_failure.rs b/crates/registry-breg/tests/postgres_proposal_guard_failure.rs index 0583af84d8..d4b5a6161c 100644 --- a/crates/registry-breg/tests/postgres_proposal_guard_failure.rs +++ b/crates/registry-breg/tests/postgres_proposal_guard_failure.rs @@ -105,7 +105,7 @@ fn guard_project(readable: &[&str], offset: Option<(&str, i32)>) -> Value { "actions":[{"action":"correct-name","operations":["start"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}], "proposals":[{"action":"correct-name","operations":["get","list","edit","submit","revise","rebase","retry","cancel","apply"], - "ownership":"caller","targets":[{"recordType":"target", + "ownership":"caller","readableInputs":["target","value","minimum"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}}}); if let Some((member, offset)) = offset { source["project"]["timezone"] = json!("UTC"); @@ -294,6 +294,54 @@ async fn apply_names_a_failed_field_guard_and_keeps_stale_revisions_generic() { Some(BRegProblemCode::ActionGuardFailed) ); assert_eq!(refusal.guard_reason(), Some("target-not-open")); + let blocked = fixture + .http + .client + .read_proposal(&submitted) + .await + .unwrap() + .value; + assert_eq!( + blocked.status(), + Some(registry_breg_client::BRegProposalStatus::AwaitingParty) + ); + assert_eq!( + serde_json::to_value(&blocked).unwrap()["applicationStatus"]["recovery"], + "rebase" + ); + assert!( + blocked + .link("rebase") + .unwrap() + .availability() + .unwrap() + .available + ); + + let (_, replacement_id) = draft(&fixture, "open", 10, "guard-replacement").await; + let client = &fixture.http.client; + let rebased = client + .execute_proposal( + &client + .prepare_proposal( + &blocked, + "rebase", + json!({"input":{"target":replacement_id,"value":"After","minimum":5}}), + &key("guard-rebase"), + ) + .unwrap(), + ) + .await + .unwrap() + .value; + let resubmitted = submit(&fixture, &rebased, "guard-resubmit").await.unwrap(); + let applied = apply(&fixture, &resubmitted, "guard-reapply") + .await + .unwrap(); + assert_eq!( + applied.state(), + registry_breg_client::BRegProposalState::Applied + ); // A revision mismatch is concurrency, never a business-state refusal, even // while the guard would also fail. diff --git a/crates/registry-breg/tests/postgres_proposal_recovery_permissions.rs b/crates/registry-breg/tests/postgres_proposal_recovery_permissions.rs index 9eb6687e05..8dad5a38c3 100644 --- a/crates/registry-breg/tests/postgres_proposal_recovery_permissions.rs +++ b/crates/registry-breg/tests/postgres_proposal_recovery_permissions.rs @@ -109,7 +109,7 @@ fn registry_source() -> Value { "proposals":[{ "action":"correct-name", "operations":["get","list","edit","submit","revise","rebase","retry","cancel","apply"], - "ownership":"caller", + "ownership":"caller","readableInputs":["target","value"], "targets":[{ "recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] @@ -127,6 +127,16 @@ fn compile(source: &Value) -> registry_breg::CompiledRegistry { } fn set_operations(profile: &mut Value, operations: Value) { + // Reading inputs needs Get, so a grant without it reads none. + if !operations + .as_array() + .is_some_and(|operations| operations.contains(&json!("get"))) + { + profile["permissions"]["proposals"][0] + .as_object_mut() + .unwrap() + .remove("readableInputs"); + } profile["permissions"]["proposals"][0]["operations"] = operations; } diff --git a/crates/registry-breg/tests/postgres_proposal_review_delivery.rs b/crates/registry-breg/tests/postgres_proposal_review_delivery.rs index 4ad6973e0b..a8103dda0f 100644 --- a/crates/registry-breg/tests/postgres_proposal_review_delivery.rs +++ b/crates/registry-breg/tests/postgres_proposal_review_delivery.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 //! Native Proposal review delivery uses durable, authority-bound PostgreSQL work. #![cfg(feature = "postgres-test")] +#[path = "support/proposal_review_asks.rs"] +mod asks; #[path = "support/client_http.rs"] #[allow(dead_code)] mod client_http; @@ -136,6 +138,7 @@ enum ResultReply { } struct AuthorityState { + asks: Mutex, gates: [Gate; 2], gated: bool, first_succeeds: bool, @@ -167,6 +170,7 @@ impl Authority { result_replies: [ResultReply; 2], ) -> Self { let state = Arc::new(AuthorityState { + asks: Mutex::new(Default::default()), gates: [Gate::default(), Gate::default()], gated, first_succeeds, @@ -182,6 +186,12 @@ impl Authority { .route("/v1/review-requests/{id}/cancel", post(cancel_review)) .route("/v1/review-requests/{id}/result", get(lookup_result)) .route("/v1/review-results", get(empty_feed)) + .route("/v1/review-asks", get(asks::feed)) + .route( + "/v1/review-requests/{request}/asks/{ask}/answer", + post(asks::answer_remote), + ) + .route("/v1/review-requests/{request}/asks/{ask}", get(asks::read)) .with_state(state.clone()); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let endpoint = format!("http://{}/", listener.local_addr().unwrap()); @@ -2519,6 +2529,8 @@ async fn a_handoff_refusal_is_named_only_while_the_refused_submission_is_current let mut source = registry_source(json!(policy())); source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["operations"] = json!(["get", "list", "submit", "revise", "cancel"]); + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] = + json!(["target", "value"]); let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); let registry = compile_project(&project, &[], CompileProfile::Authoring).unwrap(); let bindings = authority.registry.clone(); diff --git a/crates/registry-breg/tests/postgres_proposal_s3.rs b/crates/registry-breg/tests/postgres_proposal_s3.rs index e6513a8424..5232bf0421 100644 --- a/crates/registry-breg/tests/postgres_proposal_s3.rs +++ b/crates/registry-breg/tests/postgres_proposal_s3.rs @@ -82,7 +82,7 @@ fn registry_source(automatic: bool) -> Value { "actions":[{"action":"correct-name","operations":["start"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}], "proposals":[{"action":"correct-name","operations":["get","list","edit","submit","revise","rebase","retry","cancel","apply"], - "ownership":"caller","readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", + "ownership":"caller","readableInputs":["target","value"],"readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}}}); source } @@ -869,6 +869,10 @@ async fn review_document_binding_refusals_precede_s3_and_revise_never_follows_su .unwrap() .remove("writableFields"); reviewer["permissions"]["proposals"][0]["operations"] = json!(["get-review-context"]); + reviewer["permissions"]["proposals"][0] + .as_object_mut() + .unwrap() + .remove("readableInputs"); reviewer["permissions"]["proposals"][0]["readableContextFields"] = json!(["document", "changes"]); reviewer["permissions"]["proposals"][0] diff --git a/crates/registry-breg/tests/postgres_proposal_security.rs b/crates/registry-breg/tests/postgres_proposal_security.rs index efc02483ae..1247624801 100644 --- a/crates/registry-breg/tests/postgres_proposal_security.rs +++ b/crates/registry-breg/tests/postgres_proposal_security.rs @@ -69,13 +69,13 @@ fn source(membership: bool) -> Value { {"recordType":"target","operations":["create","get"],"readableFields":["name","jurisdiction","organization"], "writableFields":["name","jurisdiction","organization"],"rowBoundaries":boundary}], "actions":[{"action":"correct-name","operations":["start"],"targets":targets}], - "proposals":[{"action":"correct-name","operations":["get","edit","submit","cancel"],"ownership":"caller","targets":targets}]}}, + "proposals":[{"action":"correct-name","operations":["get","edit","submit","cancel"],"ownership":"caller","readableInputs":["target","value"],"targets":targets}]}}, "task-reviewer": {"principalClaim":"registry_principal","actorKind":"agent","requesterClients":["agent-client"], "requiredScopes":["proposal:manage"],"requiredPurposes":["registry-administration"], "taskGrant":{"sourceIssuer":"https://casework.example"},"permissions":{"records":[reader], "actions":[{"action":"correct-name","operations":["start"],"targets":targets}], "proposals":[{"action":"correct-name","operations":["get","edit","submit","get-review-context"], - "ownership":"caller","readableContextFields":["currentName","proposedName"],"targets":targets}]}}}}); + "ownership":"caller","readableInputs":["target","value"],"readableContextFields":["currentName","proposedName"],"targets":targets}]}}}}); source } @@ -536,6 +536,10 @@ async fn review_context_requires_record_grant_and_current_membership() { json!(["support"]); source["accessProfiles"]["task-reviewer"]["permissions"]["proposals"][0]["operations"] = json!(["get-review-context"]); + source["accessProfiles"]["task-reviewer"]["permissions"]["proposals"][0] + .as_object_mut() + .unwrap() + .remove("readableInputs"); source["accessProfiles"]["task-reviewer"]["permissions"]["proposals"][0] ["readableContextFields"] .as_array_mut() @@ -944,6 +948,10 @@ async fn saved_review_document_requires_current_subject_consent() { json!([{"record":"consent-decision","on":"id"}]); project["accessProfiles"]["task-reviewer"]["permissions"]["proposals"][0]["operations"] = json!(["get-review-context"]); + project["accessProfiles"]["task-reviewer"]["permissions"]["proposals"][0] + .as_object_mut() + .unwrap() + .remove("readableInputs"); project["accessProfiles"]["task-reviewer"]["permissions"]["proposals"][0] ["readableContextFields"] = json!(["currentName", "proposedName", "document"]); let status = Arc::new(Status { @@ -1092,6 +1100,10 @@ async fn explicit_service_assessment_preserves_scope_actor_target_and_record_dis .unwrap() .remove("actions"); service["permissions"]["proposals"][0]["operations"] = json!(["get-review-context"]); + service["permissions"]["proposals"][0] + .as_object_mut() + .unwrap() + .remove("readableInputs"); service["permissions"]["proposals"][0] .as_object_mut() .unwrap() diff --git a/crates/registry-breg/tests/postgres_proposal_task_authority.rs b/crates/registry-breg/tests/postgres_proposal_task_authority.rs index 514edd685e..76d70ea3b6 100644 --- a/crates/registry-breg/tests/postgres_proposal_task_authority.rs +++ b/crates/registry-breg/tests/postgres_proposal_task_authority.rs @@ -120,6 +120,7 @@ fn registry(automatic: bool, reviewed: bool) -> registry_breg::CompiledRegistry "action":"correct-name", "operations":["get","edit","submit","retry","cancel","apply"], "ownership":"caller", + "readableInputs":["target","value"], "targets":[{"recordType":"target","rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}] }] } @@ -141,6 +142,7 @@ fn registry(automatic: bool, reviewed: bool) -> registry_breg::CompiledRegistry "action":"correct-name", "operations":["get","edit","submit","cancel"], "ownership":"caller", + "readableInputs":["target","value"], "targets":[{"recordType":"target","rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}] }] } @@ -992,3 +994,116 @@ async fn completed_apply_receipt_and_owner_cancel_do_not_require_retained_status assert_eq!(status.calls.load(Ordering::SeqCst), calls_before_exceptions); fixture.finish().await; } + +/// A task grant that scopes `cancel` but not `get` on the Proposal runs the +/// command, and the response withholds what only Get may read: the decision +/// and the inputs. The same profile under a grant that holds `get` reads both. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn cancel_only_task_grant_gets_no_decision_or_input_on_its_response() { + let status = status(); + let checker = status.clone(); + let review = Arc::new(ApprovedReview { + calls: AtomicUsize::new(0), + result_id: uuid::Uuid::new_v4(), + }); + let review_source = review.clone(); + let fixture = client_http::ClientFixture::start_with_mutations( + registry(false, true), + clerk(), + move |service| { + service + .with_task_status(checker) + .with_proposal_review_substitute_for_test(review_binding(), review_source) + }, + ) + .await; + let target = create_target(&fixture, "cancel-only").await; + let idp = MockIdp::start().await; + let auth = authenticator(&fixture.registry, &idp).await; + let (proposal_id, _, _) = submit_with_task(&fixture, &auth, &idp, &target, "cancel-only").await; + let accepted = accept_review(&fixture, &proposal_id).await; + let now = chrono::Utc::now(); + let result = registry_review_client::ReviewResult { + result_id: uuid::Uuid::new_v4(), + request_id: accepted.request_id, + subject: accepted.subject.clone(), + policy: accepted.policy.clone(), + submission_digest: accepted.submission_digest.clone(), + status: registry_review_client::ReviewResultStatus::ChangesRequested, + outcome: Some("changes-requested".to_owned()), + public_reason: Some("Task reason canary".to_owned()), + result: None, + completed_at: now - chrono::Duration::seconds(1), + available_until: now + chrono::Duration::minutes(5), + }; + let (mut migration, task) = fixture.database.connect_migration().await; + let tx = migration.transaction().await.unwrap(); + registry_breg::review_store::reconcile_result( + &tx, + "local-review", + &accepted, + &result, + &fixture.mutations, + ) + .await + .unwrap(); + tx.commit().await.unwrap(); + drop(migration); + task.abort(); + + let reader = fixture + .client_for( + auth.authenticate(&idp.mint_token(token( + 2, + json!([{ + "collection":format!("proposal:{proposal_id}"), + "operations":["get","edit","submit","cancel"] + }]), + ))) + .await + .unwrap(), + ) + .await; + let (read_status, read, etag) = send( + &reader, + Method::GET, + &format!("/v1/proposals/{proposal_id}?accessProfile=task-agent"), + Value::Null, + None, + None, + ) + .await; + assert_eq!(read_status, StatusCode::OK, "{read}"); + assert_eq!(read["decision"]["publicReason"], "Task reason canary"); + assert_eq!(read["input"]["value"], "After"); + + let canceller = fixture + .client_for( + auth.authenticate(&idp.mint_token(token( + 3, + json!([{ + "collection":format!("proposal:{proposal_id}"), + "operations":["cancel"] + }]), + ))) + .await + .unwrap(), + ) + .await; + let (cancel_status, cancelled, _) = send( + &canceller, + Method::POST, + &format!("/v1/proposals/{proposal_id}/cancel?accessProfile=task-agent"), + json!({}), + Some("cancel-only-cancel"), + etag.as_deref(), + ) + .await; + assert_eq!(cancel_status, StatusCode::OK, "{cancelled}"); + assert_eq!(cancelled["state"], "cancelled", "{cancelled}"); + for member in ["decision", "input"] { + assert!(cancelled.get(member).is_none(), "{member}: {cancelled}"); + } + assert!(!cancelled.to_string().contains("Task reason canary")); + fixture.finish().await; +} diff --git a/crates/registry-breg/tests/postgres_record_attachments.rs b/crates/registry-breg/tests/postgres_record_attachments.rs index 6345d4a989..dac0b64787 100644 --- a/crates/registry-breg/tests/postgres_record_attachments.rs +++ b/crates/registry-breg/tests/postgres_record_attachments.rs @@ -162,15 +162,15 @@ fn record_source() -> Value { {"recordType":"programme","rowBoundaries":jurisdiction_boundary()}, {"recordType":"application","rowBoundaries":jurisdiction_boundary()}]}], "proposals":[{"action":"rename","operations":["get","list","edit","submit","apply"], - "ownership":"caller","readableAttachments":["support"],"writableAttachments":["support"], + "ownership":"caller","readableInputs":["target","value"],"readableAttachments":["support"],"writableAttachments":["support"], "targets":[{"recordType":"application","rowBoundaries":jurisdiction_boundary()}]}, {"action":"enrol","operations":["get","list","edit","submit"], - "ownership":"caller","readableAttachments":["document","note"], + "ownership":"caller","readableInputs":["name","jurisdiction","programme"],"readableAttachments":["document","note"], "writableAttachments":["document","note"],"targets":[ {"recordType":"programme","rowBoundaries":jurisdiction_boundary()}, {"recordType":"application","rowBoundaries":jurisdiction_boundary()}]}, {"action":"amend","operations":["get","list","edit","submit","apply"], - "ownership":"caller","readableAttachments":["document"], + "ownership":"caller","readableInputs":["target","name","jurisdiction","programme"],"readableAttachments":["document"], "writableAttachments":["document"],"targets":[ {"recordType":"programme","rowBoundaries":jurisdiction_boundary()}, {"recordType":"application","rowBoundaries":jurisdiction_boundary()}]}]}}, @@ -2700,6 +2700,7 @@ fn paired_promotion_source() -> Value { .unwrap() .push(json!({"action":"pair", "operations":["get","list","edit","submit","apply"],"ownership":"caller", + "readableInputs":["name","jurisdiction","programme"], "readableAttachments":["first","second"],"writableAttachments":["first","second"], "targets":targets})); source diff --git a/crates/registry-breg/tests/proposal_asks.rs b/crates/registry-breg/tests/proposal_asks.rs new file mode 100644 index 0000000000..a6df5aa082 --- /dev/null +++ b/crates/registry-breg/tests/proposal_asks.rs @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: Apache-2.0 +#[path = "support/proposal_hooks_model.rs"] +#[allow(dead_code)] +mod model; + +#[test] +fn applicant_can_hold_answer_authority() { + let mut source = model::source(serde_json::json!([])); + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["operations"] + .as_array_mut() + .unwrap() + .push(serde_json::json!("answer")); + let source = registry_breg::contract::parse_project_json(&serde_json::to_vec(&source).unwrap()); + assert!( + source.is_ok(), + "answer is a Proposal operation: {:?}", + source.err() + ); + let registry = registry_breg::compiler::compile_project( + &source.unwrap(), + &[], + registry_breg::compiler::CompileProfile::Authoring, + ); + assert!( + registry.is_ok(), + "answer authority compiles: {:?}", + registry.err() + ); +} + +#[test] +fn asks_are_bounded_in_single_documents_and_absent_from_batch_context_schema() { + let mut source = model::source(serde_json::json!([])); + let grant = &mut source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]; + grant["operations"] + .as_array_mut() + .unwrap() + .push(serde_json::json!("get-review-context")); + grant["readableContextFields"] = serde_json::json!(["value"]); + let registry = registry_breg::compiler::compile_project( + ®istry_breg::contract::parse_project_json(&serde_json::to_vec(&source).unwrap()) + .unwrap(), + &[], + registry_breg::compiler::CompileProfile::Authoring, + ) + .unwrap(); + let api: serde_json::Value = + serde_json::from_slice(®istry.artifacts().entries()["generated/openapi.json"].bytes) + .unwrap(); + let single = &api["paths"]["/v1/proposals/{proposal_id}/review-context"]["get"]["responses"] + ["200"]["content"]["application/json"]["schema"]; + assert_eq!( + single["properties"]["context"]["properties"]["asks"]["maxItems"], + 50 + ); + let batch = &api["paths"]["/v1/proposals/review-context"]["get"]["responses"]["200"]["content"] + ["application/json"]["schema"]["properties"]["items"]["items"]["oneOf"][0]["properties"] + ["context"]; + assert!(batch["properties"]["context"]["properties"] + .get("asks") + .is_none()); +} + +#[test] +fn ask_hooks_and_event_schema_share_the_transition_vocabulary() { + for name in ["asked", "answered"] { + let hook = model::local_hook("ask-observer", serde_json::json!([name])); + let project = registry_breg::contract::parse_project_json( + &serde_json::to_vec(&model::source(serde_json::json!([hook]))).unwrap(), + ); + assert!(project.is_ok(), "ask lifecycle hooks parse: {name}"); + let schema = registry_breg::proposal_hooks::proposal_event_schema(); + assert!(schema["properties"]["transition"]["enum"] + .as_array() + .unwrap() + .contains(&serde_json::json!(name))); + } +} + +#[test] +fn answer_openapi_declares_the_exact_problem_set_and_closed_ask_documents() { + use registry_breg::problem::ProblemCode as Code; + use std::collections::BTreeSet; + let mut source = model::source(serde_json::json!([])); + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["operations"] + .as_array_mut() + .unwrap() + .push(serde_json::json!("answer")); + let registry = registry_breg::compiler::compile_project( + ®istry_breg::contract::parse_project_json(&serde_json::to_vec(&source).unwrap()) + .unwrap(), + &[], + registry_breg::compiler::CompileProfile::Authoring, + ) + .unwrap(); + let api: serde_json::Value = + serde_json::from_slice(®istry.artifacts().entries()["generated/openapi.json"].bytes) + .unwrap(); + let operation = &api["paths"]["/v1/proposals/{proposal_id}/asks/{ask_id}/answer"]["post"]; + let request_schema = &operation["requestBody"]["content"]["application/json"]["schema"]; + let validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(request_schema) + .unwrap(); + assert!(!validator.is_valid(&serde_json::json!({}))); + assert!(!validator.is_valid(&serde_json::json!({"additions":[]}))); + assert!(validator.is_valid(&serde_json::json!({"text":"Explanation"}))); + assert!(validator + .is_valid(&serde_json::json!({"additions":["00000000-0000-4000-8000-000000000001"]}))); + assert_eq!(operation["operationId"], "proposals.answer"); + let expected = BTreeSet::from([ + Code::AuthenticationRefused, + Code::ResourceNotFound, + Code::ServiceUnavailable, + Code::SourceUnavailable, + Code::RequestTimeout, + Code::RequestInvalid, + Code::PreconditionFailed, + Code::MutationConflict, + Code::IdempotencyConflict, + Code::IdempotencyExpired, + Code::ProposalRejected, + Code::PreconditionRequired, + Code::UnsupportedMediaType, + ]) + .into_iter() + .map(|code| code.code().to_owned()) + .collect::>(); + let actual = operation["responses"] + .as_object() + .unwrap() + .values() + .filter_map(|response| { + response["content"]["application/problem+json"]["examples"].as_object() + }) + .flat_map(|examples| examples.keys().cloned()) + .collect::>(); + assert_eq!(actual, expected); + let schema = &operation["responses"]["200"]["content"]["application/json"]["schema"]; + assert_eq!(schema["additionalProperties"], false); + assert_eq!( + schema["properties"]["asks"]["items"]["additionalProperties"], + false + ); + let body = &operation["requestBody"]["content"]["application/json"]["schema"]; + assert_eq!(body["additionalProperties"], false); + assert_eq!(body["properties"]["additions"]["maxItems"], 32); +} diff --git a/crates/registry-breg/tests/proposal_default_grants.rs b/crates/registry-breg/tests/proposal_default_grants.rs index 32be909ab2..e4fd863866 100644 --- a/crates/registry-breg/tests/proposal_default_grants.rs +++ b/crates/registry-breg/tests/proposal_default_grants.rs @@ -71,7 +71,8 @@ fn overlapping_default_proposal_grants_are_refused_naming_both_profiles() { #[test] fn default_proposal_grants_with_disjoint_operations_compile() { - compile(&project(json!(["edit"]), json!(["get"]))) + // Submit, not Edit: an Edit grant must hold Get, which would overlap the other default's Get. + compile(&project(json!(["submit"]), json!(["get"]))) .expect("disjoint default operations are legal"); } diff --git a/crates/registry-breg/tests/proposal_hooks.rs b/crates/registry-breg/tests/proposal_hooks.rs index e52d45993e..2bc79e81d4 100644 --- a/crates/registry-breg/tests/proposal_hooks.rs +++ b/crates/registry-breg/tests/proposal_hooks.rs @@ -17,6 +17,23 @@ fn compile(source: &Value, assets: &[ModuleAssetSource]) -> registry_breg::Compi .unwrap() } +#[test] +fn additions_hooks_select_added_by_default_and_by_explicit_transition() { + use registry_breg::contract::ProposalEventTransition; + use std::collections::BTreeSet; + assert!( + registry_breg::proposal_hooks::matching_transitions(&BTreeSet::new()) + .any(|transition| transition == ProposalEventTransition::Added) + ); + assert_eq!( + registry_breg::proposal_hooks::matching_transitions(&BTreeSet::from([ + ProposalEventTransition::Added + ])) + .collect::>(), + vec![ProposalEventTransition::Added] + ); +} + #[test] fn proposal_observers_compile_native_owners_fixed_schema_and_reviewed_handlers() { let script = b"fn handle(ctx) { #{answer: \"none\"} }"; @@ -194,3 +211,23 @@ fn proposal_local_handlers_use_existing_abi_asset_and_build_admission() { assert!(!format!("{error:?}").contains("asset-missing")); } } + +#[test] +fn ask_hooks_select_asked_and_answered_by_default_and_explicit_filter() { + use registry_breg::contract::ProposalEventTransition; + use std::collections::BTreeSet; + for transition in [ + ProposalEventTransition::Asked, + ProposalEventTransition::Answered, + ] { + assert!( + registry_breg::proposal_hooks::matching_transitions(&BTreeSet::new()) + .any(|item| item == transition) + ); + assert_eq!( + registry_breg::proposal_hooks::matching_transitions(&BTreeSet::from([transition])) + .collect::>(), + vec![transition] + ); + } +} diff --git a/crates/registry-breg/tests/proposal_status_contract.rs b/crates/registry-breg/tests/proposal_status_contract.rs new file mode 100644 index 0000000000..3abec55a22 --- /dev/null +++ b/crates/registry-breg/tests/proposal_status_contract.rs @@ -0,0 +1,459 @@ +// SPDX-License-Identifier: Apache-2.0 +#![cfg(feature = "schema")] + +#[path = "support/proposal_hooks_model.rs"] +#[allow(dead_code)] +mod model; + +#[test] +fn shipped_required_attachment_example_reproduces_its_openapi() { + let source = + include_bytes!("../../../products/breg/examples/required-attachment/registry.yaml"); + let registry = registry_breg::compiler::compile_project( + ®istry_breg::contract::parse_project_yaml(source).unwrap(), + &[], + registry_breg::compiler::CompileProfile::Authoring, + ) + .unwrap(); + let generated = ®istry.artifacts().entries()["generated/openapi.json"].bytes; + let committed = + include_bytes!("../../../products/breg/examples/required-attachment/openapi.json"); + assert!( + generated.as_slice() == committed, + "regenerate the required-attachment example's OpenAPI with example-artifacts" + ); + let api: serde_json::Value = serde_json::from_slice(generated).unwrap(); + assert_eq!( + api["paths"]["/v1/proposals/{proposal_id}/submit"]["post"]["responses"]["422"]["content"] + ["application/problem+json"]["examples"]["attachment.required"]["value"]["fieldPath"], + "/attachments/support" + ); +} + +#[test] +fn shipped_submit_examples_use_problem_code_keys() { + let api: serde_json::Value = serde_json::from_slice(include_bytes!( + "../../../products/breg/generated/facility/generated/openapi.json" + )) + .unwrap(); + let examples = api["paths"]["/v1/proposals/{proposal_id}/submit"]["post"]["responses"]["422"] + ["content"]["application/problem+json"]["examples"] + .as_object() + .unwrap(); + let mut refusals = 0; + for (key, example) in examples { + let code = example["value"]["code"].as_str().unwrap(); + if code == "action.refused" { + refusals += 1; + } + assert!( + key == code + || key + .strip_prefix(code) + .is_some_and(|suffix| suffix.starts_with('/')), + "example {key} must be keyed by problem code {code}" + ); + } + assert!( + refusals > 0, + "the example must exercise declared planner refusals" + ); +} + +#[test] +fn apply_declares_encryption_failure_for_an_encrypted_write() { + let mut source = model::source(serde_json::json!([])); + source["recordTypes"]["target"]["fields"][0]["encrypted"] = serde_json::json!(true); + let registry = registry_breg::compiler::compile_project( + ®istry_breg::contract::parse_project_json(&serde_json::to_vec(&source).unwrap()) + .unwrap(), + &[], + registry_breg::compiler::CompileProfile::Authoring, + ) + .unwrap(); + let api: serde_json::Value = + serde_json::from_slice(®istry.artifacts().entries()["generated/openapi.json"].bytes) + .unwrap(); + assert_eq!( + api["paths"]["/v1/proposals/{proposal_id}/apply"]["post"]["responses"]["503"]["content"] + ["application/problem+json"]["examples"]["runtime.field_encryption.unavailable"] + ["value"]["code"], + "runtime.field_encryption.unavailable" + ); + assert!( + api["paths"]["/v1/proposals/{proposal_id}/submit"]["post"]["responses"]["503"]["content"] + ["application/problem+json"]["examples"] + .get("runtime.field_encryption.unavailable") + .is_none() + ); +} + +#[test] +fn proposal_availability_objects_use_a_typed_constructor() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/mutation"); + let mut files = vec![root.join("proposal.rs")]; + let mut directories = vec![root.join("proposal")]; + while let Some(directory) = directories.pop() { + for entry in std::fs::read_dir(directory).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + directories.push(path); + } else if path.extension().is_some_and(|extension| extension == "rs") { + files.push(path); + } + } + } + for path in files { + let source = std::fs::read_to_string(&path).unwrap(); + assert!( + !source.contains("[\"availability\"]"), + "{}: availability must not be assembled by mutating JSON", + path.display() + ); + for line in source + .lines() + .filter(|line| line.contains("\"availability\":")) + { + assert!( + line.contains("ProposalAvailability::"), + "{}: untyped availability: {line}", + path.display() + ); + } + } +} + +#[test] +fn every_proposal_error_response_declares_its_problem_body() { + use registry_breg::{ + compiler::{compile_project, CompileProfile}, + contract::parse_project_json, + }; + use serde_json::{json, Value}; + let mut source = model::source(json!([])); + source["reviewAuthorities"] = + json!({"local-review":{"protocol":"id.registrystack.org/protocols/review/v1"}}); + let policy = &mut source["actions"]["correct-name"]["execution"]["proposal"]; + policy["attachments"][0]["required"] = json!(true); + let mut optional = policy["attachments"][0].clone(); + optional["id"] = json!("supplement"); + optional["required"] = json!(false); + policy["attachments"].as_array_mut().unwrap().push(optional); + policy["review"] = json!({"type":"required","authority":"local-review","source":"proposal-test", + "policy":{"id":"name-correction","version":"1","digest":format!("sha256:{}","b".repeat(64))}}); + policy["additions"] = json!({"id":"other","maximumBytes":32,"maximumCount":2,"contentTypes":["text/plain"],"classification":"restricted"}); + policy["reviewContext"]["fields"]["document"] = json!({"type":"document","slot":"support"}); + policy["reviewContext"]["fields"]["other"] = json!({"type":"additions","slot":"other"}); + let grant = &mut source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]; + grant["operations"] = json!([ + "get", + "list", + "edit", + "submit", + "revise", + "rebase", + "cancel", + "apply", + "retry", + "add", + "answer", + "get-review-status", + "get-review-context", + "get-task-grant-context" + ]); + grant["readableAttachments"] = json!(["support", "other"]); + grant["writableAttachments"] = json!(["support", "other"]); + grant["readableContextFields"] = json!(["value", "document", "other"]); + grant["operations"] + .as_array_mut() + .unwrap() + .retain(|operation| operation != "get-task-grant-context"); + let mut service = source["accessProfiles"]["clerk"].clone(); + service["default"] = json!(false); + service["actorKind"] = json!("service"); + service["requesterClients"] = json!(["review-provider"]); + service["permissions"]["proposals"][0]["operations"] = json!(["get", "get-task-grant-context"]); + service["permissions"]["proposals"][0]["writableAttachments"] = json!([]); + source["accessProfiles"]["review-service"] = service; + let registry = compile_project( + &parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(), + &[], + CompileProfile::Authoring, + ) + .unwrap(); + let api: Value = + serde_json::from_slice(®istry.artifacts().entries()["generated/openapi.json"].bytes) + .unwrap(); + let mut routes = Vec::new(); + let mut omissions = Vec::new(); + let problem_schema = &api["components"]["schemas"]["Problem"]; + let validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(problem_schema) + .unwrap(); + for (path, item) in api["paths"].as_object().unwrap() { + for (method, operation) in item.as_object().unwrap() { + let Some(id) = operation["operationId"].as_str() else { + continue; + }; + if !path.starts_with("/v1/proposals") && !id.ends_with(".start") { + continue; + } + routes.push(format!("{method} {path}")); + // Pin handler-level codes, independently of the schema generator: + // read handlers conceal malformed inputs and failed preconditions; + // raw slot bodies have their own media/size problems. + use registry_breg::problem::ProblemCode as Code; + let mut expected = std::collections::BTreeSet::from([ + Code::AuthenticationRefused, + Code::ResourceNotFound, + Code::ServiceUnavailable, + Code::SourceUnavailable, + Code::RequestTimeout, + ]); + if id == "proposals.list" { + expected.insert(Code::QueryInvalid); + } else if id == "proposals.get-task-grant-context" { + expected.extend([Code::RequestInvalid, Code::UnsupportedMediaType]); + } else if method != "get" { + expected.extend([ + Code::RequestInvalid, + Code::PreconditionFailed, + Code::MutationConflict, + Code::IdempotencyConflict, + Code::IdempotencyExpired, + ]); + if !id.ends_with(".start") { + expected.extend([Code::PreconditionRequired, Code::ProposalRejected]); + } + if method == "patch" || id.starts_with("proposals.additions.") { + expected.extend([Code::AttachmentContentType, Code::AttachmentTooLarge]); + if method == "post" { + expected.insert(Code::AttachmentLimitReached); + } + } else if method != "delete" { + expected.insert(Code::UnsupportedMediaType); + } + if id == "proposals.submit" { + expected.extend([ + Code::AttachmentRequired, + Code::AttachmentVerificationPending, + Code::AttachmentVerificationRejected, + ]); + } + if id == "proposals.apply" { + expected.insert(Code::ProposalReviewResultMismatch); + } + } + if id == "proposals.get-submission" { + expected.insert(Code::ProposalSubmissionExpired); + } + let actual = operation["responses"] + .as_object() + .unwrap() + .values() + .filter_map(|response| { + response["content"]["application/problem+json"]["examples"].as_object() + }) + .flat_map(|examples| { + examples + .values() + .map(|example| example["value"]["code"].as_str().unwrap().to_owned()) + }) + .collect::>(); + let expected = expected + .iter() + .map(|code| code.code().to_owned()) + .collect::>(); + assert_eq!( + actual, expected, + "problem code set for {id} ({method} {path})" + ); + for (status, response) in operation["responses"].as_object().unwrap() { + if !status.starts_with('2') { + let problem = &response["content"]["application/problem+json"]; + let examples = problem["examples"] + .as_object() + .unwrap() + .values() + .map(|example| example["value"]["code"].as_str().unwrap().to_owned()) + .collect::>(); + let declared = problem["schema"]["allOf"][1]["properties"]["code"]["enum"] + .as_array() + .map(|codes| { + codes + .iter() + .map(|code| code.as_str().unwrap().to_owned()) + .collect::>() + }) + .unwrap_or_default(); + assert_eq!( + declared, examples, + "{id} {status} must constrain its own problem codes" + ); + } + if !status.starts_with('2') + && response["content"]["application/problem+json"]["schema"].is_null() + { + omissions.push(format!("{method} {path}: {status}")); + } + if !status.starts_with('2') { + if let Some(examples) = + response["content"]["application/problem+json"]["examples"].as_object() + { + for (code, example) in examples { + assert!( + validator.is_valid(&example["value"]), + "{method} {path}: {status} {code}" + ); + } + } + } + } + } + } + for required in [ + "/submissions/", + "/review-status", + "/review-context", + "/task-grant-context", + "/attachments/", + "/additions/", + ] { + assert!( + routes.iter().any(|route| route.contains(required)), + "fixture misses {required}" + ); + } + assert!( + routes.len() >= 18, + "fixture must cover the full Proposal surface: {routes:?}" + ); + assert!( + omissions.is_empty(), + "Proposal errors lack problem schemas: {omissions:?}" + ); + assert_eq!( + api["paths"]["/v1/proposals/{proposal_id}/submit"]["post"]["responses"]["422"]["content"] + ["application/problem+json"]["examples"]["attachment.required"]["value"]["code"], + "attachment.required" + ); +} + +#[test] +fn every_proposal_availability_reason_is_in_the_served_schema() { + let served = registry_breg::artifacts::availability_schema(); + let registry = registry_breg::compiler::compile_project( + ®istry_breg::contract::parse_project_json( + &serde_json::to_vec(&model::source(serde_json::json!([]))).unwrap(), + ) + .unwrap(), + &[], + registry_breg::compiler::CompileProfile::Authoring, + ) + .unwrap(); + for path in ["generated/sdk/project.ts", "generated/sdk/project.py"] { + let source = std::str::from_utf8(®istry.artifacts().entries()[path].bytes).unwrap(); + for (name, expected) in [ + ( + "EngineReason", + registry_breg::lifecycle::ProposalAvailabilityReason::ALL + .iter() + .map(|value| value.as_str()) + .collect::>(), + ), + ( + "RecoveryHint", + registry_breg::lifecycle::ProposalLinkRecovery::ALL + .iter() + .map(|value| value.as_str()) + .collect::>(), + ), + ] { + let declaration = source + .lines() + .find(|line| { + line.starts_with(&format!("export type {name} =")) + || line.starts_with(&format!("{name} =")) + }) + .unwrap(); + let actual = declaration + .split('\'') + .enumerate() + .filter_map(|(index, value)| (index % 2 == 1).then_some(value)) + .collect::>(); + assert_eq!( + actual, expected, + "{path} {name} must use the served vocabulary" + ); + } + } + for reason in registry_breg::lifecycle::ProposalAvailabilityReason::ALL { + let wire = serde_json::to_value(reason).unwrap(); + assert!( + served["properties"]["reason"]["enum"] + .as_array() + .unwrap() + .contains(&wire), + "served availability schema omits {wire}" + ); + serde_json::from_value::(wire).unwrap(); + } + for recovery in registry_breg::lifecycle::ProposalLinkRecovery::ALL { + let wire = serde_json::to_value(recovery).unwrap(); + assert!( + served["properties"]["recovery"]["enum"] + .as_array() + .unwrap() + .contains(&wire), + "served availability schema omits {wire}" + ); + serde_json::from_value::(wire).unwrap(); + } +} + +#[test] +fn proposal_availability_pairs_match_the_client_contract() { + use registry_breg::lifecycle::{ + ProposalAvailability, ProposalAvailabilityReason, ProposalLinkRecovery, ProposalLinkRefusal, + }; + use registry_breg_client::BRegProposal; + use serde_json::json; + let accepts = |reason, recovery| { + ["draft", "submitted", "applied", "rejected", "cancelled"].iter().any(|state| { + let id = "705cd4a4-526e-41ca-b88b-6ca8f82a87af"; + let digest = format!("sha256:{}", "a".repeat(64)); + let mut value = json!({"id":id,"actionId":"correct","actionRevision":digest, + "state":state,"submissionVersion":1,"revision":2,"links":{ + "self":{"method":"GET","path":format!("/v1/proposals/{id}"),"accessProfile":"writer","operation":"get", + "availability":{"available":false,"observedRevision":2,"reason":reason,"recovery":recovery}} + }}); + if *state == "submitted" { value["effectDigest"] = json!(digest); } + BRegProposal::from_slice(&serde_json::to_vec(&value).unwrap()).is_ok() + }) + }; + for reason in ProposalAvailabilityReason::ALL { + for recovery in ProposalLinkRecovery::ALL { + let declared = ProposalLinkRefusal::ALL + .iter() + .any(|refusal| refusal.pair() == (*reason, *recovery)); + assert_eq!( + accepts(reason, recovery), + declared, + "{reason:?}/{recovery:?}" + ); + } + } + for refusal in ProposalLinkRefusal::ALL { + let value = serde_json::to_value(ProposalAvailability::new(2, Some(*refusal))).unwrap(); + assert_eq!(value["available"], false); + assert_eq!( + value["reason"], + serde_json::to_value(refusal.pair().0).unwrap() + ); + assert_eq!( + value["recovery"], + serde_json::to_value(refusal.pair().1).unwrap() + ); + } +} diff --git a/crates/registry-breg/tests/refactor_contract.rs b/crates/registry-breg/tests/refactor_contract.rs index 4be44cca0d..4f340e1b7b 100644 --- a/crates/registry-breg/tests/refactor_contract.rs +++ b/crates/registry-breg/tests/refactor_contract.rs @@ -374,6 +374,32 @@ fn proposal_attachments_require_explicit_bounded_slot_grants() { assert!(parse_project_json(&serde_json::to_vec(&value).unwrap()).is_err()); } +/// The download answers with the stored content type, so its declaration +/// is `*/*` as the Document Store's content download declares it: a generated +/// client then finds a matching response for any stored type. +#[test] +fn proposal_attachment_download_declares_any_media_type_for_its_content() { + let model = compile(&parse_project_yaml(PROJECT).unwrap()).unwrap(); + let openapi: serde_json::Value = serde_json::from_slice( + &model + .artifacts() + .get("generated/openapi.json") + .unwrap() + .bytes, + ) + .unwrap(); + let content = openapi["paths"]["/v1/proposals/{proposal_id}/attachments/supporting-document"] + ["get"]["responses"]["200"]["content"] + .as_object() + .unwrap(); + assert_eq!(content.keys().collect::>(), ["*/*"]); + assert_eq!(content["*/*"]["schema"]["type"], "string"); + assert_eq!( + content["*/*"]["schema"]["contentMediaType"], + "application/octet-stream" + ); +} + #[test] fn proposal_attachment_download_schema_requires_a_positive_u32_submission_version() { use serde_json::json; diff --git a/crates/registry-breg/tests/standing_agent_ceiling.rs b/crates/registry-breg/tests/standing_agent_ceiling.rs index a929710d10..f75796a45e 100644 --- a/crates/registry-breg/tests/standing_agent_ceiling.rs +++ b/crates/registry-breg/tests/standing_agent_ceiling.rs @@ -56,7 +56,7 @@ fn project() -> Value { "actions":[ {"action":"relabel-note","operations":["invoke"],"targets":[{"recordType":"note","rowBoundaries":"unrestricted"}],"results":["relabelled"]}, {"action":"correct-case","operations":["start"],"targets":[{"recordType":"case","rowBoundaries":"unrestricted"}]}], - "proposals":[{"action":"correct-case","operations":["get","list","edit","submit","revise","cancel","apply","rebase","retry","get-review-status"],"ownership":"caller","targets":[{"recordType":"case","rowBoundaries":"unrestricted"}]}]}}, + "proposals":[{"action":"correct-case","operations":["get","list","edit","submit","revise","cancel","apply","rebase","retry","get-review-status"],"ownership":"caller","readableInputs":["case-ref","new-label"],"targets":[{"recordType":"case","rowBoundaries":"unrestricted"}]}]}}, "assistant": {"principalClaim":"registry_principal","requiredScopes":"unrestricted","actorKind":"agent","requesterClients":["assistant-client"], "permissions":{"records":[ {"recordType":"case","operations":["get","list"],"readableFields":["label"],"rowBoundaries":"unrestricted"}, @@ -82,6 +82,15 @@ fn codes(failure: &CompileFailure) -> Vec<&str> { .collect() } +/// Gives the standing agent's draft grant the read of the inputs it writes. A +/// profile that is no longer a standing agent may hold Get, and must read every +/// input it may write. +fn assistant_reads_its_inputs(value: &mut Value) { + let grant = &mut value["accessProfiles"]["assistant"]["permissions"]["proposals"][0]; + grant["operations"] = json!(["get", "edit"]); + grant["readableInputs"] = json!(["case-ref", "new-label"]); +} + /// Compiles a project expected to be refused, without printing the compiled /// registry when it is not. fn refused( @@ -388,6 +397,7 @@ fn human_profiles_keep_immediate_actions() { // profile bound to the agent's client keeps it too. let mut value = project(); value["accessProfiles"]["assistant"]["actorKind"] = json!("human"); + assistant_reads_its_inputs(&mut value); with_assistant_action(&mut value); let registry = compile(&value).expect("human profiles keep immediate actions"); let action = registry @@ -565,6 +575,7 @@ fn human_service_and_unspecified_profiles_keep_publish() { for actor_kind in ["human", "service"] { let mut direct = with_dataset(&[], &["publish", "read-releases"]); direct["accessProfiles"]["assistant"]["actorKind"] = json!(actor_kind); + assistant_reads_its_inputs(&mut direct); let registry = compile(&direct).unwrap_or_else(|failure| { panic!("a {actor_kind} profile lost publish: {:?}", codes(&failure)) }); @@ -577,6 +588,7 @@ fn human_service_and_unspecified_profiles_keep_publish() { .expect("profile object"); profile.remove("actorKind"); profile.remove("requesterClients"); + assistant_reads_its_inputs(&mut unspecified); let registry = compile(&unspecified).expect("a profile with no actor kind keeps publish"); assert_eq!(publisher(®istry), "assistant"); } @@ -664,6 +676,8 @@ fn task_grant_and_human_profiles_keep_their_ceilings() { "retry", "get-review-status" ]); + delegated["accessProfiles"]["assistant"]["permissions"]["proposals"][0]["readableInputs"] = + json!(["case-ref", "new-label"]); compile(&delegated).expect("explicit task grants retain bounded Proposal lifecycle operations"); let mut delegated_action = delegated.clone(); with_assistant_action(&mut delegated_action); @@ -741,3 +755,52 @@ fn module_contributed_profiles_cannot_declare_a_task_grant() { ); } } + +/// Only a standing agent drafts blind. A human profile, a task-granted agent +/// and a profile with no actor kind that may edit must read every input. +#[test] +fn only_a_standing_agent_may_edit_inputs_it_cannot_read() { + const UNREADABLE: &str = "breg.proposal.input-write-unreadable"; + let editing = |value: &mut Value| { + value["accessProfiles"]["assistant"]["permissions"]["proposals"][0]["operations"] = + json!(["get", "edit"]); + }; + let mut human = project(); + human["accessProfiles"]["assistant"]["actorKind"] = json!("human"); + editing(&mut human); + let mut delegated = project(); + delegated["accessProfiles"]["assistant"]["requiredPurposes"] = json!(["correction-review"]); + delegated["accessProfiles"]["assistant"]["taskGrant"] = + json!({"sourceIssuer":"https://casework.example"}); + editing(&mut delegated); + let mut unspecified = project(); + let profile = unspecified["accessProfiles"]["assistant"] + .as_object_mut() + .expect("profile object"); + profile.remove("actorKind"); + profile.remove("requesterClients"); + editing(&mut unspecified); + for (case, value) in [ + ("human", human), + ("task-granted agent", delegated), + ("no actor kind", unspecified), + ] { + let failure = refused(compile(&value), case); + let diagnostic = failure + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == UNREADABLE) + .unwrap_or_else(|| panic!("{case}: {:?}", codes(&failure))); + assert!( + diagnostic.message.contains("`assistant`"), + "{case}: {diagnostic:?}" + ); + let mut reads = value.clone(); + assistant_reads_its_inputs(&mut reads); + if let Err(failure) = compile(&reads) { + assert!(!codes(&failure).contains(&UNREADABLE), "{case}"); + } + } + // The standing agent edits without Get or readableInputs. + compile(&project()).expect("a standing agent drafts blind"); +} diff --git a/crates/registry-breg/tests/support/proposal_additions.rs b/crates/registry-breg/tests/support/proposal_additions.rs new file mode 100644 index 0000000000..6e36c19bfb --- /dev/null +++ b/crates/registry-breg/tests/support/proposal_additions.rs @@ -0,0 +1,932 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; + +#[path = "proposal_additions_authority.rs"] +mod authority; + +fn addition_source() -> Value { + let mut source = registry_source(false); + source["reviewAuthorities"] = + json!({"local-review":{"protocol":"id.registrystack.org/protocols/review/v1"}}); + let proposal = &mut source["actions"]["correct-name"]["execution"]["proposal"]; + proposal["review"] = json!({"type":"required","authority":"local-review","source":"proposal-test", + "policy":{"id":"name-correction","version":"1","digest":format!("sha256:{}","b".repeat(64))}}); + proposal["additions"] = json!({"id":"other","maximumBytes":32,"maximumCount":2,"contentTypes":["text/plain"],"classification":"restricted"}); + let grant = &mut source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]; + grant["operations"] + .as_array_mut() + .unwrap() + .push(json!("add")); + grant["readableAttachments"] + .as_array_mut() + .unwrap() + .push(json!("other")); + grant["writableAttachments"] + .as_array_mut() + .unwrap() + .push(json!("other")); + source +} + +async fn fixture() -> client_http::ClientFixture { + let review = std::sync::Arc::new(LocalReview { + calls: 0.into(), + mode: 0.into(), + result_id: uuid::Uuid::new_v4(), + }); + client_http::ClientFixture::start_with_mutations( + compile(addition_source()), + claims("author", "zone-a"), + move |mutations| { + mutations.with_proposal_review_substitute_for_test(local_review_binding(), review) + }, + ) + .await +} + +async fn add( + fixture: &client_http::ClientFixture, + id: &str, + etag: &str, + key: &str, + content_type: &str, + bytes: &[u8], +) -> reqwest::Response { + reqwest::Client::new() + .post(format!( + "{}/v1/proposals/{id}/additions/other?accessProfile=clerk", + fixture.http.base_url + )) + .header("if-match", etag) + .header("idempotency-key", key) + .header("content-type", content_type) + .body(bytes.to_vec()) + .send() + .await + .unwrap() +} + +async fn submitted_addition_proposal( + fixture: &client_http::ClientFixture, + prefix: &str, +) -> registry_breg_client::BRegProposal { + let draft = start(fixture, "Supporting files", &format!("{prefix}-start")).await; + fixture + .http + .client + .execute_proposal( + &fixture + .http + .client + .prepare_proposal( + &draft, + "submit", + json!({}), + &key(&format!("{prefix}-submit")), + ) + .unwrap(), + ) + .await + .unwrap() + .value +} + +#[tokio::test] +async fn additions_remain_readable_after_the_operator_lowers_the_count_limit() { + let fixture = fixture().await; + let mut proposal = submitted_addition_proposal(&fixture, "count-lowered").await; + for index in 0..2 { + proposal = fixture + .http + .client + .add_proposal_addition( + &proposal, + "other", + "text/plain", + b"retained", + &key(&format!("count-lowered-{index}")), + ) + .await + .unwrap() + .value; + } + let mut next = addition_source(); + next["actions"]["correct-name"]["execution"]["proposal"]["additions"]["maximumCount"] = + json!(1); + let (registry, identity) = proposal_activation::activate_successor(&fixture, &next).await; + let current = successor_client(&fixture, registry, identity).await; + let raw = reqwest::get(format!( + "{}/v1/proposals/{}?accessProfile=clerk", + current.base_url, + proposal.id() + )) + .await + .unwrap(); + assert_eq!(raw.status(), 200); + let value: Value = raw.json().await.unwrap(); + assert_eq!(value["additions"]["other"]["maximumCount"], 1); + assert_eq!( + value["additions"]["other"]["items"] + .as_array() + .unwrap() + .len(), + 2 + ); + assert_eq!( + value["additions"]["other"]["links"]["add"]["availability"]["reason"], + "limit-reached" + ); + let contract = current + .client + .registry_contract(Some("clerk")) + .await + .unwrap() + .value; + let retained = current + .client + .get_proposal( + &contract.select_proposal_get("clerk").unwrap(), + proposal.id(), + ) + .await + .expect("a lower limit preserves readable retained additions") + .value; + let file = retained.addition_slot("other").unwrap().items()[0].id(); + assert_eq!( + current + .client + .download_proposal_addition(&retained, file) + .await + .unwrap() + .value + .as_bytes(), + b"retained" + ); + drop(current); + fixture.finish().await; +} + +#[tokio::test] +async fn additions_report_a_failed_body_read_as_an_invalid_request() { + use tower::util::ServiceExt; + struct FailedBody; + impl futures_core::Stream for FailedBody { + type Item = Result; + fn poll_next( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Some(Err(std::io::Error::other("synthetic aborted body")))) + } + } + let fixture = fixture().await; + let proposal = submitted_addition_proposal(&fixture, "aborted-body").await; + let value = serde_json::to_value(&proposal).unwrap(); + let etag = value["additions"]["other"]["links"]["add"]["ifMatch"] + .as_str() + .unwrap(); + let app = registry_breg::api::router(fixture.service()) + .layer(axum::Extension(claims("author", "zone-a"))); + let response = app + .oneshot( + axum::http::Request::builder() + .method("POST") + .uri(format!( + "/v1/proposals/{}/additions/other?accessProfile=clerk", + proposal.id() + )) + .header("if-match", etag) + .header("idempotency-key", "aborted-file") + .header("content-type", "text/plain") + .body(axum::body::Body::from_stream(FailedBody)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), 400); + let bytes = axum::body::to_bytes(response.into_body(), 8192) + .await + .unwrap(); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["code"], "request.invalid"); + fixture.finish().await; +} + +#[tokio::test] +async fn additions_keep_the_submission_and_digest_but_fence_tabs_and_replay() { + let fixture = fixture().await; + let client = &fixture.http.client; + let draft = start(&fixture, "After", "add-start").await; + let submitted = client + .execute_proposal( + &client + .prepare_proposal(&draft, "submit", json!({}), &key("add-submit")) + .unwrap(), + ) + .await + .unwrap() + .value; + let before = serde_json::to_value(&submitted).unwrap(); + let etag = before["additions"]["other"]["links"]["add"]["ifMatch"] + .as_str() + .expect("add link"); + let first = add( + &fixture, + submitted.id(), + etag, + "addition-one", + "text/plain", + b"first", + ) + .await; + assert_eq!(first.status(), 200); + let new_etag = first.headers()["etag"].to_str().unwrap().to_owned(); + let first_bytes = first.bytes().await.unwrap(); + let added: Value = serde_json::from_slice(&first_bytes).unwrap(); + assert_eq!(added["state"], "submitted"); + assert_eq!(added["submissionVersion"], before["submissionVersion"]); + assert_eq!(added["effectDigest"], before["effectDigest"]); + assert_ne!(new_etag, etag); + assert!(added["revision"].as_u64().unwrap() > before["revision"].as_u64().unwrap()); + let replay = add( + &fixture, + submitted.id(), + etag, + "addition-one", + "text/plain", + b"first", + ) + .await; + assert_eq!(replay.status(), 200); + assert_eq!(replay.bytes().await.unwrap(), first_bytes); + assert_eq!( + add( + &fixture, + submitted.id(), + etag, + "addition-one", + "text/plain", + b"changed" + ) + .await + .status(), + 409 + ); + assert_eq!( + add( + &fixture, + submitted.id(), + etag, + "addition-stale", + "text/plain", + b"second" + ) + .await + .status(), + 412 + ); + for (kind, bytes, status, code) in [ + ( + "application/pdf", + b"file".as_slice(), + 415, + "attachment.content-type", + ), + ( + "text/plain", + b"012345678901234567890123456789012", + 413, + "attachment.too-large", + ), + ("text/plain", b"", 400, "request.invalid"), + ] { + let refusal = add( + &fixture, + submitted.id(), + &new_etag, + "addition-refused", + kind, + bytes, + ) + .await; + assert_eq!(refusal.status(), status); + assert_eq!(refusal.json::().await.unwrap()["code"], code); + } + let download = &added["additions"]["other"]["items"][0]["links"]["download"]; + let response = reqwest::get(format!( + "{}{}&accessProfile=clerk", + fixture.http.base_url, + download["path"].as_str().unwrap() + )) + .await + .unwrap(); + assert_eq!(response.status(), 200); + assert_eq!(response.headers()["x-content-type-options"], "nosniff"); + assert_eq!(response.headers()["cache-control"], "no-store"); + assert_eq!(response.bytes().await.unwrap(), b"first".as_slice()); + let second = add( + &fixture, + submitted.id(), + &new_etag, + "addition-two", + "text/plain", + b"second", + ) + .await; + assert_eq!(second.status(), 200); + let etag = second.headers()["etag"].to_str().unwrap().to_owned(); + let second: Value = second.json().await.unwrap(); + assert_eq!( + second["additions"]["other"]["items"] + .as_array() + .unwrap() + .len(), + 2 + ); + assert_eq!( + second["additions"]["other"]["links"]["add"]["availability"]["reason"], + "limit-reached" + ); + let limited = add( + &fixture, + submitted.id(), + &etag, + "addition-three", + "text/plain", + b"third", + ) + .await; + assert_eq!(limited.status(), 409); + assert_eq!( + limited.json::().await.unwrap()["code"], + "attachment.limit-reached" + ); + let rows = fixture.database.admin.query("SELECT payload FROM registry_internal.registry_outbox WHERE event_type='proposal.added'", &[]).await.unwrap(); + assert_eq!(rows.len(), 2); + fixture.finish().await; +} + +#[tokio::test] +async fn additions_keep_shared_blobs_live_until_their_retention_erases_them() { + let fixture = fixture().await; + let client = &fixture.http.client; + let draft = start(&fixture, "After", "retained-add-start").await; + let submitted = client + .execute_proposal( + &client + .prepare_proposal(&draft, "submit", json!({}), &key("retained-add-submit")) + .unwrap(), + ) + .await + .unwrap() + .value; + let before = serde_json::to_value(&submitted).unwrap(); + let etag = before["additions"]["other"]["links"]["add"]["ifMatch"] + .as_str() + .unwrap(); + let added = add( + &fixture, + submitted.id(), + etag, + "retained-add-one", + "text/plain", + b"shared", + ) + .await; + assert_eq!(added.status(), 200); + let added: Value = added.json().await.unwrap(); + let other = start(&fixture, "Other", "other-add-start").await; + let uploaded = client + .upload_proposal_attachment( + &other, + "support", + "text/plain", + b"shared", + &key("shared-upload"), + ) + .await + .unwrap() + .value; + client + .delete_proposal_attachment(&uploaded, "support", &key("shared-remove")) + .await + .unwrap(); + let path = added["additions"]["other"]["items"][0]["links"]["download"]["path"] + .as_str() + .unwrap(); + let response = reqwest::get(format!( + "{}{}&accessProfile=clerk", + fixture.http.base_url, path + )) + .await + .unwrap(); + assert_eq!( + response.status(), + 200, + "removing the draft file must keep the addition's bytes" + ); + assert_eq!(response.bytes().await.unwrap(), b"shared".as_slice()); + let current = client.read_proposal(&submitted).await.unwrap().value; + client + .execute_proposal( + &client + .prepare_proposal(¤t, "cancel", json!({}), &key("retained-add-cancel")) + .unwrap(), + ) + .await + .unwrap(); + let (mut migration, task) = fixture.database.connect_migration().await; + let erased = registry_breg::proposal_retention::erase_proposal_detail( + &mut migration, + &fixture.registry, + registry_breg::proposal_retention::ProposalDetailErasureScope { + action_id: "correct-name", + proposal_id: uuid::Uuid::parse_str(submitted.id()).unwrap(), + submission_version: 1, + }, + ) + .await + .unwrap(); + assert_eq!(erased.attachment_references, 1); + let row = fixture.database.admin.query_one("SELECT + (SELECT count(*) FROM registry_internal.registry_proposal_additions WHERE erased_at IS NULL), + (SELECT count(*) FROM registry_internal.registry_attachment_blobs)", &[]).await.unwrap(); + assert_eq!(row.get::<_, i64>(0), 0); + assert_eq!(row.get::<_, i64>(1), 0); + drop(migration); + task.abort(); + fixture.finish().await; +} + +#[tokio::test] +async fn additions_reviewer_reads_live_files_under_the_exact_context_binding() { + let mut source = addition_source(); + source["actions"]["correct-name"]["execution"]["proposal"]["reviewContext"] = json!({"id":"supporting-review", + "fields":{"otherDocuments":{"type":"additions","slot":"other"}}}); + let mut reviewer = source["accessProfiles"]["clerk"].clone(); + reviewer["default"] = json!(false); + reviewer["permissions"]["actions"] = json!([]); + reviewer["permissions"]["records"] = json!([]); + let grant = &mut reviewer["permissions"]["proposals"][0]; + grant["operations"] = json!(["get-review-context"]); + grant.as_object_mut().unwrap().remove("ownership"); + grant["readableInputs"] = json!([]); + grant["readableAttachments"] = json!([]); + grant["writableAttachments"] = json!([]); + grant["readableContextFields"] = json!(["otherDocuments"]); + source["accessProfiles"]["reviewer"] = reviewer; + let mut hidden = source["accessProfiles"]["clerk"].clone(); + hidden["default"] = json!(false); + hidden["permissions"]["actions"] = json!([]); + hidden["permissions"]["proposals"][0]["operations"] = json!(["get"]); + hidden["permissions"]["proposals"][0]["readableAttachments"] = json!([]); + hidden["permissions"]["proposals"][0]["writableAttachments"] = json!([]); + source["accessProfiles"]["no-files"] = hidden; + let review = std::sync::Arc::new(LocalReview { + calls: 0.into(), + mode: 0.into(), + result_id: uuid::Uuid::new_v4(), + }); + let fixture = client_http::ClientFixture::start_with_mutations( + compile(source), + claims("author", "zone-a"), + move |mutations| { + mutations.with_proposal_review_substitute_for_test(local_review_binding(), review) + }, + ) + .await; + let reviewer_http = client_http::ClientHttp::start( + registry_breg::api::router(fixture.service()), + claims("reviewer", "zone-a"), + ) + .await; + let draft = start(&fixture, "Reviewed", "review-add-start").await; + let client = &fixture.http.client; + let submitted = client + .execute_proposal( + &client + .prepare_proposal(&draft, "submit", json!({}), &key("review-add-submit")) + .unwrap(), + ) + .await + .unwrap() + .value; + let value = serde_json::to_value(&submitted).unwrap(); + let etag = value["additions"]["other"]["links"]["add"]["ifMatch"] + .as_str() + .unwrap(); + let added = add( + &fixture, + submitted.id(), + etag, + "review-add-one", + "text/plain", + b"review-file", + ) + .await; + assert_eq!(added.status(), 200); + let added: Value = added.json().await.unwrap(); + let context = reqwest::get(format!( + "{}/v1/proposals/{}/review-context?accessProfile=reviewer", + reviewer_http.base_url, + submitted.id() + )) + .await + .unwrap(); + assert_eq!(context.status(), 200); + let context: Value = context.json().await.unwrap(); + assert_eq!(context["effectDigest"], added["effectDigest"]); + let documents = context["context"]["fields"]["otherDocuments"] + .as_array() + .unwrap(); + assert_eq!(documents.len(), 1); + let path = documents[0]["download"]["path"].as_str().unwrap(); + assert!(path.contains("/additions/")); + let downloaded = reqwest::get(format!( + "{}{}&accessProfile=reviewer", + reviewer_http.base_url, path + )) + .await + .unwrap(); + assert_eq!(downloaded.status(), 200); + assert_eq!(downloaded.bytes().await.unwrap(), b"review-file".as_slice()); + let wrong = path.replace("submissionVersion=1", "submissionVersion=2"); + assert_eq!( + reqwest::get(format!( + "{}{}&accessProfile=reviewer", + reviewer_http.base_url, wrong + )) + .await + .unwrap() + .status(), + 404 + ); + let wrong = path.replace( + "reviewContextField=otherDocuments", + "reviewContextField=missing", + ); + assert_eq!( + reqwest::get(format!( + "{}{}&accessProfile=reviewer", + reviewer_http.base_url, wrong + )) + .await + .unwrap() + .status(), + 404 + ); + for digest in [ + context["effectDigest"].as_str().unwrap(), + context["context"]["contract"]["schemaDigest"] + .as_str() + .unwrap(), + ] { + let wrong = path.replace( + &digest.replace(':', "%3A"), + &format!("sha256%3A{}", "f".repeat(64)), + ); + assert_eq!( + reqwest::get(format!( + "{}{}&accessProfile=reviewer", + reviewer_http.base_url, wrong + )) + .await + .unwrap() + .status(), + 404 + ); + } + let hidden = reqwest::get(format!( + "{}/v1/proposals/{}?accessProfile=no-files", + fixture.http.base_url, + submitted.id() + )) + .await + .unwrap(); + assert_eq!(hidden.status(), 200); + assert!(hidden + .json::() + .await + .unwrap() + .get("additions") + .is_none()); + let download = added["additions"]["other"]["items"][0]["links"]["download"]["path"] + .as_str() + .unwrap(); + assert_eq!( + reqwest::get(format!( + "{}{}&accessProfile=no-files", + fixture.http.base_url, download + )) + .await + .unwrap() + .status(), + 404 + ); + let current = client.read_proposal(&submitted).await.unwrap().value; + let revised = client + .execute_proposal( + &client + .prepare_proposal(¤t, "revise", json!({}), &key("review-add-revise")) + .unwrap(), + ) + .await + .unwrap() + .value; + let revised = serde_json::to_value(&revised).unwrap(); + assert_eq!(revised["submissionVersion"], 2); + assert!(revised["additions"]["other"]["items"] + .as_array() + .unwrap() + .is_empty()); + assert_eq!( + reqwest::get(format!( + "{}{}&accessProfile=reviewer", + reviewer_http.base_url, path + )) + .await + .unwrap() + .status(), + 404 + ); + drop(reviewer_http); + fixture.finish().await; +} + +#[tokio::test] +async fn additions_leave_the_frozen_manifest_unchanged_and_apply_still_succeeds() { + let review = std::sync::Arc::new(LocalReview { + calls: 0.into(), + mode: 0.into(), + result_id: uuid::Uuid::new_v4(), + }); + let injected = review.clone(); + let fixture = client_http::ClientFixture::start_with_mutations( + compile(addition_source()), + claims("author", "zone-a"), + move |mutations| { + mutations.with_proposal_review_substitute_for_test(local_review_binding(), injected) + }, + ) + .await; + let client = &fixture.http.client; + let draft = start(&fixture, "Applied", "apply-add-start").await; + let submitted = client + .execute_proposal( + &client + .prepare_proposal(&draft, "submit", json!({}), &key("apply-add-submit")) + .unwrap(), + ) + .await + .unwrap() + .value; + let id = uuid::Uuid::parse_str(submitted.id()).unwrap(); + let snapshot: Value = fixture.database.admin.query_one("SELECT snapshot FROM registry_internal.registry_proposal_submissions WHERE proposal_id=$1", &[&id]).await.unwrap().get(0); + let value = serde_json::to_value(&submitted).unwrap(); + let etag = value["additions"]["other"]["links"]["add"]["ifMatch"] + .as_str() + .unwrap(); + assert_eq!( + add( + &fixture, + submitted.id(), + etag, + "apply-add-one", + "text/plain", + b"support" + ) + .await + .status(), + 200 + ); + let after: Value = fixture.database.admin.query_one("SELECT snapshot FROM registry_internal.registry_proposal_submissions WHERE proposal_id=$1", &[&id]).await.unwrap().get(0); + assert_eq!(after, snapshot); + retain_queue_review( + &fixture, + &submitted, + &review, + registry_review_client::ReviewResultStatus::Approved, + false, + true, + ) + .await; + let current = client.read_proposal(&submitted).await.unwrap().value; + let current_value = serde_json::to_value(¤t).unwrap(); + let closed = current_value["additions"]["other"]["links"]["add"]["ifMatch"] + .as_str() + .unwrap(); + assert_eq!( + add( + &fixture, + current.id(), + closed, + "approved-add", + "text/plain", + b"too late" + ) + .await + .status(), + 412 + ); + let applied = client + .execute_proposal( + &client + .prepare_proposal( + ¤t, + "apply", + json!({"submissionVersion":current.submission_version(), + "effectDigest":current.effect_digest().unwrap()}), + &key("apply-after-addition"), + ) + .unwrap(), + ) + .await + .unwrap() + .value; + assert_eq!(applied.state(), BRegProposalState::Applied); + fixture.finish().await; +} + +#[tokio::test] +async fn additions_emit_a_value_free_event_and_enqueue_the_selected_hook() { + let mut source = addition_source(); + source["actions"]["correct-name"]["execution"]["proposal"]["hooks"] = json!([{"id":"on-add","transitions":["added"], + "handler":{"type":"rhai","script":"hooks/on-add.rhai","abi":"registry.hook-handler/v1"}}]); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + let registry = compile_project_with_assets( + &project, + &[], + &[ModuleAssetSource { + module: None, + path: "hooks/on-add.rhai".into(), + bytes: b"fn handle(ctx) { #{answer: \"none\"} }".to_vec(), + }], + CompileProfile::Authoring, + ) + .unwrap(); + let review = std::sync::Arc::new(LocalReview { + calls: 0.into(), + mode: 0.into(), + result_id: uuid::Uuid::new_v4(), + }); + let fixture = client_http::ClientFixture::start_with_mutations( + registry, + claims("author", "zone-a"), + move |mutations| { + mutations.with_proposal_review_substitute_for_test(local_review_binding(), review) + }, + ) + .await; + let client = &fixture.http.client; + let draft = start(&fixture, "Event", "event-add-start").await; + let submitted = client + .execute_proposal( + &client + .prepare_proposal(&draft, "submit", json!({}), &key("event-add-submit")) + .unwrap(), + ) + .await + .unwrap() + .value; + let value = serde_json::to_value(&submitted).unwrap(); + let etag = value["additions"]["other"]["links"]["add"]["ifMatch"] + .as_str() + .unwrap(); + assert_eq!( + add( + &fixture, + submitted.id(), + etag, + "event-add-one", + "text/plain", + b"addition-private-bytes-canary" + ) + .await + .status(), + 200 + ); + let row = fixture.database.admin.query_one("SELECT payload FROM registry_internal.registry_outbox WHERE event_type='proposal.added'",&[]).await.unwrap(); + let bytes: Vec = row.get(0); + assert!(!String::from_utf8_lossy(&bytes).contains("addition-private-bytes-canary")); + let envelope = registry_platform_hooks::HookEnvelope::from_canonical_bytes( + &bytes, + ®istry_platform_hooks::EnvelopeLimits::default(), + ) + .unwrap(); + assert_eq!(envelope.data["transition"], "added"); + assert_eq!(envelope.data["state"], "submitted"); + assert_eq!(envelope.data["fromState"], "submitted"); + let hooks:i64 = fixture.database.admin.query_one("SELECT count(*) FROM registry_internal.registry_webhook_deliveries d + JOIN registry_internal.registry_outbox e USING (event_id) WHERE e.event_type='proposal.added'",&[]).await.unwrap().get(0); + assert_eq!(hooks, 1); + let audit = serde_json::to_string(&fixture.audit_capture.entries()).unwrap(); + assert!(!audit.contains("addition-private-bytes-canary")); + let row = fixture.database.admin.query_one("SELECT added_by,added_at IS NOT NULL FROM registry_internal.registry_proposal_additions",&[]).await.unwrap(); + assert!(row.get::<_, String>(0).starts_with("hmac-sha256:")); + assert!(row.get::<_, bool>(1)); + fixture.finish().await; +} + +#[tokio::test] +async fn additions_refuse_draft_approved_rejected_cancelled_and_revised_work() { + for state in ["draft", "approved", "rejected", "cancelled", "revised"] { + let source = addition_source(); + let policy = + source["actions"]["correct-name"]["execution"]["proposal"]["review"]["policy"].clone(); + let review = std::sync::Arc::new(LocalReview { + calls: 0.into(), + mode: 0.into(), + result_id: uuid::Uuid::new_v4(), + }); + let injected = review.clone(); + let fixture = client_http::ClientFixture::start_with_mutations( + compile(source), + claims("author", "zone-a"), + move |mutations| { + mutations.with_proposal_review_substitute_for_test(local_review_binding(), injected) + }, + ) + .await; + let client = &fixture.http.client; + let draft = start(&fixture, "Closed", &format!("{state}-add-start")).await; + let mut current = if state == "draft" { + draft + } else { + client + .execute_proposal( + &client + .prepare_proposal( + &draft, + "submit", + json!({}), + &key(&format!("{state}-add-submit")), + ) + .unwrap(), + ) + .await + .unwrap() + .value + }; + match state { + "approved" => { + retain_queue_review( + &fixture, + ¤t, + &review, + registry_review_client::ReviewResultStatus::Approved, + false, + true, + ) + .await + } + "rejected" => inject_review_decision(&fixture, &review, policy, "rejected").await, + "cancelled" | "revised" => { + let operation = if state == "cancelled" { + "cancel" + } else { + "revise" + }; + current = client + .execute_proposal( + &client + .prepare_proposal( + ¤t, + operation, + json!({}), + &key(&format!("{state}-add-close")), + ) + .unwrap(), + ) + .await + .unwrap() + .value; + } + _ => {} + } + let current = client.read_proposal(¤t).await.unwrap().value; + let value = serde_json::to_value(¤t).unwrap(); + let link = &value["additions"]["other"]["links"]["add"]; + assert_eq!(link["availability"]["available"], false, "{state}"); + let refusal = add( + &fixture, + current.id(), + link["ifMatch"].as_str().unwrap(), + &format!("{state}-add-refused"), + "text/plain", + b"closed", + ) + .await; + assert_eq!( + refusal.status(), + if state == "rejected" { 409 } else { 412 }, + "{state}" + ); + if state == "rejected" { + assert_eq!( + refusal.json::().await.unwrap()["code"], + "proposal.rejected" + ); + } + fixture.finish().await; + } +} diff --git a/crates/registry-breg/tests/support/proposal_additions_authority.rs b/crates/registry-breg/tests/support/proposal_additions_authority.rs new file mode 100644 index 0000000000..a8d3447240 --- /dev/null +++ b/crates/registry-breg/tests/support/proposal_additions_authority.rs @@ -0,0 +1,524 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, +}; + +async fn with_source(source: Value) -> client_http::ClientFixture { + let review = Arc::new(LocalReview { + calls: 0.into(), + mode: 0.into(), + result_id: uuid::Uuid::new_v4(), + }); + client_http::ClientFixture::start_with_mutations( + compile(source), + claims("author", "zone-a"), + move |mutations| { + mutations.with_proposal_review_substitute_for_test(local_review_binding(), review) + }, + ) + .await +} + +async fn request(base: &str, profile: &str, id: &str, etag: &str, key: &str) -> reqwest::Response { + reqwest::Client::new() + .post(format!( + "{base}/v1/proposals/{id}/additions/other?accessProfile={profile}" + )) + .header("if-match", etag) + .header("idempotency-key", key) + .header("content-type", "text/plain") + .body("supporting-file") + .send() + .await + .unwrap() +} + +fn etag(proposal: ®istry_breg_client::BRegProposal) -> String { + serde_json::to_value(proposal).unwrap()["additions"]["other"]["links"]["add"]["ifMatch"] + .as_str() + .unwrap() + .to_owned() +} + +async fn count(fixture: &client_http::ClientFixture) -> i64 { + fixture + .database + .admin + .query_one( + "SELECT count(*) FROM registry_internal.registry_proposal_additions", + &[], + ) + .await + .unwrap() + .get(0) +} + +#[tokio::test] +async fn additions_require_add_even_when_the_caller_holds_edit_or_get() { + let mut source = addition_source(); + for (profile, operation) in [("get-and-edit", "edit"), ("get-only", "get")] { + let mut restricted = source["accessProfiles"]["clerk"].clone(); + restricted["default"] = json!(false); + restricted["permissions"]["actions"] = json!([]); + let grant = &mut restricted["permissions"]["proposals"][0]; + grant["operations"] = if operation == "edit" { + json!(["get", "edit"]) + } else { + json!(["get"]) + }; + grant["readableAttachments"] = if operation == "get" { + json!(["other"]) + } else { + json!([]) + }; + grant["writableAttachments"] = json!([]); + source["accessProfiles"][profile] = restricted; + } + let fixture = with_source(source).await; + let proposal = submitted_addition_proposal(&fixture, "operation-grant").await; + for profile in ["get-and-edit", "get-only"] { + let refused = request( + &fixture.http.base_url, + profile, + proposal.id(), + &etag(&proposal), + profile, + ) + .await; + assert_eq!(refused.status(), 404, "{profile}"); + assert_eq!( + refused.json::().await.unwrap()["code"], + "resource.not_found" + ); + } + assert_eq!(count(&fixture).await, 0); + assert_eq!( + add( + &fixture, + proposal.id(), + &etag(&proposal), + "operation-allowed", + "text/plain", + b"allowed" + ) + .await + .status(), + 200 + ); + fixture.finish().await; +} + +#[tokio::test] +async fn additions_refuse_a_non_owner() { + let fixture = fixture().await; + let proposal = submitted_addition_proposal(&fixture, "non-owner").await; + let other = fixture.client_for(claims("other-author", "zone-a")).await; + let refused = request( + &other.base_url, + "clerk", + proposal.id(), + &etag(&proposal), + "non-owner-add", + ) + .await; + assert_eq!(refused.status(), 404); + assert_eq!(count(&fixture).await, 0); + drop(other); + fixture.finish().await; +} + +#[tokio::test] +async fn additions_refuse_an_owner_outside_the_row_boundary() { + let fixture = fixture().await; + let proposal = submitted_addition_proposal(&fixture, "outside-row").await; + let target = + uuid::Uuid::parse_str(proposal.input().unwrap()["target"].as_str().unwrap()).unwrap(); + let entity = &fixture.registry.entities()["target"]; + fixture + .database + .admin + .execute( + &format!( + "UPDATE registry_data.\"{}\" SET \"{}\"=$2 WHERE record_id=$1", + entity.physical_table, entity.fields["jurisdiction"].physical_name + ), + &[&target, &"zone-b"], + ) + .await + .unwrap(); + let refused = request( + &fixture.http.base_url, + "clerk", + proposal.id(), + &etag(&proposal), + "outside-row-add", + ) + .await; + assert_eq!(refused.status(), 412); + assert_eq!(count(&fixture).await, 0); + fixture.finish().await; +} + +#[tokio::test] +async fn additions_refuse_a_standing_agent() { + let fixture = fixture().await; + let proposal = submitted_addition_proposal(&fixture, "standing-agent").await; + let agent = VerifiedRequestClaims::authenticated_with_actor_kind( + "sub", + "author", + BTreeSet::from(["proposal:manage".into()]), + Some("registry-administration".into()), + BTreeMap::from([( + "jurisdiction".into(), + VerifiedClaimValue::direct_string("zone-a").unwrap(), + )]), + registry_platform_oidc::ActorKind::Agent, + ) + .unwrap(); + let agent = fixture.client_for(agent).await; + let refused = request( + &agent.base_url, + "clerk", + proposal.id(), + &etag(&proposal), + "standing-agent-add", + ) + .await; + assert_eq!(refused.status(), 404); + assert_eq!(count(&fixture).await, 0); + drop(agent); + fixture.finish().await; +} + +#[tokio::test] +async fn additions_recheck_a_stale_task_grant_before_writing() { + use registry_breg::auth::{AuthorityClaimConfig, RegistryAuthenticator}; + use registry_breg::task_grant::{TaskGrantBinding, TaskGrantError, TaskGrantStatusChecker}; + use registry_platform_httputil::FetchUrlPolicy; + use registry_platform_oidc::{JwksFetcher, JwksFetcherConfig}; + use registry_platform_testing::{oidc_verifier_config, MockIdp}; + struct Current(Arc); + impl TaskGrantStatusChecker for Current { + fn check<'a>( + &'a self, + _: &'a TaskGrantBinding, + ) -> std::pin::Pin< + Box> + Send + 'a>, + > { + Box::pin(async move { + if self.0.load(Ordering::SeqCst) { + Ok(()) + } else { + Err(TaskGrantError::Refused) + } + }) + } + } + let mut source = addition_source(); + let mut permission = source["accessProfiles"]["clerk"]["permissions"]["proposals"][0].clone(); + permission["operations"] = json!(["get", "add"]); + permission["readableAttachments"] = json!(["other"]); + permission["writableAttachments"] = json!(["other"]); + source["accessProfiles"]["task-adder"] = json!({"actorKind":"agent","requesterClients":["agent-client"], + "principalClaim":"sub","requiredScopes":["proposal:manage"],"requiredPurposes":["registry-administration"], + "taskGrant":{"sourceIssuer":"https://casework.example"},"permissions":{"proposals":[permission]}}); + let registry = compile(source); + let idp = MockIdp::start().await; + let mut verifier = oidc_verifier_config(idp.issuer(), vec!["urn:example:breg".into()]); + verifier.allowed_clients = vec!["agent-client".into()]; + let auth = RegistryAuthenticator::new( + ®istry, + verifier, + Arc::new(JwksFetcher::new_with_fetch_url_policy( + idp.jwks_uri(), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::https_or_loopback(), + )), + AuthorityClaimConfig::new("sub", Some("registry_purpose".into())), + ) + .unwrap(); + let human=auth.authenticate(&idp.mint_token(json!({"aud":"urn:example:breg","sub":"author","azp":"agent-client", + "registry_actor_kind":"human","registry_purpose":"registry-administration","scope":"proposal:manage","jurisdiction":"zone-a"}))).await.unwrap(); + let current = Arc::new(AtomicBool::new(true)); + let check = current.clone(); + let review = Arc::new(LocalReview { + calls: 0.into(), + mode: 0.into(), + result_id: uuid::Uuid::new_v4(), + }); + let fixture = + client_http::ClientFixture::start_with_mutations(registry, human, move |mutations| { + mutations + .with_task_status(Arc::new(Current(check))) + .with_proposal_review_substitute_for_test(local_review_binding(), review) + }) + .await; + let proposal = submitted_addition_proposal(&fixture, "stale-grant").await; + let expiry = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() + + 600; + let caller=auth.authenticate(&idp.mint_token(json!({"aud":"urn:example:breg","sub":"author","azp":"agent-client", + "registry_actor_kind":"agent","registry_purpose":"registry-administration","scope":"proposal:manage", + "registry_grant_id":"00000000-0000-4000-8000-000000000071","registry_approver":"h:approver", + "registry_grant_source_issuer":"https://casework.example","registry_grant_client":"agent-client", + "registry_grant_resource":"urn:example:breg","registry_grant_exp":expiry,"exp":expiry, + "registry_grant_bounds":{"type":"breg","permissions":[{"collection":format!("proposal:{}",proposal.id()),"operations":["get","add"]}]}, + "identity":{"jurisdiction":"zone-a"},"jurisdiction":"zone-b"}))).await.unwrap(); + let agent = fixture.client_for(caller).await; + let contract = agent + .client + .registry_contract(Some("task-adder")) + .await + .unwrap() + .value; + let proposal = agent + .client + .get_proposal( + &contract.select_proposal_get("task-adder").unwrap(), + proposal.id(), + ) + .await + .unwrap() + .value; + let added = agent + .client + .add_proposal_addition( + &proposal, + "other", + "text/plain", + b"allowed", + &key("live-grant-add"), + ) + .await + .unwrap() + .value; + assert_eq!(count(&fixture).await, 1); + current.store(false, Ordering::SeqCst); + let refused = request( + &agent.base_url, + "task-adder", + added.id(), + &etag(&added), + "stale-grant-add", + ) + .await; + assert_eq!(refused.status(), 412); + assert_eq!(count(&fixture).await, 1); + drop(agent); + fixture.finish().await; +} + +#[tokio::test] +async fn additions_refuse_blocked_applied_and_changes_requested_proposals() { + for state in ["blocked", "applied", "changes-requested"] { + let review = Arc::new(LocalReview { + calls: 0.into(), + mode: 0.into(), + result_id: uuid::Uuid::new_v4(), + }); + let injected = review.clone(); + let fixture = client_http::ClientFixture::start_with_mutations( + compile(addition_source()), + claims("author", "zone-a"), + move |mutations| { + mutations.with_proposal_review_substitute_for_test(local_review_binding(), injected) + }, + ) + .await; + let mut proposal = submitted_addition_proposal(&fixture, state).await; + if state == "blocked" { + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_state SET blocked_reason='package-changed'",&[]).await.unwrap(); + } else { + let status = if state == "applied" { + registry_review_client::ReviewResultStatus::Approved + } else { + registry_review_client::ReviewResultStatus::ChangesRequested + }; + retain_queue_review(&fixture, &proposal, &review, status, false, true).await; + proposal = fixture + .http + .client + .read_proposal(&proposal) + .await + .unwrap() + .value; + if state == "applied" { + proposal=fixture.http.client.execute_proposal(&fixture.http.client.prepare_proposal(&proposal,"apply", + json!({"submissionVersion":proposal.submission_version(),"effectDigest":proposal.effect_digest().unwrap()}), + &key("applied-before-add")).unwrap()).await.unwrap().value; + } + } + proposal = fixture + .http + .client + .read_proposal(&proposal) + .await + .unwrap() + .value; + let value = serde_json::to_value(&proposal).unwrap(); + assert_eq!( + value["additions"]["other"]["links"]["add"]["availability"]["available"], false, + "{state}" + ); + assert_eq!( + request( + &fixture.http.base_url, + "clerk", + proposal.id(), + &etag(&proposal), + &format!("{state}-refused") + ) + .await + .status(), + 412, + "{state}" + ); + assert_eq!(count(&fixture).await, 0); + fixture.finish().await; + } +} + +#[tokio::test] +async fn additions_racing_for_the_last_place_commit_exactly_one_file() { + let fixture = fixture().await; + let proposal = submitted_addition_proposal(&fixture, "last-place").await; + let proposal = fixture + .http + .client + .add_proposal_addition( + &proposal, + "other", + "text/plain", + b"first", + &key("last-place-first"), + ) + .await + .unwrap() + .value; + let condition = etag(&proposal); + let (left, right) = tokio::join!( + add( + &fixture, + proposal.id(), + &condition, + "last-place-left", + "text/plain", + b"left" + ), + add( + &fixture, + proposal.id(), + &condition, + "last-place-right", + "text/plain", + b"right" + ) + ); + let mut success = 0; + for response in [left, right] { + match response.status().as_u16() { + 200 => success += 1, + 412 => {} + 409 => assert_eq!( + response.json::().await.unwrap()["code"], + "attachment.limit-reached" + ), + status => panic!("unexpected addition race status {status}"), + } + } + assert_eq!(success, 1); + assert_eq!(count(&fixture).await, 2); + fixture.finish().await; +} + +#[tokio::test] +async fn additions_reviewer_cannot_download_a_file_missing_from_the_live_context() { + let mut source = addition_source(); + source["actions"]["correct-name"]["execution"]["proposal"]["reviewContext"] = json!({"id":"supporting-review", + "fields":{"otherDocuments":{"type":"additions","slot":"other"}}}); + let mut reviewer = source["accessProfiles"]["clerk"].clone(); + reviewer["default"] = json!(false); + reviewer["permissions"]["actions"] = json!([]); + reviewer["permissions"]["records"] = json!([]); + let grant = &mut reviewer["permissions"]["proposals"][0]; + grant["operations"] = json!(["get-review-context"]); + grant.as_object_mut().unwrap().remove("ownership"); + grant["readableInputs"] = json!([]); + grant["readableAttachments"] = json!([]); + grant["writableAttachments"] = json!([]); + grant["readableContextFields"] = json!(["otherDocuments"]); + source["accessProfiles"]["reviewer"] = reviewer; + let fixture = with_source(source).await; + let first = submitted_addition_proposal(&fixture, "context-first").await; + let first = fixture + .http + .client + .add_proposal_addition( + &first, + "other", + "text/plain", + b"first", + &key("context-first-add"), + ) + .await + .unwrap() + .value; + let second = submitted_addition_proposal(&fixture, "context-second").await; + let second = fixture + .http + .client + .add_proposal_addition( + &second, + "other", + "text/plain", + b"second", + &key("context-second-add"), + ) + .await + .unwrap() + .value; + let other_file = second.addition_slot("other").unwrap().items()[0].id(); + assert_eq!( + fixture + .http + .client + .download_proposal_addition(&second, other_file) + .await + .unwrap() + .value + .as_bytes(), + b"second" + ); + let reviewer = fixture.client_for(claims("reviewer", "zone-a")).await; + let context: Value = reqwest::get(format!( + "{}/v1/proposals/{}/review-context?accessProfile=reviewer", + reviewer.base_url, + first.id() + )) + .await + .unwrap() + .json() + .await + .unwrap(); + let documents = context["context"]["fields"]["otherDocuments"] + .as_array() + .unwrap(); + assert_eq!(documents.len(), 1); + let path = documents[0]["download"]["path"].as_str().unwrap(); + let first_file = first.addition_slot("other").unwrap().items()[0].id(); + assert!(!path.contains(other_file)); + let forged = path.replace(first_file, other_file); + let refused = reqwest::get(format!( + "{}{forged}&accessProfile=reviewer", + reviewer.base_url + )) + .await + .unwrap(); + assert_eq!(refused.status(), 404); + drop(reviewer); + fixture.finish().await; +} diff --git a/crates/registry-breg/tests/support/proposal_final.rs b/crates/registry-breg/tests/support/proposal_final.rs new file mode 100644 index 0000000000..59246d0d34 --- /dev/null +++ b/crates/registry-breg/tests/support/proposal_final.rs @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; + +#[tokio::test] +async fn concealed_or_deleted_apply_targets_create_no_block_or_revision() { + for deleted in [false, true] { + let fixture = + client_http::ClientFixture::start(registry(false), claims("author", "zone-a")).await; + let client = &fixture.http.client; + let draft = start(&fixture, "After", "hidden-target").await; + let submitted = client + .execute_proposal( + &client + .prepare_proposal(&draft, "submit", json!({}), &key("hidden-submit")) + .unwrap(), + ) + .await + .unwrap() + .value; + let target = + uuid::Uuid::parse_str(submitted.input().unwrap()["target"].as_str().unwrap()).unwrap(); + let entity = &fixture.registry.entities()["target"]; + let sql = if deleted { + format!( + "DELETE FROM registry_data.\"{}\" WHERE record_id=$1", + entity.physical_table + ) + } else { + format!( + "UPDATE registry_data.\"{}\" SET \"{}\"='zone-b' WHERE record_id=$1", + entity.physical_table, entity.fields["jurisdiction"].physical_name + ) + }; + fixture + .database + .admin + .execute(&sql, &[&target]) + .await + .unwrap(); + let refused = client.execute_proposal(&client.prepare_proposal(&submitted, "apply", json!({"submissionVersion":submitted.submission_version(),"effectDigest":submitted.effect_digest().unwrap()}), &key("hidden-apply")).unwrap()).await.unwrap_err(); + assert_eq!( + refused.problem_code(), + Some(BRegProblemCode::PreconditionFailed) + ); + assert_eq!( + client + .read_proposal(&submitted) + .await + .unwrap_err() + .problem_code(), + Some(BRegProblemCode::ResourceNotFound) + ); + let revision: i64 = fixture + .database + .admin + .query_one( + "SELECT workflow_revision FROM registry_internal.registry_proposal_state", + &[], + ) + .await + .unwrap() + .get(0); + assert_eq!(revision as u64, submitted.revision()); + let blocks: i64 = fixture.database.admin.query_one("SELECT count(*) FROM registry_internal.registry_proposal_state WHERE blocked_reason IS NOT NULL", &[]).await.unwrap().get(0); + assert_eq!(blocks, 0, "deleted={deleted}"); + fixture.finish().await; + } +} diff --git a/crates/registry-breg/tests/support/proposal_hooks_model.rs b/crates/registry-breg/tests/support/proposal_hooks_model.rs index b588ea331e..6317b7bb2d 100644 --- a/crates/registry-breg/tests/support/proposal_hooks_model.rs +++ b/crates/registry-breg/tests/support/proposal_hooks_model.rs @@ -19,7 +19,7 @@ pub fn source(hooks: Value) -> Value { "records":[{"recordType":"target","operations":["create","get"],"readableFields":["name"],"writableFields":["name"],"rowBoundaries":"unrestricted"}], "actions":[{"action":"correct-name","operations":["start"],"targets":[{"recordType":"target","rowBoundaries":"unrestricted"}]}], "proposals":[{"action":"correct-name","operations":["get","edit","submit","cancel","apply"],"ownership":"caller", - "readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target","rowBoundaries":"unrestricted"}]}]}}}}) + "readableInputs":["target","value"],"readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target","rowBoundaries":"unrestricted"}]}]}}}}) } pub fn url_hook() -> Value { diff --git a/crates/registry-breg/tests/support/proposal_required_attachment.rs b/crates/registry-breg/tests/support/proposal_required_attachment.rs new file mode 100644 index 0000000000..51fd37cfb4 --- /dev/null +++ b/crates/registry-breg/tests/support/proposal_required_attachment.rs @@ -0,0 +1,537 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; + +async fn required_slot(readable: bool) { + let mut source = registry_source(false); + source["actions"]["correct-name"]["execution"]["proposal"]["attachments"][0]["required"] = + json!(true); + if !readable { + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableAttachments"] = + json!([]); + } + let registry = if readable { + registry_breg::compiler::compile_project( + ®istry_breg::contract::parse_project_yaml(include_bytes!( + "../../../../products/breg/examples/required-attachment/registry.yaml" + )) + .unwrap(), + &[], + CompileProfile::Authoring, + ) + .unwrap() + } else { + compile(source) + }; + let fixture = client_http::ClientFixture::start(registry, claims("author", "zone-a")).await; + let draft = start(&fixture, "Required file", "required-file-start").await; + let value = serde_json::to_value(&draft).unwrap(); + let response = reqwest::Client::new() + .post(format!( + "{}/v1/proposals/{}/submit?accessProfile=clerk", + fixture.http.base_url, + draft.id() + )) + .header( + "if-match", + value["links"]["submit"]["ifMatch"].as_str().unwrap(), + ) + .header("idempotency-key", "required-file-missing") + .json(&json!({})) + .send() + .await + .unwrap(); + let status = response.status(); + let problem: Value = response.json().await.unwrap(); + assert_eq!(status, 422, "missing required file: {problem}"); + assert_eq!(problem["code"], "attachment.required"); + assert_eq!(problem["fieldPath"], "/attachments/support"); + assert_eq!(value["links"]["submit"]["availability"]["available"], false); + assert_eq!( + value["links"]["submit"]["availability"]["reason"], + "attachment-required" + ); + assert_eq!( + value["links"]["submit"]["availability"]["recovery"], + "correct-input" + ); + let uploaded = fixture + .http + .client + .upload_proposal_attachment( + &draft, + "support", + "text/plain", + b"required support", + &key("required-file-upload"), + ) + .await + .unwrap() + .value; + let current = fixture + .http + .client + .read_proposal(&uploaded) + .await + .unwrap() + .value; + let value = serde_json::to_value(¤t).unwrap(); + assert_eq!(value["links"]["submit"]["availability"]["available"], true); + assert_eq!( + value["attachments"]["support"].get("value").is_some(), + readable + ); + let client = &fixture.http.client; + let submitted = client + .execute_proposal( + &client + .prepare_proposal(¤t, "submit", json!({}), &key("required-file-submit")) + .unwrap(), + ) + .await + .unwrap() + .value; + assert_eq!(submitted.state(), BRegProposalState::Submitted); + fixture.finish().await; +} + +#[tokio::test] +async fn submit_names_an_empty_required_attachment_and_recovers_after_upload() { + required_slot(true).await; +} + +#[tokio::test] +async fn submit_checks_required_attachments_the_writer_cannot_read() { + required_slot(false).await; +} + +async fn verified_slot(required: bool, verdict: &str, readable: bool) { + use registry_breg::attachment_verification::AttachmentVerification; + use registry_platform_config::{AttachmentVerifierConfig, SecretProvider, SecretResolver}; + use registry_platform_objectstore::{HttpVerifierSettings, VerifierNamespace}; + let secrets = tempfile::tempdir().unwrap(); + let credential = secrets.path().join("verifier"); + std::fs::write(&credential, b"synthetic-verifier-token").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&credential, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + let resolver = SecretResolver::new([SecretProvider::File], secrets.path()).unwrap(); + let config: AttachmentVerifierConfig = serde_json::from_value(json!({ + "url":"http://127.0.0.1:1/verify","policyId":"synthetic-policy", + "authorizationRef":"secret:file/verifier","attemptTimeoutMilliseconds":2000 + })) + .unwrap(); + let verification = AttachmentVerification::Http(std::sync::Arc::new( + HttpVerifierSettings::from_config(&config) + .unwrap() + .activate( + VerifierNamespace { + binding_domain: "breg-attachment-verification-http-v1", + max_content_bytes: registry_breg::contract::MAX_ATTACHMENT_BYTES as u64, + }, + &resolver, + ) + .unwrap(), + )); + let policy = verification.binding_digest(); + let mut source = registry_source(false); + source["actions"]["correct-name"]["execution"]["proposal"]["attachments"][0]["required"] = + json!(required); + if !readable { + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableAttachments"] = + json!([]); + } + let fixture = client_http::ClientFixture::start_with_mutations( + compile(source), + claims("author", "zone-a"), + move |mutations| mutations.with_attachment_verification(verification), + ) + .await; + let draft = start(&fixture, "Verification", "verification-start").await; + let uploaded = fixture + .http + .client + .upload_proposal_attachment( + &draft, + "support", + "text/plain", + b"synthetic supporting file", + &key("verification-upload"), + ) + .await + .unwrap() + .value; + if verdict != "pending" { + fixture.database.admin.execute( + "INSERT INTO registry_internal.registry_attachment_verification (sha256,policy_digest,content_type,verdict) + SELECT sha256,$1,content_type,$2 FROM registry_internal.registry_proposal_attachments WHERE slot_id='support' + ON CONFLICT (sha256,policy_digest,content_type) DO UPDATE SET verdict=EXCLUDED.verdict", + &[&policy,&verdict]).await.unwrap(); + } + let current = reqwest::get(format!( + "{}/v1/proposals/{}?accessProfile=clerk", + fixture.http.base_url, + uploaded.id() + )) + .await + .unwrap(); + let etag = current.headers()["etag"].to_str().unwrap().to_owned(); + let current: Value = current.json().await.unwrap(); + let response = reqwest::Client::new() + .post(format!( + "{}/v1/proposals/{}/submit?accessProfile=clerk", + fixture.http.base_url, + uploaded.id() + )) + .header("if-match", etag) + .header("idempotency-key", "verification-submit") + .json(&json!({})) + .send() + .await + .unwrap(); + let status = response.status(); + let problem: Value = response.json().await.unwrap(); + let (expected_status, code, reason, recovery) = match (required, verdict) { + (_, "pending") => ( + 409, + "attachment.verification-pending", + "attachment-pending", + "refresh", + ), + (true, "rejected") => ( + 422, + "attachment.required", + "attachment-required", + "correct-input", + ), + (false, "rejected") => ( + 422, + "attachment.verification-rejected", + "invalid-input", + "correct-input", + ), + _ => unreachable!(), + }; + assert_eq!( + current["links"]["submit"]["availability"], + json!({ + "available":false,"observedRevision":current["revision"],"reason":reason,"recovery":recovery + }) + ); + assert_eq!(status, expected_status, "{problem}"); + assert_eq!(problem["code"], code); + assert_eq!(problem["fieldPath"], "/attachments/support"); + assert_eq!( + problem + .as_object() + .unwrap() + .keys() + .cloned() + .collect::>(), + BTreeSet::from( + [ + "type", + "title", + "status", + "detail", + "code", + "traceId", + "fieldPath" + ] + .map(str::to_owned) + ) + ); + if !readable { + assert!(current["attachments"]["support"].get("value").is_none()); + } + let client = &fixture.http.client; + let ready = if verdict == "rejected" && !required { + client + .delete_proposal_attachment(&uploaded, "support", &key("verification-remove")) + .await + .unwrap() + .value + } else { + let current = if verdict == "rejected" { + client + .upload_proposal_attachment( + &uploaded, + "support", + "text/plain", + b"replacement supporting file", + &key("verification-replace"), + ) + .await + .unwrap() + .value + } else { + uploaded + }; + // Model the verifier completing its verdict, without a network poll or clock delay. + fixture.database.admin.execute( + "UPDATE registry_internal.registry_attachment_verification SET verdict='approved' WHERE verdict='pending'", + &[], + ).await.unwrap(); + client.read_proposal(¤t).await.unwrap().value + }; + assert!( + ready + .link("submit") + .unwrap() + .availability() + .unwrap() + .available + ); + let submitted = client + .execute_proposal( + &client + .prepare_proposal(&ready, "submit", json!({}), &key("verification-submit")) + .unwrap(), + ) + .await + .unwrap() + .value; + assert_eq!(submitted.state(), BRegProposalState::Submitted); + // A later verification observation cannot reopen the Submit lifecycle command. + fixture + .database + .admin + .execute( + "UPDATE registry_internal.registry_attachment_verification SET verdict='pending'", + &[], + ) + .await + .unwrap(); + let current = client.read_proposal(&submitted).await.unwrap().value; + let current = serde_json::to_value(¤t).unwrap(); + let wrong_state = reqwest::Client::new() + .post(format!( + "{}/v1/proposals/{}/submit?accessProfile=clerk", + fixture.http.base_url, + submitted.id() + )) + .header( + "if-match", + current["links"]["submit"]["ifMatch"].as_str().unwrap(), + ) + .header("idempotency-key", "verification-submit-again") + .json(&json!({})) + .send() + .await + .unwrap(); + assert_eq!(wrong_state.status(), 412); + fixture.finish().await; +} + +#[tokio::test] +async fn submit_and_link_agree_for_pending_verification() { + for readable in [true, false] { + verified_slot(true, "pending", readable).await; + } +} + +#[tokio::test] +async fn submit_and_link_treat_a_rejected_required_file_as_empty() { + for readable in [true, false] { + verified_slot(true, "rejected", readable).await; + } +} + +#[tokio::test] +async fn submit_and_link_name_a_rejected_optional_file_without_metadata() { + for readable in [true, false] { + verified_slot(false, "rejected", readable).await; + } +} + +#[tokio::test] +async fn required_file_precedes_plan_evaluation() { + let mut source = registry_source(false); + source["actions"]["correct-name"]["execution"]["proposal"]["attachments"][0]["required"] = + json!(true); + source["functions"] = json!({"failing-plan":{"runtime":"rhai","source":"plans/failing.rhai","entrypoint":"plan","abi":"registry.action-plan/v1"}}); + source["actions"]["correct-name"]["plan"] = json!({"type":"function","function":"failing-plan","inputs":["target","value"], + "writes":[{"id":"name","target":{"fromInput":"target"},"operation":"patch","fields":["name"]}]}); + let registry = compile_project_with_assets( + &parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(), + &[], + &[ModuleAssetSource { + module: None, + path: "plans/failing.rhai".into(), + bytes: br#"fn plan(ctx) { throw "synthetic plan failure"; }"#.to_vec(), + }], + CompileProfile::Authoring, + ) + .unwrap(); + let fixture = client_http::ClientFixture::start(registry, claims("author", "zone-a")).await; + let draft = start(&fixture, "Required before plan", "precedence-start").await; + let value = serde_json::to_value(&draft).unwrap(); + let response = reqwest::Client::new() + .post(format!( + "{}/v1/proposals/{}/submit?accessProfile=clerk", + fixture.http.base_url, + draft.id() + )) + .header( + "if-match", + value["links"]["submit"]["ifMatch"].as_str().unwrap(), + ) + .header("idempotency-key", "precedence-submit") + .json(&json!({})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 422); + assert_eq!( + response.json::().await.unwrap()["code"], + "attachment.required" + ); + fixture.finish().await; +} + +#[tokio::test] +async fn submit_without_slot_write_authority_names_the_first_empty_slot_only() { + let mut source = registry_source(false); + let mut alpha = + source["actions"]["correct-name"]["execution"]["proposal"]["attachments"][0].clone(); + alpha["required"] = json!(true); + alpha["id"] = json!("zeta"); + source["actions"]["correct-name"]["execution"]["proposal"]["attachments"] + .as_array_mut() + .unwrap() + .push(alpha.clone()); + alpha["id"] = json!("alpha"); + source["actions"]["correct-name"]["execution"]["proposal"]["attachments"] + .as_array_mut() + .unwrap() + .push(alpha); + let grant = &mut source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]; + grant["readableAttachments"] = json!([]); + grant["writableAttachments"] = json!([]); + let fixture = + client_http::ClientFixture::start(compile(source), claims("author", "zone-a")).await; + let draft = start(&fixture, "Split responsibilities", "split-start").await; + let value = serde_json::to_value(&draft).unwrap(); + assert!(value.get("attachments").is_none()); + let response = reqwest::Client::new() + .post(format!( + "{}/v1/proposals/{}/submit?accessProfile=clerk", + fixture.http.base_url, + draft.id() + )) + .header( + "if-match", + value["links"]["submit"]["ifMatch"].as_str().unwrap(), + ) + .header("idempotency-key", "split-submit") + .json(&json!({})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 422); + let problem: Value = response.json().await.unwrap(); + assert_eq!(problem["fieldPath"], "/attachments/alpha"); + assert!(problem.get("fieldPaths").is_none()); + assert!(!problem.to_string().contains("zeta")); + fixture.finish().await; +} + +#[tokio::test] +async fn slot_upload_names_media_and_size_refusals() { + let fixture = + client_http::ClientFixture::start(registry(false), claims("author", "zone-a")).await; + let draft = start(&fixture, "Upload refusals", "upload-refusal-start").await; + let value = serde_json::to_value(&draft).unwrap(); + for (content_type, bytes, status, code) in [ + ( + "application/pdf", + b"file".to_vec(), + 415, + "attachment.content-type", + ), + ("text/plain", vec![b'x'; 4097], 413, "attachment.too-large"), + ] { + let response = reqwest::Client::new() + .patch(format!( + "{}/v1/proposals/{}/attachments/support?accessProfile=clerk", + fixture.http.base_url, + draft.id() + )) + .header( + "if-match", + value["links"]["edit"]["ifMatch"].as_str().unwrap(), + ) + .header("idempotency-key", format!("upload-refusal-{status}")) + .header("content-type", content_type) + .body(bytes) + .send() + .await + .unwrap(); + assert_eq!(response.status(), status); + assert_eq!(response.json::().await.unwrap()["code"], code); + } + fixture.finish().await; +} + +#[tokio::test] +async fn a_retired_slot_reference_refuses_submit_without_concealing_the_proposal() { + let fixture = + client_http::ClientFixture::start(registry(false), claims("author", "zone-a")).await; + let draft = start(&fixture, "Retired slot", "retired-slot-start").await; + let uploaded = fixture + .http + .client + .upload_proposal_attachment( + &draft, + "support", + "text/plain", + b"support", + &key("retired-slot-upload"), + ) + .await + .unwrap() + .value; + // Model a reference retained from a removed slot; current grants cannot name it. + fixture.database.admin.execute( + "INSERT INTO registry_internal.registry_proposal_attachments + (action_id,proposal_id,submission_version,slot_id,sha256,content_type,byte_size,uploaded_at,uploaded_by) + SELECT action_id,proposal_id,submission_version,'retired-slot',sha256,content_type,byte_size,uploaded_at,uploaded_by + FROM registry_internal.registry_proposal_attachments WHERE slot_id='support'", + &[], + ).await.unwrap(); + let response = reqwest::get(format!( + "{}/v1/proposals/{}?accessProfile=clerk", + fixture.http.base_url, + uploaded.id() + )) + .await + .unwrap(); + assert_eq!(response.status(), 200); + let current: Value = response.json().await.unwrap(); + assert_eq!( + current["links"]["submit"]["availability"]["available"], + false + ); + assert!(!current.to_string().contains("retired-slot")); + let refused = reqwest::Client::new() + .post(format!( + "{}/v1/proposals/{}/submit?accessProfile=clerk", + fixture.http.base_url, + uploaded.id() + )) + .header( + "if-match", + current["links"]["submit"]["ifMatch"].as_str().unwrap(), + ) + .header("idempotency-key", "retired-slot-submit") + .json(&json!({})) + .send() + .await + .unwrap(); + assert_eq!(refused.status(), 412); + let problem: Value = refused.json().await.unwrap(); + assert_eq!(problem["code"], "precondition.failed"); + assert!(problem.get("fieldPath").is_none()); + fixture.finish().await; +} diff --git a/crates/registry-breg/tests/support/proposal_review_asks.rs b/crates/registry-breg/tests/support/proposal_review_asks.rs new file mode 100644 index 0000000000..3fd17e9285 --- /dev/null +++ b/crates/registry-breg/tests/support/proposal_review_asks.rs @@ -0,0 +1,2494 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; +#[path = "proposal_review_asks_final.rs"] +mod final_review; + +#[tokio::test] +async fn storage_installs_the_ask_mirror_answers_and_feed_checkpoint() { + let authority = Authority::start(false, true).await; + let fixture = fixture(&authority).await; + for table in [ + "registry_proposal_review_asks", + "registry_proposal_review_ask_answers", + "registry_proposal_review_ask_feed_events", + "registry_proposal_review_ask_feed_checkpoints", + "registry_proposal_review_ask_announcements", + ] { + let name = format!("registry_internal.{table}"); + let found: Option = fixture + .database + .admin + .query_one("SELECT to_regclass($1)::text", &[&name]) + .await + .unwrap() + .get(0); + assert!(found.is_some(), "missing ask storage: {table}"); + } + fixture.finish().await; +} + +#[derive(Default)] +pub(super) struct FeedState { + feed_unavailable: bool, + gone_once: bool, + pause_answer: bool, + answer_status: u16, + answer_code: Option, + reads: Vec, + deliveries: Vec<(String, Value)>, + entries: Vec, + replies: BTreeMap, + feed_cursors: Vec>, +} + +pub(super) async fn feed( + State(state): State>, + axum::extract::Query(query): axum::extract::Query>, + headers: HeaderMap, +) -> Response { + assert_eq!(headers["authorization"], format!("Bearer {OUTGOING_TOKEN}")); + assert_eq!(headers["registry-review-profile"], "producer"); + let cursor = query.get("cursor").map(|id| Uuid::parse_str(id).unwrap()); + let mut asks = state.asks.lock().unwrap(); + asks.feed_cursors.push(cursor); + if asks.feed_unavailable { + return response(StatusCode::SERVICE_UNAVAILABLE, json!({})); + } + if cursor.is_some() && std::mem::take(&mut asks.gone_once) { + return (StatusCode::GONE,[("content-type","application/problem+json"),("traceparent",TRACE)],serde_json::to_vec(&json!({"type":"https://review.example.test/problems/cursor.expired","title":"Cursor expired","status":410,"detail":"Refresh the feed","code":"cursor.expired","traceId":"0123456789abcdef0123456789abcdef"})).unwrap()).into_response(); + } + let start = cursor + .and_then(|cursor| { + asks.entries + .iter() + .position(|item| item["eventId"] == cursor.to_string()) + .map(|index| index + 1) + }) + .unwrap_or(0); + let items = &asks.entries[start..]; + response(StatusCode::OK, json!({"items":items})) +} + +pub(super) async fn read( + State(state): State>, + AxumPath((_request, ask)): AxumPath<(Uuid, Uuid)>, + headers: HeaderMap, +) -> Response { + assert_eq!(headers["authorization"], format!("Bearer {OUTGOING_TOKEN}")); + assert_eq!(headers["registry-review-profile"], "producer"); + let mut asks = state.asks.lock().unwrap(); + asks.reads.push(ask); + let (status, body) = asks.replies.get(&ask).unwrap(); + response(*status, body.clone()) +} + +fn announce(authority: &Authority, binding: &ReviewRequestAccepted) -> (Uuid, Uuid) { + let ask = Uuid::new_v4(); + let event = Uuid::new_v4(); + let now = chrono::Utc::now(); + let mut state = authority.state.asks.lock().unwrap(); + state + .entries + .push(json!({"eventId":event,"requestId":binding.request_id,"askId":ask,"changedAt":now})); + state.replies.insert(ask,(StatusCode::OK,json!({"askId":ask,"requestId":binding.request_id,"subject":binding.subject,"text":"Synthetic question, never in events","wants":[{"kind":"answer"}],"askedAt":now,"state":"open"}))); + (ask, event) +} + +#[tokio::test] +async fn fix_announcement_before_acceptance_is_recovered_after_binding_without_another_event() { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "parked-ask").await; + let binding = retained_binding(&fixture, id).await; + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_submissions SET state='uncertain',next_attempt_at=transaction_timestamp()+interval '1 hour' WHERE proposal_id=$1",&[&id]).await.unwrap(); + let (ask, _) = announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + accept(&fixture, id, &binding).await; + worker(&fixture, &authority).await.unwrap(); + let document = read_applicant(&fixture, &format!("/v1/proposals/{id}")).await; + assert_eq!(document["asks"][0]["id"], ask.to_string()); + assert_eq!(document["status"], "awaiting-party"); + fixture.finish().await; +} + +#[tokio::test] +async fn parked_announcements_expire_without_retaining_question_text_or_extending_the_deadline() { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "parked-expiry").await; + let binding = retained_binding(&fixture, id).await; + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_submissions SET state='uncertain',next_attempt_at=transaction_timestamp()+interval '1 hour' WHERE proposal_id=$1",&[&id]).await.unwrap(); + let (_, event) = announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + let row=fixture.database.admin.query_one("SELECT announcement,expires_at<=(SELECT recovery_deadline FROM registry_internal.registry_proposal_review_submissions WHERE proposal_id=$1) FROM registry_internal.registry_proposal_review_ask_announcements",&[&id]).await.unwrap(); + let announcement: Value = row.get(0); + assert_eq!(announcement.as_object().unwrap().len(), 4); + assert!(!announcement.to_string().contains("Synthetic question")); + assert!(row.get::<_, bool>(1)); + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_ask_announcements SET expires_at=transaction_timestamp()-interval '1 second'",&[]).await.unwrap(); + authority.state.asks.lock().unwrap().feed_unavailable = true; + assert!(worker(&fixture, &authority).await.is_err()); + assert_eq!( + fixture + .database + .admin + .query_one( + "SELECT count(*) FROM registry_internal.registry_proposal_review_ask_announcements", + &[] + ) + .await + .unwrap() + .get::<_, i64>(0), + 0 + ); + let row=fixture.database.admin.query_one("SELECT state,error_code FROM registry_internal.registry_proposal_review_ask_feed_events WHERE event_id=$1",&[&event]).await.unwrap(); + assert_eq!(row.get::<_, String>(0), "unknown"); + assert_eq!(row.get::<_, String>(1), "ask-request-unknown"); + authority.state.asks.lock().unwrap().feed_unavailable = false; + tokio::time::sleep(Duration::from_millis(1100)).await; + accept(&fixture, id, &binding).await; + worker(&fixture, &authority).await.unwrap(); + assert!(read_raw(&fixture, &format!("/v1/proposals/{id}")) + .await + .get("asks") + .is_none()); + fixture.finish().await; +} + +#[tokio::test] +async fn fix_ask_read_credentials_back_off_without_committing_the_page() { + for code in [StatusCode::UNAUTHORIZED, StatusCode::FORBIDDEN] { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "ask-auth-outage").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (ask, _) = announce(&authority, &binding); + let good = authority.state.asks.lock().unwrap().replies[&ask].clone(); + authority + .state + .asks + .lock() + .unwrap() + .replies + .insert(ask, (code, json!({}))); + assert!( + worker(&fixture, &authority).await.is_err(), + "credential failure is recoverable" + ); + assert_eq!(fixture.database.admin.query_one("SELECT count(*) FROM registry_internal.registry_proposal_review_ask_feed_events",&[]).await.unwrap().get::<_,i64>(0),0); + let calls = authority.state.asks.lock().unwrap().feed_cursors.len(); + let _ = worker(&fixture, &authority).await; + assert_eq!( + authority.state.asks.lock().unwrap().feed_cursors.len(), + calls, + "backoff suppresses immediate retry" + ); + authority + .state + .asks + .lock() + .unwrap() + .replies + .insert(ask, good); + tokio::time::sleep(Duration::from_millis(1100)).await; + worker(&fixture, &authority).await.unwrap(); + assert_eq!( + read_applicant(&fixture, &format!("/v1/proposals/{id}")).await["asks"][0]["id"], + ask.to_string() + ); + fixture.finish().await; + } +} + +#[tokio::test] +async fn fix_mirror_caps_distinct_asks_and_counts_excess_announcements() { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "ask-cap").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + for _ in 0..51 { + announce(&authority, &binding); + } + worker(&fixture, &authority).await.unwrap(); + assert_eq!( + read_applicant(&fixture, &format!("/v1/proposals/{id}")).await["asks"] + .as_array() + .unwrap() + .len(), + 50 + ); + assert_eq!(fixture.database.admin.query_one("SELECT count(*) FROM registry_internal.registry_proposal_review_ask_feed_events WHERE error_code='ask-limit-reached'",&[]).await.unwrap().get::<_,i64>(0),1); + fixture.finish().await; +} + +#[tokio::test] +async fn fix_duplicate_accepted_request_ids_do_not_stall_the_feed() { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let first = submitted(&fixture, "duplicate-request-a").await; + let second = submitted(&fixture, "duplicate-request-b").await; + let binding = retained_binding(&fixture, first).await; + accept(&fixture, first, &binding).await; + accept(&fixture, second, &binding).await; + announce(&authority, &binding); + assert!( + worker(&fixture, &authority).await.is_ok(), + "ambiguous binding must not stall other announcements" + ); + assert_eq!(fixture.database.admin.query_one("SELECT count(*) FROM registry_internal.registry_proposal_review_ask_feed_events WHERE error_code='ask-request-ambiguous'",&[]).await.unwrap().get::<_,i64>(0),1); + fixture.finish().await; +} + +#[tokio::test] +async fn fix_terminal_ask_feed_changes_the_etag_once_without_reopening() { + for terminal in ["closed", "expired"] { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "ask-terminal").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (ask, _) = announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + let (_, headers, before) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + { + let mut feed = authority.state.asks.lock().unwrap(); + let reply = &mut feed.replies.get_mut(&ask).unwrap().1; + reply["state"] = json!(terminal); + reply["closedAt"] = json!(chrono::Utc::now() + chrono::Duration::hours(2)); + if terminal == "expired" { + reply["dueAt"] = json!(chrono::Utc::now() + chrono::Duration::hours(1)); + } + feed.entries.push(json!({"eventId":Uuid::new_v4(),"requestId":binding.request_id,"askId":ask,"changedAt":chrono::Utc::now()})); + } + worker(&fixture, &authority).await.unwrap(); + let (_, after_headers, after) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + assert_ne!(headers["etag"], after_headers["etag"]); + assert_eq!( + after["revision"].as_u64().unwrap(), + before["revision"].as_u64().unwrap() + 1 + ); + assert_eq!(after["asks"][0]["state"], terminal); + { + let mut feed = authority.state.asks.lock().unwrap(); + let reply = &mut feed.replies.get_mut(&ask).unwrap().1; + reply["state"] = json!("open"); + reply.as_object_mut().unwrap().remove("closedAt"); + feed.entries.push(json!({"eventId":Uuid::new_v4(),"requestId":binding.request_id,"askId":ask,"changedAt":chrono::Utc::now()})); + } + worker(&fixture, &authority).await.unwrap(); + let replay = read_applicant(&fixture, &format!("/v1/proposals/{id}")).await; + assert_eq!(replay["revision"], after["revision"]); + assert_eq!(replay["asks"][0]["state"], terminal); + fixture.finish().await; + } +} + +#[tokio::test] +async fn fix_erased_submission_does_not_retain_late_question_text() { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "late-erased-ask").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_submissions SET snapshot=NULL,erased_at=transaction_timestamp() WHERE proposal_id=$1",&[&id]).await.unwrap(); + announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + assert_eq!(fixture.database.admin.query_one("SELECT count(*) FROM registry_internal.registry_proposal_review_asks WHERE proposal_id=$1",&[&id]).await.unwrap().get::<_,i64>(0),0); + fixture.finish().await; +} + +async fn worker( + fixture: &client_http::ClientFixture, + authority: &Authority, +) -> Result { + run_review_authority_once_for_test(&fixture.pool, &authority.registry, &fixture.mutations).await +} + +#[tokio::test] +async fn ask_feed_mirrors_two_questions_once_and_bumps_two_revisions_without_changing_the_submission( +) { + let authority = Authority::start(false, true).await; + let fixture = fixture(&authority).await; + let id = submitted(&fixture, "ask-feed").await; + let before = read_raw(&fixture, &format!("/v1/proposals/{id}")).await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (_, first) = announce(&authority, &binding); + let (_, last) = announce(&authority, &binding); + assert!(worker(&fixture, &authority).await.unwrap()); + let rows = fixture.database.admin.query("SELECT text,state FROM registry_internal.registry_proposal_review_asks WHERE proposal_id=$1",&[&id]).await.unwrap(); + assert_eq!(rows.len(), 2, "the worker must mirror both asks"); + let after = read_raw(&fixture, &format!("/v1/proposals/{id}")).await; + assert_eq!( + after["revision"].as_u64().unwrap(), + before["revision"].as_u64().unwrap() + 2 + ); + assert_eq!(after["submissionVersion"], before["submissionVersion"]); + assert_eq!(after["effectDigest"], before["effectDigest"]); + assert_eq!(after["state"], "submitted"); + let events = fixture.database.admin.query("SELECT event_id,payload FROM registry_internal.registry_outbox WHERE event_type='proposal.asked'",&[]).await.unwrap(); + assert_eq!(events.len(), 2); + assert_ne!(events[0].get::<_, Uuid>(0), events[1].get::<_, Uuid>(0)); + assert!(!format!("{events:?}").contains("Synthetic question")); + worker(&fixture, &authority).await.unwrap(); + let cursor: Uuid = fixture + .database + .admin + .query_one( + "SELECT cursor FROM registry_internal.registry_proposal_review_ask_feed_checkpoints", + &[], + ) + .await + .unwrap() + .get(0); + assert_ne!(first, last); + assert_eq!(cursor, last); + assert_eq!( + read_raw(&fixture, &format!("/v1/proposals/{id}")).await["revision"], + after["revision"] + ); + fixture.finish().await; +} + +#[tokio::test] +async fn ask_feed_skips_unknown_and_bad_bindings_but_transient_reads_leave_the_page_uncommitted() { + let authority = Authority::start(false, true).await; + let fixture = fixture(&authority).await; + let id = submitted(&fixture, "ask-feed-failures").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let mut unknown = binding.clone(); + unknown.request_id = Uuid::new_v4(); + announce(&authority, &unknown); + let (bad, _) = announce(&authority, &binding); + authority + .state + .asks + .lock() + .unwrap() + .replies + .get_mut(&bad) + .unwrap() + .1["subject"]["id"] = json!("other-proposal"); + let (retry, last) = announce(&authority, &binding); + let good = authority.state.asks.lock().unwrap().replies[&retry].clone(); + authority + .state + .asks + .lock() + .unwrap() + .replies + .insert(retry, (StatusCode::TOO_MANY_REQUESTS, json!({}))); + assert!( + worker(&fixture, &authority).await.is_err(), + "429 must stop this page" + ); + let counts=fixture.database.admin.query_one("SELECT (SELECT count(*) FROM registry_internal.registry_proposal_review_ask_feed_events),(SELECT count(*) FROM registry_internal.registry_proposal_review_ask_feed_checkpoints)",&[]).await.unwrap(); + assert_eq!(counts.get::<_, i64>(0), 0); + assert_eq!(counts.get::<_, i64>(1), 0); + authority + .state + .asks + .lock() + .unwrap() + .replies + .insert(retry, good); + tokio::time::sleep(Duration::from_millis(1100)).await; + worker(&fixture, &authority).await.unwrap(); + let states:Vec=fixture.database.admin.query("SELECT state FROM registry_internal.registry_proposal_review_ask_feed_events ORDER BY state",&[]).await.unwrap().iter().map(|r|r.get(0)).collect(); + assert_eq!(states, vec!["mirrored", "refused", "unknown"]); + assert_eq!(fixture.database.admin.query_one("SELECT cursor FROM registry_internal.registry_proposal_review_ask_feed_checkpoints",&[]).await.unwrap().get::<_,Uuid>(0),last); + fixture.finish().await; +} + +#[tokio::test] +async fn ask_feed_turn_uses_the_shared_awaiting_party_rule_and_lists_only_live_unanswered_asks() { + let authority = Authority::start(false, true).await; + let fixture = fixture(&authority).await; + let id = submitted(&fixture, "ask-turn").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (ask, _) = announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + let value = read_raw(&fixture, &format!("/v1/proposals/{id}")).await; + assert_eq!(value["status"], "awaiting-party"); + assert_eq!(value["turn"], "party"); + let page = read_raw(&fixture, "/v1/proposals?turn=party").await; + assert!(page["items"] + .as_array() + .unwrap() + .iter() + .any(|item| item["id"] == id.to_string())); + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_asks SET state='answered',answered_at=transaction_timestamp() WHERE ask_id=$1",&[&ask]).await.unwrap(); + let value = read_raw(&fixture, &format!("/v1/proposals/{id}")).await; + assert_eq!(value["status"], "in-review"); + assert_eq!(value["turn"], "official"); + assert!( + read_raw(&fixture, "/v1/proposals?turn=party").await["items"] + .as_array() + .unwrap() + .is_empty() + ); + fixture.finish().await; +} + +async fn answer_fixture(authority: &Authority) -> client_http::ClientFixture { + answer_fixture_with_verification( + authority, + registry_breg::attachment_verification::AttachmentVerification::Disabled, + ) + .await +} + +async fn answer_fixture_with_verification( + authority: &Authority, + verification: registry_breg::attachment_verification::AttachmentVerification, +) -> client_http::ClientFixture { + let source = answer_source(); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + let registry = compile_project(&project, &[], CompileProfile::Authoring).unwrap(); + let bindings = authority.registry.clone(); + client_http::ClientFixture::start_with_mutations(registry, claims(), move |service| { + service + .with_review_result_source(bindings) + .with_attachment_verification(verification) + }) + .await +} + +fn answer_source() -> Value { + let mut source = registry_source(json!(policy())); + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["operations"] + .as_array_mut() + .unwrap() + .push(json!("answer")); + source["actions"]["correct-name"]["execution"]["proposal"]["reviewContext"] = + json!({"id":"ask-context","fields":{"value":{"type":"input","input":"value"}}}); + source["actions"]["correct-name"]["execution"]["proposal"]["additions"] = json!({"id":"other","maximumBytes":1024,"maximumCount":8,"contentTypes":["text/plain"],"classification":"internal"}); + let grant = &mut source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]; + grant["operations"].as_array_mut().unwrap().extend([ + json!("get-review-context"), + json!("add"), + json!("revise"), + json!("rebase"), + ]); + grant["readableContextFields"] = json!(["value"]); + grant["readableAttachments"] = json!(["other"]); + grant["writableAttachments"] = json!(["other"]); + let mut reviewer = source["accessProfiles"]["clerk"].clone(); + reviewer["default"] = json!(false); + reviewer["requiredScopes"] = json!(["proposal:review"]); + let grant = &mut reviewer["permissions"]["proposals"][0]; + grant["operations"] = json!(["get-review-context"]); + grant.as_object_mut().unwrap().remove("ownership"); + grant["readableAttachments"] = json!([]); + grant["writableAttachments"] = json!([]); + source["accessProfiles"]["reviewer"] = reviewer; + let mut writer = source["accessProfiles"]["clerk"].clone(); + writer["default"] = json!(false); + writer["permissions"]["proposals"][0]["operations"] = + json!(["list", "answer", "get-review-status"]); + writer["permissions"]["proposals"][0]["readableContextFields"] = json!([]); + writer["permissions"]["proposals"][0]["readableAttachments"] = json!([]); + writer["permissions"]["proposals"][0]["writableAttachments"] = json!([]); + source["accessProfiles"]["writer"] = writer; + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] = + json!(["target", "value"]); + source +} + +async fn request( + fixture: &client_http::ClientFixture, + method: &str, + path: &str, + etag: Option<&str>, + key: Option<&str>, + body: Value, +) -> (StatusCode, HeaderMap, Value) { + request_as(fixture, applicant(), method, path, etag, key, body).await +} + +/// A read by the applicant, who may answer and so receives its asks. +async fn read_applicant(fixture: &client_http::ClientFixture, path: &str) -> Value { + let (status, _, value) = request(fixture, "GET", path, None, None, Value::Null).await; + assert_eq!(status, StatusCode::OK, "{path}: {value}"); + value +} + +/// The applicant as bearer admission reports a person: the same principal as +/// `claims()`, verified as human, so it may answer and read its asks. +fn applicant() -> VerifiedRequestClaims { + caller_claims("author-canary", registry_platform_oidc::ActorKind::Human) +} + +async fn request_as( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + method: &str, + path: &str, + etag: Option<&str>, + key: Option<&str>, + body: Value, +) -> (StatusCode, HeaderMap, Value) { + use tower::ServiceExt; + let mut req = axum::http::Request::builder() + .method(method) + .uri(path) + .header("content-type", "application/json"); + if let Some(etag) = etag { + req = req.header("if-match", etag); + } + if let Some(key) = key { + req = req.header("idempotency-key", key); + } + let response = registry_breg::api::router(fixture.service()) + .layer(axum::Extension(caller)) + .oneshot( + req.body(if method == "GET" { + axum::body::Body::empty() + } else { + axum::body::Body::from(serde_json::to_vec(&body).unwrap()) + }) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let headers = response.headers().clone(); + let bytes = axum::body::to_bytes(response.into_body(), 1 << 20) + .await + .unwrap(); + let value = if bytes.is_empty() { + Value::Null + } else { + serde_json::from_slice(&bytes).unwrap() + }; + (status, headers, value) +} + +#[tokio::test] +async fn answer_command_commits_once_with_a_new_etag_and_its_own_delivery_deadline() { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "answer-command").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (ask, _) = announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + // An accepted review may be older than the submission recovery deadline. + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_submissions SET recovery_deadline=transaction_timestamp()-interval '1 day' WHERE proposal_id=$1",&[&id]).await.unwrap(); + let (_, before_headers, before) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let etag = before_headers["etag"].to_str().unwrap(); + let path = format!("/v1/proposals/{id}/asks/{ask}/answer"); + let body = json!({"text":"Synthetic answer must stay out of events and audit"}); + let (status, headers, after) = request( + &fixture, + "POST", + &path, + Some(etag), + Some("answer-once"), + body.clone(), + ) + .await; + assert_eq!(status, StatusCode::OK, "{after}"); + assert_eq!(after["state"], "submitted"); + assert_eq!(after["submissionVersion"], before["submissionVersion"]); + assert_eq!(after["effectDigest"], before["effectDigest"]); + assert_ne!(headers["etag"], before_headers["etag"]); + assert_eq!( + after["revision"].as_u64().unwrap(), + before["revision"].as_u64().unwrap() + 1 + ); + assert_eq!(after["status"], "in-review"); + assert_eq!(after["turn"], "official"); + let replay = request( + &fixture, + "POST", + &path, + Some(etag), + Some("answer-once"), + body, + ) + .await; + assert_eq!(replay.0, StatusCode::OK); + assert_eq!(replay.2, after); + assert_eq!(replay.1["etag"], headers["etag"]); + let conflict = request( + &fixture, + "POST", + &path, + Some(etag), + Some("answer-once"), + json!({"text":"Other answer"}), + ) + .await; + assert_eq!(conflict.0, StatusCode::CONFLICT); + assert_eq!(conflict.2["code"], "idempotency.key-reused"); + assert_eq!( + request( + &fixture, + "POST", + &path, + Some(etag), + Some("stale-answer"), + json!({"text":"Other answer"}) + ) + .await + .0, + StatusCode::PRECONDITION_FAILED + ); + let row=fixture.database.admin.query_one("SELECT text,delivery_state,delivery_deadline>transaction_timestamp()+interval '6 days',answered_by IS NOT NULL FROM registry_internal.registry_proposal_review_ask_answers WHERE ask_id=$1",&[&ask]).await.unwrap(); + assert_eq!( + row.get::<_, String>(0), + "Synthetic answer must stay out of events and audit" + ); + assert_eq!(row.get::<_, String>(1), "pending"); + assert!(row.get::<_, bool>(2)); + assert!(row.get::<_, bool>(3)); + let events=fixture.database.admin.query("SELECT payload FROM registry_internal.registry_outbox WHERE event_type='proposal.answered'",&[]).await.unwrap(); + assert_eq!(events.len(), 1); + assert!(!format!("{events:?}").contains("Synthetic answer")); + fixture.finish().await; +} + +pub(super) async fn answer_remote( + State(state): State>, + AxumPath((_request, ask)): AxumPath<(Uuid, Uuid)>, + headers: HeaderMap, + Json(body): Json, +) -> Response { + authenticated(&headers); + assert_eq!( + body.as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect::>(), + vec!["answeredAt", "subject"] + ); + let (status, mut reply, pause) = { + let mut asks = state.asks.lock().unwrap(); + asks.deliveries.push(( + headers["idempotency-key"].to_str().unwrap().into(), + body.clone(), + )); + ( + StatusCode::from_u16(if asks.answer_status == 0 { + 200 + } else { + asks.answer_status + }) + .unwrap(), + asks.replies[&ask].1.clone(), + std::mem::take(&mut asks.pause_answer), + ) + }; + if pause { + state.gates[0].pause().await; + } + if status == StatusCode::NOT_FOUND { + return (status, [("traceparent", TRACE)]).into_response(); + } + if status == StatusCode::OK { + reply["state"] = json!("answered"); + reply["answeredAt"] = body["answeredAt"].clone(); + reply.as_object_mut().unwrap().remove("closedAt"); + return response(status, reply); + } + let code = if let Some(code) = state.asks.lock().unwrap().answer_code.clone() { + code + } else if status == StatusCode::CONFLICT { + "review.ask-not-open".to_owned() + } else { + "review.refused".to_owned() + }; + (status,[("content-type","application/problem+json"),("traceparent",TRACE)],serde_json::to_vec(&json!({"type":format!("https://review.example.test/problems/{code}"),"title":"Refused","status":status.as_u16(),"detail":"Synthetic refusal","code":code,"traceId":"0123456789abcdef0123456789abcdef"})).unwrap()).into_response() +} + +async fn committed_answer( + authority: &Authority, + key: &str, +) -> (client_http::ClientFixture, Uuid, Uuid) { + let fixture = answer_fixture(authority).await; + let id = submitted(&fixture, key).await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + *authority.state.accepted.lock().unwrap() = Some(binding.clone()); + let (ask, _) = announce(authority, &binding); + worker(&fixture, authority).await.unwrap(); + let (_, headers, _) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let answered = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer"), + Some(headers["etag"].to_str().unwrap()), + Some("commit-local-answer"), + json!({"text":"private-answer-not-in-outbound-request"}), + ) + .await; + assert_eq!(answered.0, StatusCode::OK, "{}", answered.2); + (fixture, id, ask) +} +async fn delivery(fixture: &client_http::ClientFixture, ask: Uuid) -> Value { + fixture.database.admin.query_one("SELECT jsonb_build_object('state',delivery_state,'error',last_error_code,'attempts',attempt_count,'answeredAt',answered_at,'deadline',delivery_deadline) FROM registry_internal.registry_proposal_review_ask_answers WHERE ask_id=$1",&[&ask]).await.unwrap().get(0) +} + +#[tokio::test] +async fn cursor_expiry_resets_then_replays_without_duplicating_the_ask_or_revision() { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "ask-cursor-expiry").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + let before = read_applicant(&fixture, &format!("/v1/proposals/{id}")).await; + authority.state.asks.lock().unwrap().gone_once = true; + worker(&fixture, &authority).await.unwrap(); + let cursor: Option = fixture + .database + .admin + .query_one( + "SELECT cursor FROM registry_internal.registry_proposal_review_ask_feed_checkpoints", + &[], + ) + .await + .unwrap() + .get(0); + assert!(cursor.is_none()); + worker(&fixture, &authority).await.unwrap(); + let after = read_applicant(&fixture, &format!("/v1/proposals/{id}")).await; + assert_eq!(after["revision"], before["revision"]); + assert_eq!(after["asks"].as_array().unwrap().len(), 1); + assert!(authority + .state + .asks + .lock() + .unwrap() + .feed_cursors + .last() + .unwrap() + .is_none()); + fixture.finish().await; +} + +#[tokio::test] +async fn a_lost_answer_lease_cannot_settle_the_replacement_claim() { + let authority = Arc::new(Authority::start(false, true).await); + let (fixture, _, ask) = committed_answer(&authority, "answer-lost-lease").await; + authority.state.asks.lock().unwrap().pause_answer = true; + let pool = fixture.pool.clone(); + let registry = authority.registry.clone(); + let mutations = fixture.mutations.clone(); + let in_flight = tokio::spawn(async move { + run_review_authority_once_for_test(&pool, ®istry, &mutations).await + }); + authority.state.gates[0].reached().await; + let replacement = Uuid::new_v4(); + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_ask_answers SET claim_token=$2,lease_until=transaction_timestamp()+interval '1 hour' WHERE ask_id=$1",&[&ask,&replacement]).await.unwrap(); + authority.state.gates[0].release.notify_one(); + in_flight.await.unwrap().unwrap(); + let row=fixture.database.admin.query_one("SELECT delivery_state,claim_token FROM registry_internal.registry_proposal_review_ask_answers WHERE ask_id=$1",&[&ask]).await.unwrap(); + assert_eq!(row.get::<_, String>(0), "pending"); + assert_eq!(row.get::<_, Uuid>(1), replacement); + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_ask_answers SET lease_until=transaction_timestamp()-interval '1 second' WHERE ask_id=$1",&[&ask]).await.unwrap(); + worker(&fixture, &authority).await.unwrap(); + assert_eq!(delivery(&fixture, ask).await["state"], "delivered"); + let calls = authority.state.asks.lock().unwrap().deliveries.clone(); + assert_eq!(calls.len(), 2); + assert_eq!( + calls[0], calls[1], + "a replacement retains the committed delivery key and answer time" + ); + fixture.finish().await; +} + +#[tokio::test] +async fn stored_on_time_answers_deliver_after_remote_expiry_and_an_old_submission_deadline() { + let authority = Authority::start(false, true).await; + let (fixture, id, ask) = committed_answer(&authority, "deliver-answer").await; + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_submissions SET recovery_deadline=transaction_timestamp()-interval '1 day' WHERE proposal_id=$1",&[&id]).await.unwrap(); + let before = delivery(&fixture, ask).await; + { + let mut state = authority.state.asks.lock().unwrap(); + let reply = &mut state.replies.get_mut(&ask).unwrap().1; + let due: chrono::DateTime = + before["answeredAt"].as_str().unwrap().parse().unwrap(); + reply["dueAt"] = json!(due); + reply["closedAt"] = json!(due + chrono::Duration::microseconds(1)); + reply["state"] = json!("expired"); + let request = reply["requestId"].clone(); + state.entries.push(json!({"eventId":Uuid::new_v4(),"requestId":request,"askId":ask,"changedAt":due+chrono::Duration::microseconds(1)})); + } + worker(&fixture, &authority).await.unwrap(); + assert_eq!(delivery(&fixture, ask).await["state"], "delivered"); + { + let state = authority.state.asks.lock().unwrap(); + assert_eq!(state.deliveries.len(), 1); + assert_eq!( + state.deliveries[0].1["answeredAt"] + .as_str() + .unwrap() + .parse::>() + .unwrap(), + before["answeredAt"] + .as_str() + .unwrap() + .parse::>() + .unwrap() + ); + assert!(!state.deliveries[0].1.to_string().contains("private-answer")); + } + fixture.finish().await; +} + +#[tokio::test] +async fn answer_delivery_retries_transient_exchanges_with_the_exact_key_and_stored_time() { + for status in [429, 503, 201] { + let authority = Authority::start(false, true).await; + let (fixture, _, ask) = committed_answer(&authority, "retry-answer").await; + authority.state.asks.lock().unwrap().answer_status = status; + let _ = worker(&fixture, &authority).await; + assert_eq!(delivery(&fixture, ask).await["attempts"], 1); + assert_eq!(delivery(&fixture, ask).await["state"], "pending"); + authority.state.asks.lock().unwrap().answer_status = 200; + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_ask_answers SET next_attempt_at=transaction_timestamp() WHERE ask_id=$1",&[&ask]).await.unwrap(); + worker(&fixture, &authority).await.unwrap(); + assert_eq!(delivery(&fixture, ask).await["state"], "delivered"); + { + let state = authority.state.asks.lock().unwrap(); + assert_eq!(state.deliveries.len(), 2); + assert_eq!(state.deliveries[0], state.deliveries[1]); + } + fixture.finish().await; + } +} + +#[tokio::test] +async fn deterministic_answer_delivery_refusals_keep_the_local_answer_without_retrying() { + for (status, code) in [ + (409, "review.ask-not-open"), + (404, "ask-concealed-or-unknown"), + (422, "review.refused"), + ] { + let authority = Authority::start(false, true).await; + let (fixture, _, ask) = committed_answer(&authority, "refused-answer").await; + authority.state.asks.lock().unwrap().answer_status = status; + worker(&fixture, &authority).await.unwrap(); + let job = delivery(&fixture, ask).await; + assert_eq!(job["state"], "refused"); + assert_eq!(job["error"], code); + assert!(fixture.database.admin.query_one("SELECT text IS NOT NULL FROM registry_internal.registry_proposal_review_ask_answers WHERE ask_id=$1",&[&ask]).await.unwrap().get::<_,bool>(0)); + worker(&fixture, &authority).await.unwrap(); + assert_eq!(authority.state.asks.lock().unwrap().deliveries.len(), 1); + fixture.finish().await; + } +} + +#[tokio::test] +async fn cancelling_a_submission_closes_its_asks_and_supersedes_its_pending_answers() { + let authority = Authority::start(false, true).await; + let (fixture, id, ask) = committed_answer(&authority, "cancel-answer").await; + let (_, headers, _) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let cancelled = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/cancel"), + Some(headers["etag"].to_str().unwrap()), + Some("cancel-with-answer"), + json!({}), + ) + .await; + assert_eq!(cancelled.0, StatusCode::OK, "{}", cancelled.2); + assert_eq!(delivery(&fixture, ask).await["state"], "superseded"); + assert_eq!( + fixture + .database + .admin + .query_one( + "SELECT state FROM registry_internal.registry_proposal_review_asks WHERE ask_id=$1", + &[&ask] + ) + .await + .unwrap() + .get::<_, String>(0), + "closed" + ); + worker(&fixture, &authority).await.unwrap(); + assert!(authority.state.asks.lock().unwrap().deliveries.is_empty()); + fixture.finish().await; +} + +#[tokio::test] +async fn applicant_asks_require_get_even_on_a_command_response_and_report_the_answered_reason() { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "ask-disclosure").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (ask, _) = announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + let (_, _, value) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(value["asks"][0]["id"], ask.to_string()); + assert_eq!( + value["asks"][0]["text"], + "Synthetic question, never in events" + ); + assert_eq!( + value["asks"][0]["links"]["answer"]["availability"]["available"], + true + ); + let (_, _, page) = request( + &fixture, + "GET", + "/v1/proposals?accessProfile=writer", + None, + None, + Value::Null, + ) + .await; + assert!(page["items"][0].get("asks").is_none()); + let (status, headers, status_doc) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}/review-status?accessProfile=writer"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::OK, "{status_doc}"); + let answered = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer?accessProfile=writer"), + Some(headers["etag"].to_str().unwrap()), + Some("answer-as-writer"), + json!({"text":"private command answer"}), + ) + .await; + assert_eq!(answered.0, StatusCode::OK, "{}", answered.2); + assert!(answered.2.get("asks").is_none()); + let (_, _, read) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(read["asks"][0]["state"], "answered"); + assert_eq!(read["asks"][0]["answer"]["text"], "private command answer"); + assert_eq!( + read["asks"][0]["links"]["answer"]["availability"]["reason"], + "ask-answered" + ); + assert_eq!( + read["asks"][0]["links"]["answer"]["availability"]["recovery"], + "receipt-only" + ); + fixture.finish().await; +} + +fn reviewer_claims(jurisdiction: &str) -> VerifiedRequestClaims { + VerifiedRequestClaims::authenticated_with_actor_kind( + "sub", + "reviewer-own-subject", + BTreeSet::from(["proposal:review".into()]), + Some("registry-administration".into()), + BTreeMap::from([( + "jurisdiction".into(), + VerifiedClaimValue::direct_string(jurisdiction).unwrap(), + )]), + registry_platform_oidc::ActorKind::Human, + ) + .unwrap() +} +async fn reviewer_get( + fixture: &client_http::ClientFixture, + path: &str, + jurisdiction: &str, +) -> (StatusCode, HeaderMap, Vec) { + use tower::ServiceExt; + let response = registry_breg::api::router(fixture.service()) + .layer(axum::Extension(reviewer_claims(jurisdiction))) + .oneshot( + axum::http::Request::get(path) + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let headers = response.headers().clone(); + let bytes = axum::body::to_bytes(response.into_body(), 1 << 20) + .await + .unwrap() + .to_vec(); + (status, headers, bytes) +} + +#[tokio::test] +async fn intrinsic_review_context_shows_the_answer_outside_the_authored_fields() { + let authority = Authority::start(false, true).await; + let (fixture, id, ask) = committed_answer(&authority, "review-answer-context").await; + let (status, _, bytes) = reviewer_get( + &fixture, + &format!("/v1/proposals/{id}/review-context?accessProfile=reviewer&include=answers"), + "zone-a", + ) + .await; + assert_eq!( + status, + StatusCode::OK, + "{}", + String::from_utf8_lossy(&bytes) + ); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["context"]["fields"], json!({"value":"After"})); + assert_eq!(value["context"]["asks"][0]["id"], ask.to_string()); + assert_eq!( + value["context"]["asks"][0]["answer"]["text"], + "private-answer-not-in-outbound-request" + ); + assert_eq!( + value["context"]["asks"][0]["answer"]["documents"], + json!([]) + ); + assert!(!value.to_string().contains("reviewer-own-subject")); + let schema = registry_breg::compiler::review_context::compile_schema( + &fixture.registry, + &fixture.registry.actions().actions[0], + ) + .unwrap() + .unwrap(); + assert!( + schema.schema["properties"].get("asks").is_none(), + "intrinsic asks cannot collide with authored field IDs" + ); + let denied = reviewer_get( + &fixture, + &format!("/v1/proposals/{id}/review-context?accessProfile=reviewer&include=answers"), + "zone-b", + ) + .await; + assert_eq!(denied.0, StatusCode::NOT_FOUND); + fixture.finish().await; +} + +#[tokio::test] +async fn serving_questions_marks_get_list_and_command_audit_without_recording_text() { + let authority = Authority::start(false, true).await; + let (fixture, id, ask) = committed_answer(&authority, "ask-audit").await; + for path in [format!("/v1/proposals/{id}"), "/v1/proposals".into()] { + let before = fixture.audit_capture.entries().len(); + let read = request(&fixture, "GET", &path, None, None, Value::Null).await; + assert_eq!(read.0, StatusCode::OK); + let entries = fixture.audit_capture.entries(); + assert!(entries[before..] + .iter() + .any( + |entry| entry["record"]["fieldSetReference"] == "proposal-review-ask" + || entry["record"]["askFieldSetReference"] == "proposal-review-ask" + )); + } + let entries = fixture.audit_capture.entries(); + let committed = entries + .iter() + .find(|entry| { + entry["record"]["operationId"] == "proposals.correct-name.answer" + && entry["record"]["outcome"] == "committed" + }) + .unwrap(); + assert_eq!(committed["record"]["reviewAskId"], ask.to_string()); + assert_eq!(committed["record"]["citedAdditionIds"], json!([])); + assert_eq!( + committed["record"]["askFieldSetReference"], + "proposal-review-ask" + ); + let journal = serde_json::to_string(&entries).unwrap(); + assert!(!journal.contains("private-answer-not-in-outbound-request")); + assert!(!journal.contains("Synthetic question")); + fixture.finish().await; +} + +async fn add_file(fixture: &client_http::ClientFixture, id: Uuid, key: &str, bytes: &[u8]) -> Uuid { + use tower::ServiceExt; + let (_, headers, _) = request( + fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let response = registry_breg::api::router(fixture.service()) + .layer(axum::Extension(claims())) + .oneshot( + axum::http::Request::post(format!("/v1/proposals/{id}/additions/other")) + .header("content-type", "text/plain") + .header("if-match", headers["etag"].clone()) + .header("idempotency-key", key) + .body(axum::body::Body::from(bytes.to_vec())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let value: Value = serde_json::from_slice( + &axum::body::to_bytes(response.into_body(), 1 << 20) + .await + .unwrap(), + ) + .unwrap(); + let item = value["additions"]["other"]["items"] + .as_array() + .unwrap() + .last() + .unwrap(); + Uuid::parse_str(item["id"].as_str().unwrap()).unwrap() +} + +#[tokio::test] +async fn ask_bound_file_download_discloses_only_cited_verified_files_of_this_review_binding_and_audits_why( +) { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "review-cited-file").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (ask, _) = announce(&authority, &binding); + authority + .state + .asks + .lock() + .unwrap() + .replies + .get_mut(&ask) + .unwrap() + .1["wants"] = json!([{"kind":"answer"},{"kind":"document"}]); + worker(&fixture, &authority).await.unwrap(); + let cited = add_file(&fixture, id, "cited-file", b"cited bytes").await; + let other_file = add_file(&fixture, id, "uncited-file", b"uncited bytes").await; + let (_, headers, _) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let answered = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer"), + Some(headers["etag"].to_str().unwrap()), + Some("cite-document"), + json!({"text":"The requested statement","additions":[cited]}), + ) + .await; + assert_eq!(answered.0, StatusCode::OK, "{}", answered.2); + let context = reviewer_get( + &fixture, + &format!("/v1/proposals/{id}/review-context?accessProfile=reviewer&include=answers"), + "zone-a", + ) + .await; + assert_eq!( + context.0, + StatusCode::OK, + "{}", + String::from_utf8_lossy(&context.2) + ); + let value: Value = serde_json::from_slice(&context.2).unwrap(); + assert_eq!(value["context"]["fields"], json!({"value":"After"})); + let documents = value["context"]["asks"][0]["answer"]["documents"] + .as_array() + .unwrap(); + assert_eq!(documents.len(), 1); + assert_eq!(documents[0]["id"], cited.to_string()); + let path = format!( + "{}&accessProfile=reviewer", + documents[0]["download"]["path"].as_str().unwrap() + ); + let before = fixture.audit_capture.entries().len(); + let downloaded = reviewer_get(&fixture, &path, "zone-a").await; + assert_eq!( + downloaded.0, + StatusCode::OK, + "{}", + String::from_utf8_lossy(&downloaded.2) + ); + assert_eq!(downloaded.2, b"cited bytes"); + assert_eq!(downloaded.1["content-type"], "text/plain"); + assert_eq!(downloaded.1["x-content-type-options"], "nosniff"); + assert_eq!(downloaded.1["cache-control"], "no-store"); + assert!(downloaded.1["content-disposition"] + .to_str() + .unwrap() + .starts_with("attachment")); + let entries = fixture.audit_capture.entries(); + let terminal = entries[before..] + .iter() + .find(|entry| entry["record"]["phase"] == "terminal") + .unwrap(); + assert_eq!(terminal["record"]["reviewAskId"], ask.to_string()); + assert_eq!(terminal["record"]["additionId"], cited.to_string()); + assert!(terminal["record"]["principalReference"].is_string()); + let answered_audit = entries + .iter() + .find(|entry| { + entry["record"]["outcome"] == "committed" + && entry["record"]["operationId"] == "proposals.correct-name.answer" + }) + .unwrap(); + assert_eq!(answered_audit["record"]["citedAdditionIds"], json!([cited])); + let other = submitted(&fixture, "other-review").await; + let other_binding = retained_binding(&fixture, other).await; + accept(&fixture, other, &other_binding).await; + let (other_ask, _) = announce(&authority, &other_binding); + worker(&fixture, &authority).await.unwrap(); + for denied in [ + path.replace(&cited.to_string(), &other_file.to_string()), + path.replace("submissionVersion=1", "submissionVersion=2"), + path.replace(&ask.to_string(), &other_ask.to_string()), + ] { + assert_eq!( + reviewer_get(&fixture, &denied, "zone-a").await.0, + StatusCode::NOT_FOUND, + "{denied}" + ); + } + assert_eq!( + reviewer_get(&fixture, &path, "zone-b").await.0, + StatusCode::NOT_FOUND + ); + let journal = serde_json::to_string(&fixture.audit_capture.entries()).unwrap(); + assert!(!journal.contains("The requested statement")); + assert!(!journal.contains("cited bytes")); + fixture.finish().await; +} + +#[tokio::test] +async fn pending_and_rejected_cited_files_have_no_review_link_and_refuse_a_guessed_download() { + use registry_breg::attachment_verification::AttachmentVerification; + use registry_platform_config::{AttachmentVerifierConfig, SecretProvider, SecretResolver}; + use registry_platform_objectstore::{HttpVerifierSettings, VerifierNamespace}; + let secrets = tempfile::tempdir().unwrap(); + let credential = secrets.path().join("verifier"); + std::fs::write(&credential, b"synthetic-verifier-token").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&credential, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + let resolver = SecretResolver::new([SecretProvider::File], secrets.path()).unwrap(); + let config:AttachmentVerifierConfig=serde_json::from_value(json!({"url":"http://127.0.0.1:1/verify","policyId":"synthetic-policy","authorizationRef":"secret:file/verifier","attemptTimeoutMilliseconds":2000})).unwrap(); + let verification = AttachmentVerification::Http(Arc::new( + HttpVerifierSettings::from_config(&config) + .unwrap() + .activate( + VerifierNamespace { + binding_domain: "breg-attachment-verification-http-v1", + max_content_bytes: registry_breg::contract::MAX_ATTACHMENT_BYTES as u64, + }, + &resolver, + ) + .unwrap(), + )); + let policy = verification.binding_digest(); + let authority = Authority::start(false, true).await; + let fixture = answer_fixture_with_verification(&authority, verification).await; + let id = submitted(&fixture, "quarantined-answer-file").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (ask, _) = announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + let file = add_file(&fixture, id, "quarantined-file", b"quarantined cited bytes").await; + let (_, headers, _) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let answered = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer"), + Some(headers["etag"].to_str().unwrap()), + Some("cite-quarantined-file"), + json!({"text":"Statement","additions":[file]}), + ) + .await; + assert_eq!(answered.0, StatusCode::OK, "{}", answered.2); + let mut download = None; + // Establish the exact same binding's valid URL, then quarantine it again. + for verdict in ["approved", "pending", "rejected"] { + fixture.database.admin.execute("INSERT INTO registry_internal.registry_attachment_verification(sha256,policy_digest,content_type,verdict) SELECT sha256,$1,content_type,$2 FROM registry_internal.registry_proposal_additions WHERE addition_id=$3 ON CONFLICT(sha256,policy_digest,content_type) DO UPDATE SET verdict=EXCLUDED.verdict",&[&policy,&verdict,&file]).await.unwrap(); + let context = reviewer_get( + &fixture, + &format!("/v1/proposals/{id}/review-context?accessProfile=reviewer&include=answers"), + "zone-a", + ) + .await; + assert_eq!(context.0, StatusCode::OK); + let value: Value = serde_json::from_slice(&context.2).unwrap(); + let descriptor = &value["context"]["asks"][0]["answer"]["documents"][0]; + assert_eq!(descriptor["verificationStatus"], verdict); + if verdict == "approved" { + download = Some(format!( + "{}&accessProfile=reviewer", + descriptor["download"]["path"].as_str().unwrap() + )); + assert_eq!( + reviewer_get(&fixture, download.as_deref().unwrap(), "zone-a") + .await + .0, + StatusCode::OK + ); + } else { + assert!(descriptor.get("download").is_none()); + let response = reviewer_get(&fixture, download.as_deref().unwrap(), "zone-a").await; + assert_eq!(response.0, StatusCode::NOT_FOUND); + assert!(!String::from_utf8_lossy(&response.2).contains("quarantined cited bytes")); + } + } + fixture.finish().await; +} + +#[tokio::test] +async fn an_empty_answer_to_an_ask_without_wants_is_invalid_without_changing_the_revision() { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "answer-without-wants").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (ask, _) = announce(&authority, &binding); + authority + .state + .asks + .lock() + .unwrap() + .replies + .get_mut(&ask) + .unwrap() + .1["wants"] = json!([]); + worker(&fixture, &authority).await.unwrap(); + let (_, headers, before) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + for (index, body) in [json!({}), json!({"additions":[]})].into_iter().enumerate() { + let response = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer"), + Some(headers["etag"].to_str().unwrap()), + Some(&format!("empty-answer-{index}")), + body, + ) + .await; + assert_eq!(response.0, StatusCode::BAD_REQUEST); + assert_eq!(response.2["code"], "request.invalid"); + assert_eq!(response.2["fieldPath"], "/text"); + } + let after = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(after.1["etag"], headers["etag"]); + assert_eq!(after.2["revision"], before["revision"]); + fixture.finish().await; +} + +#[tokio::test] +async fn operator_erasure_counts_and_scrubs_question_answer_actor_and_cited_files_per_version() { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "erase-ask-details").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + *authority.state.accepted.lock().unwrap() = Some(binding.clone()); + let (ask, _) = announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + let file = add_file(&fixture, id, "erase-answer-file", b"retained answer bytes").await; + let (_, headers, _) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let answered = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer"), + Some(headers["etag"].to_str().unwrap()), + Some("answer-for-erasure"), + json!({"text":"erase this answer","additions":[file]}), + ) + .await; + assert_eq!(answered.0, StatusCode::OK); + let (mut migration, task) = fixture.database.connect_migration().await; + let scope = registry_breg::proposal_retention::ProposalDetailErasureScope { + action_id: "correct-name", + proposal_id: id, + submission_version: 1, + }; + assert!(matches!( + registry_breg::proposal_retention::erase_proposal_detail( + &mut migration, + &fixture.registry, + scope.clone() + ) + .await, + Err(registry_breg::proposal_retention::ProposalRetentionError::ActiveDetailPinned) + )); + let (_, headers, _) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let cancelled = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/cancel"), + Some(headers["etag"].to_str().unwrap()), + Some("cancel-for-erasure"), + json!({}), + ) + .await; + assert_eq!(cancelled.0, StatusCode::OK); + worker(&fixture, &authority).await.unwrap(); + let erasure = registry_breg::proposal_retention::erase_proposal_detail( + &mut migration, + &fixture.registry, + scope, + ) + .await + .unwrap(); + let counts = serde_json::to_value(erasure).unwrap(); + assert_eq!(counts["reviewAsks"], 1); + assert_eq!(counts["reviewAnswers"], 1); + assert_eq!(counts["reviewAnswerFiles"], 1); + assert_eq!(erasure.attachment_references, 1); + let row=fixture.database.admin.query_one("SELECT (SELECT text IS NULL FROM registry_internal.registry_proposal_review_asks WHERE ask_id=$1),(SELECT text IS NULL AND answered_by IS NULL AND delivery_state='superseded' AND answered_at IS NOT NULL FROM registry_internal.registry_proposal_review_ask_answers WHERE ask_id=$1),(SELECT count(*) FROM registry_internal.registry_proposal_review_ask_files),(SELECT count(*) FROM registry_internal.registry_proposal_additions WHERE erased_at IS NULL),(SELECT count(*) FROM registry_internal.registry_attachment_blobs)",&[&ask]).await.unwrap(); + assert!(row.get::<_, bool>(0)); + assert!(row.get::<_, bool>(1)); + for index in 2..5 { + assert_eq!(row.get::<_, i64>(index), 0); + } + drop(migration); + task.abort(); + fixture.finish().await; +} + +#[tokio::test] +async fn answer_refusals_name_only_fields_and_preserve_the_open_ask() { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "answer-refusals").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (ask, _) = announce(&authority, &binding); + authority + .state + .asks + .lock() + .unwrap() + .replies + .get_mut(&ask) + .unwrap() + .1["wants"] = json!([{"kind":"answer"},{"kind":"document"}]); + worker(&fixture, &authority).await.unwrap(); + let file = add_file(&fixture, id, "answer-file", b"cited bytes").await; + let (_, headers, before) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let etag = headers["etag"].to_str().unwrap(); + let path = format!("/v1/proposals/{id}/asks/{ask}/answer"); + for (index, body, field) in [ + (0, json!({"additions":[file]}), Some("/text")), + (1, json!({"text":" ","additions":[file]}), Some("/text")), + (2, json!({"text":null,"additions":[file]}), Some("/text")), + (3, json!({"text":"explanation"}), Some("/additions")), + ( + 4, + json!({"text":"explanation","additions":[file,file]}), + Some("/additions"), + ), + ( + 5, + json!({"text":"explanation","additions":[Uuid::new_v4()]}), + Some("/additions"), + ), + ( + 6, + json!({"text":"explanation","additions":[file],"unknown":"secret"}), + None, + ), + ] { + let response = request( + &fixture, + "POST", + &path, + Some(etag), + Some(&format!("invalid-answer-{index}")), + body, + ) + .await; + assert_eq!(response.0, StatusCode::BAD_REQUEST, "{}", response.2); + assert_eq!(response.2["code"], "request.invalid"); + if let Some(field) = field { + assert_eq!(response.2["fieldPath"], field); + } + assert!(!response.2.to_string().contains("cited bytes")); + } + let unchanged = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(unchanged.2["revision"], before["revision"]); + // A citation must belong to this Proposal and submission version. + let other = submitted(&fixture, "foreign-citation").await; + let other_binding = retained_binding(&fixture, other).await; + accept(&fixture, other, &other_binding).await; + let foreign = add_file(&fixture, other, "foreign-citation-file", b"foreign file").await; + let wrong_proposal = request( + &fixture, + "POST", + &path, + Some(etag), + Some("foreign-file"), + json!({"text":"explanation","additions":[foreign]}), + ) + .await; + assert_eq!(wrong_proposal.0, StatusCode::BAD_REQUEST); + assert_eq!(wrong_proposal.2["code"], "request.invalid"); + assert_eq!(wrong_proposal.2["fieldPath"], "/additions"); + let accepted = request( + &fixture, + "POST", + &path, + Some(etag), + Some("valid-text-document"), + json!({"text":"explanation","additions":[file]}), + ) + .await; + assert_eq!(accepted.0, StatusCode::OK, "{}", accepted.2); + let again = request( + &fixture, + "POST", + &path, + Some(accepted.1["etag"].to_str().unwrap()), + Some("second-answer"), + json!({"text":"again","additions":[file]}), + ) + .await; + assert_eq!(again.0, StatusCode::PRECONDITION_FAILED); + let (second, _) = announce(&authority, &binding); + authority + .state + .asks + .lock() + .unwrap() + .replies + .get_mut(&second) + .unwrap() + .1["askedAt"] = json!((chrono::Utc::now() - chrono::Duration::days(1)).to_rfc3339()); + worker(&fixture, &authority).await.unwrap(); + let (_, headers, _) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let reused = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/asks/{second}/answer"), + Some(headers["etag"].to_str().unwrap()), + Some("reused-citation"), + json!({"text":"second explanation","additions":[file]}), + ) + .await; + assert_eq!(reused.0, StatusCode::BAD_REQUEST); + assert_eq!(reused.2["fieldPath"], "/additions"); + fixture.finish().await; +} + +#[tokio::test] +async fn due_and_closed_asks_have_typed_receipt_only_links_and_refuse_fresh_commands() { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "answer-due").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (ask, _) = announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + for (state, reason) in [("open", "ask-due-passed"), ("closed", "ask-closed")] { + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_asks SET state=$2,asked_at=transaction_timestamp()-interval '2 days',asked_at_wire=$3,due_at=transaction_timestamp()-interval '1 day',due_at_wire=$4 WHERE ask_id=$1",&[&ask,&state,&(chrono::Utc::now()-chrono::Duration::days(2)).to_rfc3339(),&(chrono::Utc::now()-chrono::Duration::days(1)).to_rfc3339()]).await.unwrap(); + let (_, headers, document) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let availability = &document["asks"][0]["links"]["answer"]["availability"]; + assert_eq!(availability["available"], false); + assert_eq!(availability["reason"], reason); + assert_eq!(availability["recovery"], "receipt-only"); + assert_eq!(document["status"], "in-review"); + let response = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer"), + Some(headers["etag"].to_str().unwrap()), + Some(reason), + json!({"text":"valid"}), + ) + .await; + assert_eq!( + response.0, + StatusCode::PRECONDITION_FAILED, + "{}", + response.2 + ); + } + fixture.finish().await; +} + +#[tokio::test] +async fn expired_answer_deadlines_refuse_without_sending_or_erasing_local_detail() { + let authority = Authority::start(false, true).await; + let (fixture, _, ask) = committed_answer(&authority, "answer-deadline").await; + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_ask_answers SET answered_at=transaction_timestamp()-interval '2 days',delivery_deadline=transaction_timestamp()-interval '1 day' WHERE ask_id=$1",&[&ask]).await.unwrap(); + worker(&fixture, &authority).await.unwrap(); + let row=fixture.database.admin.query_one("SELECT delivery_state,last_error_code,text,attempt_count FROM registry_internal.registry_proposal_review_ask_answers WHERE ask_id=$1",&[&ask]).await.unwrap(); + assert_eq!(row.get::<_, String>(0), "refused"); + assert_eq!(row.get::<_, String>(1), "answer-delivery-expired"); + assert!(row.get::<_, Option>(2).is_some()); + assert_eq!(row.get::<_, i32>(3), 0); + assert!(authority.state.asks.lock().unwrap().deliveries.is_empty()); + fixture.finish().await; +} + +#[tokio::test] +async fn revise_and_rebase_supersede_answers_and_hide_the_previous_round() { + for operation in ["revise", "rebase"] { + let authority = Authority::start(false, true).await; + let (fixture, id, ask) = committed_answer(&authority, operation).await; + let (_, headers, prior) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let draft = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/{operation}"), + Some(headers["etag"].to_str().unwrap()), + Some(operation), + json!({"input":prior["input"]}), + ) + .await; + assert_eq!(draft.0, StatusCode::OK, "{}", draft.2); + assert_eq!(draft.2["state"], "draft"); + assert!(draft.2.get("asks").is_none()); + assert_eq!(delivery(&fixture, ask).await["state"], "superseded"); + let denied = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer"), + Some(draft.1["etag"].to_str().unwrap()), + Some("old-round-answer"), + json!({"text":"Again"}), + ) + .await; + assert_eq!(denied.0, StatusCode::PRECONDITION_FAILED); + worker(&fixture, &authority).await.unwrap(); + assert!(authority.state.asks.lock().unwrap().deliveries.is_empty()); + fixture.finish().await; + } +} + +struct ActiveTaskGrant; +impl registry_breg::task_grant::TaskGrantStatusChecker for ActiveTaskGrant { + fn check<'a>( + &'a self, + _: &'a registry_breg::task_grant::TaskGrantBinding, + ) -> std::pin::Pin< + Box< + dyn std::future::Future> + + Send + + 'a, + >, + > { + Box::pin(async { Ok(()) }) + } +} + +/// The answer fixture plus a standing agent and a task-granted agent, each +/// holding the same get-review-context grant as the human reviewer. +async fn agent_answer_fixture( + authority: &Authority, +) -> ( + client_http::ClientFixture, + registry_platform_testing::MockIdp, + registry_breg::auth::RegistryAuthenticator, +) { + agent_answer_fixture_with_checker(authority, Arc::new(ActiveTaskGrant)).await +} + +async fn agent_answer_fixture_with_checker( + authority: &Authority, + checker: Arc, +) -> ( + client_http::ClientFixture, + registry_platform_testing::MockIdp, + registry_breg::auth::RegistryAuthenticator, +) { + let mut source = answer_source(); + let mut standing = source["accessProfiles"]["reviewer"].clone(); + standing["actorKind"] = json!("agent"); + standing["requesterClients"] = json!(["agent-client"]); + standing["permissions"] = json!({"proposals":standing["permissions"]["proposals"].clone()}); + let mut task = standing.clone(); + task["taskGrant"] = json!({"sourceIssuer":"https://casework.example"}); + let mut task_answerer = task.clone(); + task_answerer["permissions"]["proposals"][0]["operations"] = json!(["get", "answer"]); + source["accessProfiles"]["agent-reader"] = standing; + source["accessProfiles"]["task-reader"] = task; + source["accessProfiles"]["task-answerer"] = task_answerer; + // Get holders that may not answer, a service that holds `answer`, and a + // human reviewer who also holds Get. + let clerk = source["accessProfiles"]["clerk"].clone(); + for (id, operations, inputs, kind) in [ + ( + "staff", + json!(["get", "list", "cancel"]), + json!(["target", "value"]), + None, + ), + ( + "status", + json!(["get", "list", "get-review-status"]), + json!([]), + None, + ), + ( + "service", + json!(["get", "list", "answer"]), + json!(["target", "value"]), + Some("service"), + ), + ] { + let mut profile = clerk.clone(); + profile["default"] = json!(false); + if let Some(kind) = kind { + profile["actorKind"] = json!(kind); + profile["requesterClients"] = json!(["agent-client"]); + } + let grant = &mut profile["permissions"]["proposals"][0]; + grant.as_object_mut().unwrap().remove("ownership"); + grant["operations"] = operations; + grant["readableInputs"] = inputs; + grant["readableContextFields"] = json!([]); + grant["readableAttachments"] = json!([]); + grant["writableAttachments"] = json!([]); + source["accessProfiles"][id] = profile; + } + let mut review_staff = source["accessProfiles"]["reviewer"].clone(); + review_staff["permissions"]["proposals"][0]["operations"] = + json!(["get-review-context", "get", "list"]); + source["accessProfiles"]["review-staff"] = review_staff; + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + let registry = compile_project(&project, &[], CompileProfile::Authoring).unwrap(); + let bindings = authority.registry.clone(); + let fixture = + client_http::ClientFixture::start_with_mutations(registry, claims(), move |service| { + service + .with_review_result_source(bindings) + .with_task_status(checker) + }) + .await; + let idp = registry_platform_testing::MockIdp::start().await; + let mut verifier = registry_platform_testing::oidc_verifier_config( + idp.issuer(), + vec!["urn:example:breg".into()], + ); + verifier.allowed_clients = vec!["agent-client".into()]; + let auth = registry_breg::auth::RegistryAuthenticator::new( + &fixture.registry, + verifier, + Arc::new( + registry_platform_oidc::JwksFetcher::new_with_fetch_url_policy( + idp.jwks_uri(), + registry_platform_oidc::JwksFetcherConfig::defaults(), + registry_platform_httputil::FetchUrlPolicy::https_or_loopback(), + ), + ), + registry_breg::auth::AuthorityClaimConfig::new("sub", Some("registry_purpose".into())) + .with_contextual_claims( + registry_platform_oidc::ClaimNames::default(), + BTreeMap::from([("agent-client".to_owned(), TRUSTED_ACTOR.to_owned())]), + ), + ) + .unwrap(); + (fixture, idp, auth) +} + +const TRUSTED_ACTOR: &str = "00000000-0000-4000-8000-0000000000c7"; + +/// An agent token. Without a Proposal it is a standing agent acting for a +/// person through the trusted actor; with one it carries a task grant bounded +/// to that Proposal's review context. +fn agent_token(issuer: &str, grant: u64, proposal: Option) -> Value { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let mut token = json!({"aud":"urn:example:breg","sub":"review-agent","azp":"agent-client", + "registry_actor_kind":"agent", + "registry_purpose":"registry-administration","scope":"proposal:review", + "jurisdiction":"zone-a","exp":now+900}); + let Some(id) = proposal else { + token["act"] = json!({"sub":TRUSTED_ACTOR,"iss":issuer}); + return token; + }; + { + let claims = token.as_object_mut().unwrap(); + for (name, value) in [ + ( + "registry_grant_id", + json!(format!("00000000-0000-4000-8000-{grant:012x}")), + ), + ("registry_approver", json!("h:approver")), + ( + "registry_grant_source_issuer", + json!("https://casework.example"), + ), + ("registry_grant_client", json!("agent-client")), + ("registry_grant_resource", json!("urn:example:breg")), + ("registry_grant_exp", json!(now + 600)), + ( + "registry_grant_bounds", + json!({"type":"breg","permissions":[ + {"collection":format!("proposal:{id}"),"operations":["get-review-context"]}]}), + ), + ("identity", json!({"jurisdiction":"zone-a"})), + ] { + claims.insert(name.into(), value); + } + } + token +} + +async fn agent_get(http: &client_http::ClientHttp, path: &str) -> (StatusCode, Vec) { + let response = reqwest::Client::new() + .get(format!("{}{path}", http.base_url)) + .send() + .await + .unwrap(); + let status = StatusCode::from_u16(response.status().as_u16()).unwrap(); + (status, response.bytes().await.unwrap().to_vec()) +} + +fn discloses_asks(entries: &[Value]) -> bool { + entries.iter().any(|entry| { + entry["record"]["fieldSetReference"] == "proposal-review-ask" + || entry["record"]["askFieldSetReference"] == "proposal-review-ask" + }) +} + +/// Commit an answer that cites one verified file and return the reviewer's +/// download path for it, without an access profile. +async fn cited_answer( + fixture: &client_http::ClientFixture, + authority: &Authority, + id: Uuid, +) -> (Uuid, Uuid, String) { + let binding = retained_binding(fixture, id).await; + accept(fixture, id, &binding).await; + let (ask, _) = announce(authority, &binding); + authority + .state + .asks + .lock() + .unwrap() + .replies + .get_mut(&ask) + .unwrap() + .1["wants"] = json!([{"kind":"answer"},{"kind":"document"}]); + worker(fixture, authority).await.unwrap(); + let cited = add_file(fixture, id, &format!("cited-{id}"), b"cited bytes").await; + let (_, headers, _) = request( + fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let answered = request( + fixture, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer"), + Some(headers["etag"].to_str().unwrap()), + Some(&format!("cite-{id}")), + json!({"text":"The requested statement","additions":[cited]}), + ) + .await; + assert_eq!(answered.0, StatusCode::OK, "{}", answered.2); + let (status, _, bytes) = reviewer_get( + fixture, + &format!("/v1/proposals/{id}/review-context?accessProfile=reviewer&include=answers"), + "zone-a", + ) + .await; + assert_eq!( + status, + StatusCode::OK, + "{}", + String::from_utf8_lossy(&bytes) + ); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["context"]["asks"][0]["id"], ask.to_string()); + let path = value["context"]["asks"][0]["answer"]["documents"][0]["download"]["path"] + .as_str() + .unwrap() + .to_owned(); + (ask, cited, path) +} + +#[tokio::test] +async fn agents_holding_review_context_authority_get_no_answers_and_no_cited_files() { + let authority = Authority::start(false, true).await; + let (fixture, idp, auth) = agent_answer_fixture(&authority).await; + let id = submitted(&fixture, "agent-answers").await; + let (_, _, path) = cited_answer(&fixture, &authority, id).await; + let human = reviewer_get( + &fixture, + &format!("{path}&accessProfile=reviewer"), + "zone-a", + ) + .await; + assert_eq!(human.0, StatusCode::OK); + assert_eq!(human.2, b"cited bytes"); + for (profile, token) in [ + ("agent-reader", agent_token(&idp.issuer(), 1, None)), + ("task-reader", agent_token(&idp.issuer(), 2, Some(id))), + ] { + let agent = fixture + .client_for(auth.authenticate(&idp.mint_token(token)).await.unwrap()) + .await; + let before = fixture.audit_capture.entries().len(); + let (status, bytes) = agent_get( + &agent, + &format!("/v1/proposals/{id}/review-context?accessProfile={profile}&include=answers"), + ) + .await; + assert_eq!( + status, + StatusCode::OK, + "{profile}: {}", + String::from_utf8_lossy(&bytes) + ); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["context"]["fields"], json!({"value":"After"})); + assert!( + value["context"].get("asks").is_none(), + "{profile} received applicant answers" + ); + assert!(!String::from_utf8_lossy(&bytes).contains("The requested statement")); + assert!( + !discloses_asks(&fixture.audit_capture.entries()[before..]), + "{profile} was audited as disclosed answers" + ); + let (status, bytes) = agent_get(&agent, &format!("{path}&accessProfile={profile}")).await; + assert_eq!( + status, + StatusCode::NOT_FOUND, + "{profile} downloaded a cited file" + ); + assert!(!String::from_utf8_lossy(&bytes).contains("cited bytes")); + } + fixture.finish().await; +} + +#[tokio::test] +async fn batch_review_context_carries_no_answers_and_records_no_ask_disclosure() { + let authority = Authority::start(false, true).await; + let (fixture, id, ask) = committed_answer(&authority, "batch-answers").await; + let before = fixture.audit_capture.entries().len(); + let (status, _, bytes) = reviewer_get( + &fixture, + &format!("/v1/proposals/review-context?accessProfile=reviewer&ids={id}"), + "zone-a", + ) + .await; + assert_eq!( + status, + StatusCode::OK, + "{}", + String::from_utf8_lossy(&bytes) + ); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["items"][0]["status"], "visible"); + let context = &value["items"][0]["context"]["context"]; + assert_eq!(context["fields"], json!({"value":"After"})); + assert!( + context.get("asks").is_none(), + "the inbox batch carried answers" + ); + assert!(!String::from_utf8_lossy(&bytes).contains("private-answer-not-in-outbound-request")); + assert!(!discloses_asks(&fixture.audit_capture.entries()[before..])); + let before = fixture.audit_capture.entries().len(); + let (status, _, bytes) = reviewer_get( + &fixture, + &format!("/v1/proposals/{id}/review-context?accessProfile=reviewer&include=answers"), + "zone-a", + ) + .await; + assert_eq!(status, StatusCode::OK); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["context"]["asks"][0]["id"], ask.to_string()); + assert!(discloses_asks(&fixture.audit_capture.entries()[before..])); + fixture.finish().await; +} + +#[tokio::test] +async fn a_human_reviewer_under_a_stale_binding_is_refused_the_previous_rounds_cited_file() { + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "stale-binding").await; + let (_, _, path) = cited_answer(&fixture, &authority, id).await; + let current = format!("{path}&accessProfile=reviewer"); + assert!(current.contains("submissionVersion=1")); + assert_eq!( + reviewer_get(&fixture, ¤t, "zone-a").await.0, + StatusCode::OK + ); + let (_, headers, prior) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let draft = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/revise"), + Some(headers["etag"].to_str().unwrap()), + Some("stale-revise"), + json!({"input":prior["input"]}), + ) + .await; + assert_eq!(draft.0, StatusCode::OK, "{}", draft.2); + let resubmitted = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/submit"), + Some(draft.1["etag"].to_str().unwrap()), + Some("stale-resubmit"), + json!({}), + ) + .await; + assert_eq!(resubmitted.0, StatusCode::OK, "{}", resubmitted.2); + assert_eq!(resubmitted.2["submissionVersion"], 2); + // Accept the second round so the current binding is a live one. + let row = fixture.database.admin.query_one("SELECT create_request,expected_policy,expected_submission_digest FROM registry_internal.registry_proposal_review_submissions WHERE proposal_id=$1 AND submission_version=2", &[&id]).await.unwrap(); + let request: ReviewCreateRequest = serde_json::from_value(row.get(0)).unwrap(); + let binding = ReviewRequestAccepted { + request_id: Uuid::new_v4(), + subject: request.subject, + policy: serde_json::from_value(row.get(1)).unwrap(), + submission_digest: registry_review_client::SubmissionDigest::parse( + &row.get::<_, String>(2), + ) + .unwrap(), + }; + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_submissions SET state='accepted',accepted_binding=$2,next_result_poll_at=transaction_timestamp()+interval '1 hour' WHERE proposal_id=$1 AND submission_version=2", &[&id, &json!(binding)]).await.unwrap(); + let (status, _, bytes) = reviewer_get( + &fixture, + &format!("/v1/proposals/{id}/review-context?accessProfile=reviewer&include=answers"), + "zone-a", + ) + .await; + assert_eq!( + status, + StatusCode::OK, + "{}", + String::from_utf8_lossy(&bytes) + ); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["submissionVersion"], 2); + assert!( + value["context"] + .get("asks") + .and_then(Value::as_array) + .is_none_or(Vec::is_empty), + "the previous round's answers reached the current binding" + ); + let (status, _, bytes) = reviewer_get(&fixture, ¤t, "zone-a").await; + assert_eq!( + status, + StatusCode::NOT_FOUND, + "old-version cited file was served" + ); + assert!(!String::from_utf8_lossy(&bytes).contains("cited bytes")); + fixture.finish().await; +} + +fn caller_claims( + principal: &str, + kind: registry_platform_oidc::ActorKind, +) -> VerifiedRequestClaims { + VerifiedRequestClaims::authenticated_with_actor_kind( + "sub", + principal, + BTreeSet::from(["proposal:manage".into()]), + Some("registry-administration".into()), + BTreeMap::from([( + "jurisdiction".into(), + VerifiedClaimValue::direct_string("zone-a").unwrap(), + )]), + kind, + ) + .unwrap() +} + +/// Neither the question text nor an `asks` member reached this caller. +fn assert_no_asks(value: &Value, who: &str) { + assert!(value.get("asks").is_none(), "{who} received asks: {value}"); + assert!( + !value.to_string().contains("Synthetic question"), + "{who} received the question text" + ); +} + +#[tokio::test] +async fn asks_reach_only_a_human_caller_who_may_answer_this_proposal() { + use registry_platform_oidc::ActorKind; + let authority = Authority::start(false, true).await; + let (fixture, idp, auth) = agent_answer_fixture(&authority).await; + let id = submitted(&fixture, "ask-holders").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (ask, _) = announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + let owner = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(owner.2["asks"][0]["id"], ask.to_string(), "{}", owner.2); + + let mut service_token = agent_token(&idp.issuer(), 5, None); + let fields = service_token.as_object_mut().unwrap(); + fields.remove("act"); + fields.insert("sub".into(), json!("service-caller")); + fields.insert("registry_actor_kind".into(), json!("service")); + fields.insert("scope".into(), json!("proposal:manage")); + let service = auth + .authenticate(&idp.mint_token(service_token)) + .await + .unwrap(); + for (profile, claims) in [ + ("staff", caller_claims("staff-caller", ActorKind::Human)), + ("status", caller_claims("status-caller", ActorKind::Human)), + ("service", service.clone()), + ] { + let caller = || claims.clone(); + let get = request_as( + &fixture, + caller(), + "GET", + &format!("/v1/proposals/{id}?accessProfile={profile}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(get.0, StatusCode::OK, "{profile}: {}", get.2); + assert_no_asks(&get.2, profile); + let list = request_as( + &fixture, + caller(), + "GET", + &format!("/v1/proposals?accessProfile={profile}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(list.0, StatusCode::OK, "{profile}: {}", list.2); + assert_eq!(list.2["items"].as_array().unwrap().len(), 1, "{profile}"); + assert_no_asks(&list.2["items"][0], profile); + } + let (_, headers, _) = request_as( + &fixture, + service.clone(), + "GET", + &format!("/v1/proposals/{id}?accessProfile=service"), + None, + None, + Value::Null, + ) + .await; + let refused = request_as( + &fixture, + service, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer?accessProfile=service"), + Some(headers["etag"].to_str().unwrap()), + Some("service-answer"), + json!({"text":"service answer"}), + ) + .await; + assert_eq!(refused.0, StatusCode::NOT_FOUND, "{}", refused.2); + assert_eq!(refused.2["code"], "resource.not_found"); + + let standing = fixture + .client_for( + auth.authenticate(&idp.mint_token(agent_token(&idp.issuer(), 3, None))) + .await + .unwrap(), + ) + .await; + let (status, bytes) = agent_get( + &standing, + &format!("/v1/proposals/{id}?accessProfile=agent-reader"), + ) + .await; + assert!( + !String::from_utf8_lossy(&bytes).contains("Synthetic question"), + "standing agent: {status}" + ); + if status == StatusCode::OK { + assert_no_asks(&serde_json::from_slice(&bytes).unwrap(), "standing agent"); + } + let mut token = agent_token(&idp.issuer(), 4, Some(id)); + token["registry_grant_bounds"] = json!({"type":"breg","permissions":[ + {"collection":format!("proposal:{id}"),"operations":["get","answer"]}]}); + let task = fixture + .client_for(auth.authenticate(&idp.mint_token(token)).await.unwrap()) + .await; + let response = reqwest::Client::new() + .get(format!( + "{}/v1/proposals/{id}?accessProfile=task-answerer", + task.base_url + )) + .send() + .await + .unwrap(); + assert_eq!(response.status().as_u16(), 200); + let etag = response.headers()["etag"].to_str().unwrap().to_owned(); + assert_no_asks(&response.json().await.unwrap(), "task agent"); + let answered = reqwest::Client::new() + .post(format!( + "{}/v1/proposals/{id}/asks/{ask}/answer?accessProfile=task-answerer", + task.base_url + )) + .header("content-type", "application/json") + .header("if-match", etag) + .header("idempotency-key", "task-agent-answer") + .body(r#"{"text":"agent answer"}"#) + .send() + .await + .unwrap(); + assert_eq!(answered.status().as_u16(), 404); + assert_eq!( + answered.json::().await.unwrap()["code"], + "resource.not_found" + ); + + let (_, headers, _) = request_as( + &fixture, + caller_claims("staff-caller", ActorKind::Human), + "GET", + &format!("/v1/proposals/{id}?accessProfile=staff"), + None, + None, + Value::Null, + ) + .await; + let cancelled = request_as( + &fixture, + caller_claims("staff-caller", ActorKind::Human), + "POST", + &format!("/v1/proposals/{id}/cancel?accessProfile=staff"), + Some(headers["etag"].to_str().unwrap()), + Some("staff-cancel"), + json!({}), + ) + .await; + assert_eq!(cancelled.0, StatusCode::OK, "{}", cancelled.2); + assert_no_asks(&cancelled.2, "staff command response"); + let owner = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(owner.2["asks"][0]["id"], ask.to_string()); + assert!( + owner.2["asks"][0].get("answer").is_none(), + "a refused caller's answer was kept" + ); + fixture.finish().await; +} + +#[tokio::test] +async fn a_human_reviewer_without_answer_reads_answers_only_through_the_review_context() { + let authority = Authority::start(false, true).await; + let (fixture, _idp, _auth) = agent_answer_fixture(&authority).await; + let id = submitted(&fixture, "reviewer-get").await; + let (ask, _, path) = cited_answer(&fixture, &authority, id).await; + let (status, _, bytes) = reviewer_get( + &fixture, + &format!("/v1/proposals/{id}/review-context?accessProfile=review-staff&include=answers"), + "zone-a", + ) + .await; + assert_eq!( + status, + StatusCode::OK, + "{}", + String::from_utf8_lossy(&bytes) + ); + let context: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(context["context"]["asks"][0]["id"], ask.to_string()); + assert_eq!( + context["context"]["asks"][0]["answer"]["text"], + "The requested statement" + ); + let download = reviewer_get( + &fixture, + &format!("{path}&accessProfile=review-staff"), + "zone-a", + ) + .await; + assert_eq!(download.0, StatusCode::OK); + assert_eq!(download.2, b"cited bytes"); + let (status, _, bytes) = reviewer_get( + &fixture, + &format!("/v1/proposals/{id}?accessProfile=review-staff"), + "zone-a", + ) + .await; + assert_eq!( + status, + StatusCode::OK, + "{}", + String::from_utf8_lossy(&bytes) + ); + let document: Value = serde_json::from_slice(&bytes).unwrap(); + assert!(document.get("asks").is_none(), "{document}"); + assert!(!String::from_utf8_lossy(&bytes).contains("The requested statement")); + fixture.finish().await; +} diff --git a/crates/registry-breg/tests/support/proposal_review_asks_final.rs b/crates/registry-breg/tests/support/proposal_review_asks_final.rs new file mode 100644 index 0000000000..d40b8efc7c --- /dev/null +++ b/crates/registry-breg/tests/support/proposal_review_asks_final.rs @@ -0,0 +1,348 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; + +#[tokio::test] +async fn answering_requires_the_human_owner_operation_and_current_row_boundary() { + use registry_platform_oidc::ActorKind; + let authority = Authority::start(false, true).await; + let (fixture, _, _) = agent_answer_fixture(&authority).await; + let id = submitted(&fixture, "answer-authority").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (ask, _) = announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + let (_, headers, before) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + for (key, profile, caller) in [ + ( + "wrong-grant", + "staff", + caller_claims("author-canary", ActorKind::Human), + ), + ( + "non-owner", + "clerk", + caller_claims("other-applicant", ActorKind::Human), + ), + ( + "agent", + "clerk", + caller_claims("author-canary", ActorKind::Agent), + ), + ] { + let refused = request_as( + &fixture, + caller, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer?accessProfile={profile}"), + Some(headers["etag"].to_str().unwrap()), + Some(key), + json!({"text":"unauthorized"}), + ) + .await; + assert_eq!(refused.0, StatusCode::NOT_FOUND, "{key}: {}", refused.2); + assert_eq!(refused.2["code"], "resource.not_found", "{key}"); + } + let other = submitted(&fixture, "another-ask-owner").await; + let other_binding = retained_binding(&fixture, other).await; + accept(&fixture, other, &other_binding).await; + let (foreign_ask, _) = announce(&authority, &other_binding); + worker(&fixture, &authority).await.unwrap(); + let foreign = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/asks/{foreign_ask}/answer"), + Some(headers["etag"].to_str().unwrap()), + Some("foreign-ask"), + json!({"text":"unauthorized"}), + ) + .await; + assert_eq!(foreign.0, StatusCode::NOT_FOUND, "{}", foreign.2); + assert_eq!(foreign.2["code"], "resource.not_found"); + let target = Uuid::parse_str(before["input"]["target"].as_str().unwrap()).unwrap(); + let entity = &fixture.registry.entities()["target"]; + fixture + .database + .admin + .execute( + &format!( + "UPDATE registry_data.\"{}\" SET \"{}\"=$2 WHERE record_id=$1", + entity.physical_table, entity.fields["jurisdiction"].physical_name + ), + &[&target, &"zone-b"], + ) + .await + .unwrap(); + let refused = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer"), + Some(headers["etag"].to_str().unwrap()), + Some("outside-boundary"), + json!({"text":"unauthorized"}), + ) + .await; + assert_eq!(refused.0, StatusCode::PRECONDITION_FAILED, "{}", refused.2); + assert_eq!(refused.2["code"], "precondition.failed"); + let count: i64 = fixture.database.admin.query_one("SELECT count(*) FROM registry_internal.registry_proposal_review_ask_answers WHERE proposal_id=$1", &[&id]).await.unwrap().get(0); + assert_eq!(count, 0); + fixture.finish().await; +} + +#[tokio::test] +async fn a_stale_task_grant_cannot_answer_even_when_its_profile_lists_answer() { + struct Stale; + impl registry_breg::task_grant::TaskGrantStatusChecker for Stale { + fn check<'a>( + &'a self, + _: &'a registry_breg::task_grant::TaskGrantBinding, + ) -> std::pin::Pin< + Box< + dyn std::future::Future< + Output = Result<(), registry_breg::task_grant::TaskGrantError>, + > + Send + + 'a, + >, + > { + Box::pin(async { Err(registry_breg::task_grant::TaskGrantError::Refused) }) + } + } + let authority = Authority::start(false, true).await; + let (fixture, idp, auth) = agent_answer_fixture_with_checker(&authority, Arc::new(Stale)).await; + let id = submitted(&fixture, "stale-answer-grant").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (ask, _) = announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + let (_, headers, _) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let mut token = agent_token(&idp.issuer(), 4, Some(id)); + token["registry_grant_bounds"] = json!({"type":"breg","permissions":[{"collection":format!("proposal:{id}"),"operations":["get","answer"]}]}); + let caller = auth.authenticate(&idp.mint_token(token)).await.unwrap(); + let refused = request_as( + &fixture, + caller, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer?accessProfile=task-answerer"), + Some(headers["etag"].to_str().unwrap()), + Some("stale-grant"), + json!({"text":"unauthorized"}), + ) + .await; + assert_eq!(refused.0, StatusCode::NOT_FOUND, "{}", refused.2); + assert_eq!(refused.2["code"], "resource.not_found"); + assert_eq!(fixture.database.admin.query_one("SELECT count(*) FROM registry_internal.registry_proposal_review_ask_answers WHERE proposal_id=$1", &[&id]).await.unwrap().get::<_,i64>(0), 0); + fixture.finish().await; +} + +#[tokio::test] +async fn only_an_explicit_display_read_serves_and_audits_intrinsic_answers() { + let authority = Authority::start(false, true).await; + let (fixture, id, _) = committed_answer(&authority, "answers-opt-in").await; + let before = fixture.audit_capture.entries().len(); + let plain = reviewer_get( + &fixture, + &format!("/v1/proposals/{id}/review-context?accessProfile=reviewer"), + "zone-a", + ) + .await; + assert_eq!(plain.0, StatusCode::OK); + let value: Value = serde_json::from_slice(&plain.2).unwrap(); + assert!( + value["context"].get("asks").is_none(), + "preflight context must omit answers" + ); + assert!(fixture.audit_capture.entries()[before..] + .iter() + .all(|entry| entry["record"].get("askFieldSetReference").is_none())); + for query in [ + "include=progress", + "include=answers&include=answers", + "include=unknown", + ] { + let invalid = reviewer_get( + &fixture, + &format!("/v1/proposals/{id}/review-context?accessProfile=reviewer&{query}"), + "zone-a", + ) + .await; + assert_eq!(invalid.0, StatusCode::NOT_FOUND, "{query}"); + let problem: Value = serde_json::from_slice(&invalid.2).unwrap(); + assert_eq!(problem["code"], "resource.not_found"); + } + let before = fixture.audit_capture.entries().len(); + let shown = reviewer_get( + &fixture, + &format!("/v1/proposals/{id}/review-context?accessProfile=reviewer&include=answers"), + "zone-a", + ) + .await; + assert_eq!(shown.0, StatusCode::OK); + let value: Value = serde_json::from_slice(&shown.2).unwrap(); + assert!(value["context"]["asks"][0]["answer"]["text"].is_string()); + assert!(fixture.audit_capture.entries()[before..] + .iter() + .any(|entry| entry["record"]["askFieldSetReference"] == "proposal-review-ask")); + fixture.finish().await; +} + +#[tokio::test] +async fn a_document_ask_can_cite_an_uncited_current_file_when_the_additions_slot_is_full() { + let authority = Authority::start(false, true).await; + let mut source = answer_source(); + source["actions"]["correct-name"]["execution"]["proposal"]["additions"]["maximumCount"] = + json!(1); + let registry = compile_project( + &parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(), + &[], + CompileProfile::Authoring, + ) + .unwrap(); + let bindings = authority.registry.clone(); + let fixture = + client_http::ClientFixture::start_with_mutations(registry, applicant(), move |m| { + m.with_review_result_source(bindings) + }) + .await; + let id = submitted(&fixture, "full-additions-ask").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let file = add_file(&fixture, id, "already-added", b"current submission file").await; + let (ask, _) = announce(&authority, &binding); + authority + .state + .asks + .lock() + .unwrap() + .replies + .get_mut(&ask) + .unwrap() + .1["wants"] = json!([{"kind":"document"}]); + worker(&fixture, &authority).await.unwrap(); + let (_, headers, before) = request( + &fixture, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!( + before["additions"]["other"]["items"] + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!( + before["additions"]["other"]["links"]["add"]["availability"]["reason"], + "limit-reached" + ); + let answered = request( + &fixture, + "POST", + &format!("/v1/proposals/{id}/asks/{ask}/answer"), + Some(headers["etag"].to_str().unwrap()), + Some("cite-existing"), + json!({"additions":[file]}), + ) + .await; + assert_eq!(answered.0, StatusCode::OK, "{}", answered.2); + assert_eq!(answered.2["asks"][0]["answer"]["additions"], json!([file])); + assert_eq!(answered.2["effectDigest"], before["effectDigest"]); + assert_eq!(answered.2["submissionVersion"], before["submissionVersion"]); + fixture.finish().await; +} + +#[tokio::test] +async fn a_clock_skew_delivery_refusal_keeps_its_code_and_raises_the_operator_signal() { + let authority = Authority::start(false, true).await; + let (fixture, _, ask) = committed_answer(&authority, "clock-skew-answer").await; + { + let mut state = authority.state.asks.lock().unwrap(); + state.answer_status = 422; + state.answer_code = Some("review.ask-answer-time-invalid".into()); + } + let logs = CapturedDiagnosticLogs::default(); + worker(&fixture, &authority) + .with_subscriber(logs.subscriber_with_max_level(tracing::Level::DEBUG)) + .await + .unwrap(); + let job = delivery(&fixture, ask).await; + assert_eq!(job["state"], "refused"); + assert_eq!(job["error"], "review.ask-answer-time-invalid"); + assert!( + logs.text().contains("review.result_lookups.unavailable"), + "{}", + logs.text() + ); + worker(&fixture, &authority).await.unwrap(); + assert_eq!(authority.state.asks.lock().unwrap().deliveries.len(), 1); + fixture.finish().await; +} + +#[tokio::test] +async fn pruning_a_receipt_then_resetting_the_cursor_never_refetches_or_duplicates_its_stored_ask() +{ + let authority = Authority::start(false, true).await; + let fixture = answer_fixture(&authority).await; + let id = submitted(&fixture, "prune-ask-receipt").await; + let binding = retained_binding(&fixture, id).await; + accept(&fixture, id, &binding).await; + let (_, event) = announce(&authority, &binding); + worker(&fixture, &authority).await.unwrap(); + let before = read_applicant(&fixture, &format!("/v1/proposals/{id}")).await; + assert_eq!(authority.state.asks.lock().unwrap().reads.len(), 1); + assert_eq!(fixture.database.admin.query_one("SELECT recovery_days FROM registry_internal.registry_proposal_review_ask_feed_events WHERE event_id=$1", &[&event]).await.unwrap().get::<_,i32>(0), 7); + let fresh = Uuid::new_v4(); + fixture.database.admin.execute("INSERT INTO registry_internal.registry_proposal_review_ask_feed_events(authority,event_id,review_request_id,ask_id,state,recovery_days) SELECT authority,$2,review_request_id,ask_id,state,recovery_days FROM registry_internal.registry_proposal_review_ask_feed_events WHERE event_id=$1", &[&event,&fresh]).await.unwrap(); + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_ask_feed_events SET observed_at=transaction_timestamp()-interval '8 days' WHERE event_id=$1",&[&event]).await.unwrap(); + let logs = CapturedDiagnosticLogs::default(); + worker(&fixture, &authority) + .with_subscriber(logs.subscriber_with_max_level(tracing::Level::DEBUG)) + .await + .unwrap(); + assert_eq!(fixture.database.admin.query_one("SELECT count(*) FROM registry_internal.registry_proposal_review_ask_feed_events WHERE event_id=$1",&[&event]).await.unwrap().get::<_,i64>(0),0,"the maintenance runner prunes an eight-day receipt under this seven-day authority"); + assert!( + logs.text().contains("\"ask_feed_events_pruned\":1"), + "{}", + logs.text() + ); + assert_eq!(fixture.database.admin.query_one("SELECT count(*) FROM registry_internal.registry_proposal_review_ask_feed_events WHERE event_id=$1", &[&fresh]).await.unwrap().get::<_,i64>(0), 1, "a fresh receipt remains inside its observation recovery window"); + authority.state.asks.lock().unwrap().gone_once = true; + worker(&fixture, &authority).await.unwrap(); + worker(&fixture, &authority).await.unwrap(); + let after = read_applicant(&fixture, &format!("/v1/proposals/{id}")).await; + assert_eq!(after["revision"], before["revision"]); + assert_eq!(after["asks"], before["asks"]); + assert_eq!( + authority.state.asks.lock().unwrap().reads.len(), + 1, + "a pruned receipt and 410 must not fetch its stored ask again" + ); + fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_asks SET last_feed_changed_at_wire=NULL WHERE proposal_id=$1", &[&id]).await.unwrap(); + authority.state.asks.lock().unwrap().gone_once = true; + worker(&fixture, &authority).await.unwrap(); + worker(&fixture, &authority).await.unwrap(); + assert_eq!( + authority.state.asks.lock().unwrap().reads.len(), + 1, + "a legacy open mirror uses its original askedAt to skip the opening event" + ); + fixture.finish().await; +} diff --git a/crates/registry-breg/tests/support/proposal_status.rs b/crates/registry-breg/tests/support/proposal_status.rs new file mode 100644 index 0000000000..e35b295244 --- /dev/null +++ b/crates/registry-breg/tests/support/proposal_status.rs @@ -0,0 +1,537 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; +use std::sync::Arc; + +pub(super) fn require_review(source: &mut Value) { + source["reviewAuthorities"] = + json!({"local-review":{"protocol":"id.registrystack.org/protocols/review/v1"}}); + source["actions"]["correct-name"]["execution"]["proposal"]["review"] = json!({"type":"required", + "authority":"local-review","source":"proposal-test", + "policy":{"id":"name-correction","version":"1","digest":format!("sha256:{}","b".repeat(64))}}); +} + +pub(super) async fn pending_review_fixture( + registry: registry_breg::CompiledRegistry, +) -> client_http::ClientFixture { + let review = Arc::new(LocalReview { + calls: 0.into(), + mode: 0.into(), + result_id: uuid::Uuid::new_v4(), + }); + client_http::ClientFixture::start_with_mutations( + registry, + claims("author", "zone-a"), + move |mutations| { + mutations.with_proposal_review_substitute_for_test(local_review_binding(), review) + }, + ) + .await +} + +async fn fixture(required: bool) -> (client_http::ClientFixture, Arc) { + let mut source = registry_source(false); + let review = Arc::new(LocalReview { + calls: 0.into(), + mode: 0.into(), + result_id: uuid::Uuid::new_v4(), + }); + let fixture = if required { + source["reviewAuthorities"] = + json!({"local-review":{"protocol":"id.registrystack.org/protocols/review/v1"}}); + source["actions"]["correct-name"]["execution"]["proposal"]["review"] = json!({"type":"required", + "authority":"local-review","source":"proposal-test", + "policy":{"id":"name-correction","version":"1","digest":format!("sha256:{}","b".repeat(64))}}); + let injected = review.clone(); + client_http::ClientFixture::start_with_mutations( + compile(source), + claims("author", "zone-a"), + move |mutations| { + mutations.with_proposal_review_substitute_for_test(local_review_binding(), injected) + }, + ) + .await + } else { + client_http::ClientFixture::start(compile(source), claims("author", "zone-a")).await + }; + (fixture, review) +} + +async fn submit( + fixture: &client_http::ClientFixture, + prefix: &str, +) -> registry_breg_client::BRegProposal { + let draft = start(fixture, "Status test", &format!("{prefix}-start")).await; + fixture + .http + .client + .execute_proposal( + &fixture + .http + .client + .prepare_proposal( + &draft, + "submit", + json!({}), + &key(&format!("{prefix}-submit")), + ) + .unwrap(), + ) + .await + .unwrap() + .value +} + +async fn observations( + fixture: &client_http::ClientFixture, + command: ®istry_breg_client::BRegProposal, + status: &str, + turn: &str, +) { + let value = serde_json::to_value(command).unwrap(); + assert_eq!(value["status"], status, "command/read document"); + assert_eq!(value["turn"], turn); + let current = fixture + .http + .client + .read_proposal(command) + .await + .unwrap() + .value; + let value = serde_json::to_value(¤t).unwrap(); + assert_eq!(value["status"], status, "Get"); + assert_eq!(value["turn"], turn); + let metadata = fixture + .http + .client + .registry_contract(Some("clerk")) + .await + .unwrap() + .value; + let collection = metadata.select_proposals("clerk").unwrap(); + let page = fixture + .http + .client + .list_proposals(&collection, &BRegProposalQuery::default()) + .await + .unwrap() + .value; + let item = page + .items + .iter() + .find(|item| item.id() == command.id()) + .unwrap(); + let item = serde_json::to_value(item).unwrap(); + assert_eq!(item["status"], status, "List"); + assert_eq!(item["turn"], turn); +} + +pub(super) async fn raw_command( + fixture: &client_http::ClientFixture, + proposal: ®istry_breg_client::BRegProposal, + operation: &str, +) -> reqwest::Response { + let value = serde_json::to_value(proposal).unwrap(); + reqwest::Client::new() + .post(format!( + "{}/v1/proposals/{}/{operation}?accessProfile=clerk", + fixture.http.base_url, + proposal.id() + )) + .header( + "if-match", + value["links"][operation]["ifMatch"].as_str().unwrap(), + ) + .header("idempotency-key", format!("status-{operation}")) + .json(&if operation == "rebase" { + json!({"input": value["input"]}) + } else { + json!({}) + }) + .send() + .await + .unwrap() +} + +#[tokio::test] +async fn proposal_status_is_served_on_draft_review_approval_and_application() { + let (fixture, review) = fixture(true).await; + let client = &fixture.http.client; + let draft = start(&fixture, "Status test", "status-draft-start").await; + observations(&fixture, &draft, "draft", "party").await; + let submitted = client + .execute_proposal( + &client + .prepare_proposal(&draft, "submit", json!({}), &key("status-draft-submit")) + .unwrap(), + ) + .await + .unwrap() + .value; + observations(&fixture, &submitted, "in-review", "official").await; + retain_queue_review( + &fixture, + &submitted, + &review, + registry_review_client::ReviewResultStatus::Approved, + false, + true, + ) + .await; + let approved = client.read_proposal(&submitted).await.unwrap().value; + observations(&fixture, &approved, "approved", "official").await; + let value = serde_json::to_value(&approved).unwrap(); + for operation in ["revise", "rebase"] { + let availability = &value["links"][operation]["availability"]; + assert_eq!(availability["available"], false); + assert_eq!(availability["reason"], "application-pending"); + assert_eq!(availability["recovery"], "refresh"); + } + let applied=client.execute_proposal(&client.prepare_proposal(&approved,"apply", + json!({"submissionVersion":approved.submission_version(),"effectDigest":approved.effect_digest().unwrap()}), + &key("status-apply")).unwrap()).await.unwrap().value; + observations(&fixture, &applied, "applied", "nobody").await; + for row in fixture.database.admin.query("SELECT payload FROM registry_internal.registry_outbox WHERE event_type LIKE 'proposal.%'",&[]).await.unwrap() { + let bytes:Vec=row.get(0); + let payload:Value=serde_json::from_slice(&bytes).unwrap(); + assert!(payload.get("status").is_none(),"lifecycle event vocabulary stays unchanged"); + } + assert_eq!( + reqwest::get(format!( + "{}/v1/proposals?accessProfile=clerk&status=approved", + fixture.http.base_url + )) + .await + .unwrap() + .status(), + 400, + "status is not a collection filter" + ); + fixture.finish().await; +} + +async fn approval_refuses(operation: &str) { + let (fixture, review) = fixture(true).await; + let submitted = submit(&fixture, &format!("approved-{operation}")).await; + retain_queue_review( + &fixture, + &submitted, + &review, + registry_review_client::ReviewResultStatus::Approved, + false, + true, + ) + .await; + let approved = fixture + .http + .client + .read_proposal(&submitted) + .await + .unwrap() + .value; + let fresh = reqwest::get(format!( + "{}/v1/proposals/{}?accessProfile=clerk", + fixture.http.base_url, + approved.id() + )) + .await + .unwrap(); + let etag = fresh.headers()["etag"].to_str().unwrap().to_owned(); + let served: Value = fresh.json().await.unwrap(); + assert_eq!(served["links"][operation]["ifMatch"], etag); + assert_eq!( + served["links"][operation]["availability"], + json!({ + "available":false,"observedRevision":approved.revision(), + "reason":"application-pending","recovery":"refresh" + }) + ); + assert!(served["input"]["target"].is_string()); + assert!(served["input"]["value"].is_string()); + let response = raw_command(&fixture, &approved, operation).await; + let status = response.status(); + let problem: Value = response.json().await.unwrap(); + assert_eq!(problem["code"], "precondition.failed"); + assert_eq!( + problem["type"], + "https://id.registrystack.org/problems/registry-breg/precondition/failed" + ); + assert_eq!(problem["detail"], "The mutation precondition failed."); + let current = fixture + .http + .client + .read_proposal(&approved) + .await + .unwrap() + .value; + let state = current.state(); + let version = current.submission_version(); + fixture.finish().await; + assert_eq!( + status, 412, + "an approval cannot be discarded by {operation}" + ); + assert_eq!(state, BRegProposalState::Submitted); + assert_eq!(version, 1); +} + +#[tokio::test] +async fn proposal_status_prevents_revise_from_discarding_an_approval() { + approval_refuses("revise").await; +} + +#[tokio::test] +async fn proposal_status_prevents_rebase_from_discarding_an_approval() { + approval_refuses("rebase").await; +} + +#[tokio::test] +async fn proposal_link_checks_do_not_lock_target_rows() { + let mut source = registry_source(false); + require_review(&mut source); + source["actions"]["correct-name"]["execution"]["proposal"]["additions"] = json!({ + "id":"other","maximumBytes":32,"maximumCount":2,"contentTypes":["text/plain"],"classification":"restricted" + }); + let grant = &mut source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]; + grant["operations"] + .as_array_mut() + .unwrap() + .push(json!("add")); + grant["readableAttachments"] = json!(["support", "other"]); + grant["writableAttachments"] = json!(["support", "other"]); + let fixture = + client_http::ClientFixture::start(compile(source), claims("author", "zone-a")).await; + let draft = start(&fixture, "Lock probe", "status-read-lock").await; + let value = serde_json::to_value(&draft).unwrap(); + let target = uuid::Uuid::parse_str(value["input"]["target"].as_str().unwrap()).unwrap(); + // Hold the target on an independent connection while serving every lifecycle link. + fixture.database.admin.batch_execute("BEGIN").await.unwrap(); + fixture + .database + .admin + .query_one( + &format!( + "SELECT record_id FROM registry_data.\"{}\" WHERE record_id=$1 FOR UPDATE", + fixture.registry.entities()["target"].physical_table + ), + &[&target], + ) + .await + .unwrap(); + let response = reqwest::get(format!( + "{}/v1/proposals/{}?accessProfile=clerk", + fixture.http.base_url, + draft.id() + )) + .await + .unwrap(); + let status = response.status(); + let served: Value = response.json().await.unwrap(); + let command = reqwest::Client::new() + .post(format!( + "{}/v1/proposals/{}/edit?accessProfile=clerk", + fixture.http.base_url, + draft.id() + )) + .header( + "if-match", + value["links"]["edit"]["ifMatch"].as_str().unwrap(), + ) + .header("idempotency-key", "status-lock-edit") + .json(&json!({"input":value["input"]})) + .send() + .await + .unwrap(); + let command_status = command.status(); + fixture + .database + .admin + .batch_execute("ROLLBACK") + .await + .unwrap(); + fixture.finish().await; + assert_eq!( + status, 200, + "link checks must read through another transaction's target lock" + ); + assert!(served["attachments"]["support"]["links"]["upload"].is_object()); + assert!(served["additions"]["other"]["links"]["add"].is_object()); + assert_eq!( + command_status, 503, + "the command must still acquire the target lock" + ); +} + +async fn concealed_target_is_not_a_recovery_block(deleted: bool) { + let (fixture, _) = fixture(false).await; + let proposal = submit( + &fixture, + if deleted { + "deleted-target" + } else { + "hidden-target" + }, + ) + .await; + let value = serde_json::to_value(&proposal).unwrap(); + let target = uuid::Uuid::parse_str(value["input"]["target"].as_str().unwrap()).unwrap(); + let entity = &fixture.registry.entities()["target"]; + // This fixture exposes only name corrections, with no Delete or jurisdiction + // mutation. Model an independent writer removing this caller's target access. + let statement = if deleted { + format!( + "UPDATE registry_data.\"{}\" SET record_lifecycle='tombstoned' WHERE record_id=$1", + entity.physical_table + ) + } else { + format!( + "UPDATE registry_data.\"{}\" SET \"{}\"='zone-b' WHERE record_id=$1", + entity.physical_table, entity.fields["jurisdiction"].physical_name + ) + }; + fixture + .database + .admin + .execute(&statement, &[&target]) + .await + .unwrap(); + let refused = fixture.http.client.execute_proposal(&fixture.http.client.prepare_proposal(&proposal,"apply", + json!({"submissionVersion":proposal.submission_version(),"effectDigest":proposal.effect_digest().unwrap()}), + &key("concealed-target-apply")).unwrap()).await.unwrap_err(); + assert_eq!( + refused.problem_code(), + Some(BRegProblemCode::PreconditionFailed) + ); + let read = reqwest::get(format!( + "{}/v1/proposals/{}?accessProfile=clerk", + fixture.http.base_url, + proposal.id() + )) + .await + .unwrap(); + assert_eq!(read.status(), 404); + let id = uuid::Uuid::parse_str(proposal.id()).unwrap(); + let row = fixture.database.admin.query_one( + "SELECT blocked_reason,workflow_revision FROM registry_internal.registry_proposal_state WHERE proposal_id=$1",&[&id]).await.unwrap(); + assert_eq!(row.get::<_, Option>(0), None); + assert_eq!(row.get::<_, i64>(1), proposal.revision() as i64); + fixture.finish().await; +} + +#[tokio::test] +async fn a_deleted_target_stays_concealed_without_an_application_block() { + concealed_target_is_not_a_recovery_block(true).await; +} + +#[tokio::test] +async fn a_target_outside_the_current_boundary_stays_concealed_without_an_application_block() { + concealed_target_is_not_a_recovery_block(false).await; +} + +#[tokio::test] +async fn proposal_status_returns_changes_requested_to_the_party_for_revise() { + let (fixture, review) = fixture(true).await; + let submitted = submit(&fixture, "status-returned").await; + retain_queue_review( + &fixture, + &submitted, + &review, + registry_review_client::ReviewResultStatus::ChangesRequested, + false, + true, + ) + .await; + let returned = fixture + .http + .client + .read_proposal(&submitted) + .await + .unwrap() + .value; + observations(&fixture, &returned, "awaiting-party", "party").await; + assert_eq!( + serde_json::to_value(&returned).unwrap()["links"]["revise"]["availability"]["available"], + true + ); + let revised = fixture + .http + .client + .execute_proposal( + &fixture + .http + .client + .prepare_proposal( + &returned, + "revise", + json!({}), + &key("status-returned-revise"), + ) + .unwrap(), + ) + .await + .unwrap() + .value; + assert_eq!(revised.submission_version(), 2); + observations(&fixture, &revised, "draft", "party").await; + fixture.finish().await; +} + +#[tokio::test] +async fn proposal_status_distinguishes_rejection_and_cancellation() { + for terminal in ["rejected", "cancelled"] { + let (fixture, review) = fixture(true).await; + let submitted = submit(&fixture, &format!("status-{terminal}")).await; + let closed = if terminal == "cancelled" { + fixture + .http + .client + .execute_proposal( + &fixture + .http + .client + .prepare_proposal(&submitted, "cancel", json!({}), &key("status-cancel")) + .unwrap(), + ) + .await + .unwrap() + .value + } else { + let policy = json!({"id":"name-correction","version":"1","digest":format!("sha256:{}","b".repeat(64))}); + inject_review_decision(&fixture, &review, policy, "rejected").await; + fixture + .http + .client + .read_proposal(&submitted) + .await + .unwrap() + .value + }; + observations(&fixture, &closed, terminal, "nobody").await; + fixture.finish().await; + } +} + +#[tokio::test] +async fn proposal_status_processing_preserves_a_review_free_manual_submission() { + let (fixture, _) = fixture(false).await; + let submitted = submit(&fixture, "status-processing").await; + let current = fixture + .http + .client + .read_proposal(&submitted) + .await + .unwrap() + .value; + let response = raw_command(&fixture, ¤t, "revise").await; + let status = response.status(); + if status != 412 { + fixture.finish().await; + assert_eq!(status, 412, "processing work cannot be revised"); + return; + } + assert_eq!( + raw_command(&fixture, ¤t, "rebase").await.status(), + 412 + ); + observations(&fixture, ¤t, "processing", "official").await; + fixture.finish().await; +} diff --git a/crates/registry-breg/tests/support/review_go_live.rs b/crates/registry-breg/tests/support/review_go_live.rs index f7cb0d9188..9261229a9a 100644 --- a/crates/registry-breg/tests/support/review_go_live.rs +++ b/crates/registry-breg/tests/support/review_go_live.rs @@ -25,6 +25,15 @@ async fn reviewed_fixture_with_recovery( authority: &Authority, automatic: bool, recovery_contract: bool, +) -> (client_http::ClientFixture, Value) { + reviewed_fixture_options(authority, automatic, recovery_contract, false).await +} + +async fn reviewed_fixture_options( + authority: &Authority, + automatic: bool, + recovery_contract: bool, + competing_action: bool, ) -> (client_http::ClientFixture, Value) { let mut source = registry_source(json!(policy())); source["actions"]["correct-name"]["execution"]["proposal"]["application"] = @@ -59,6 +68,21 @@ async fn reviewed_fixture_with_recovery( .unwrap() .push(json!("apply")); } + if competing_action { + let mut competing = source["actions"]["correct-name"].clone(); + competing["execution"]["proposal"]["review"] = json!({"type":"none"}); + competing["execution"]["proposal"]["application"] = json!({"mode":"manual"}); + source["actions"]["competing-name"] = competing; + let permissions = &mut source["accessProfiles"]["clerk"]["permissions"]; + for member in ["actions", "proposals"] { + let mut grant = permissions[member][0].clone(); + grant["action"] = json!("competing-name"); + if member == "proposals" { + grant["operations"] = json!(["get", "submit", "apply"]); + } + permissions[member].as_array_mut().unwrap().push(grant); + } + } let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); let registry = compile_project(&project, &[], CompileProfile::Authoring).unwrap(); let bindings = authority.registry.clone(); @@ -156,13 +180,21 @@ async fn approve( } async fn reconcile(fixture: &client_http::ClientFixture, accepted: &ReviewRequestAccepted) { + reconcile_with_result_id(fixture, accepted, Uuid::new_v4()).await; +} + +async fn reconcile_with_result_id( + fixture: &client_http::ClientFixture, + accepted: &ReviewRequestAccepted, + result_id: Uuid, +) { let mut client = fixture.pool.get_for_test().await.unwrap(); let tx = client.transaction().await.unwrap(); reconcile_result( &tx, AUTHORITY, accepted, - &result(accepted, Uuid::new_v4(), ReviewResultStatus::Approved), + &result(accepted, result_id, ReviewResultStatus::Approved), &fixture.mutations, ) .await @@ -601,6 +633,10 @@ async fn rollback_does_not_revive_cancelled_review_or_application() { successor["actions"]["correct-name"]["inputs"].as_array_mut().unwrap().push( json!({"id":"review-note","type":"string","maximumLength":32,"required":false,"classification":"internal"}), ); + successor["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] + .as_array_mut() + .unwrap() + .push(json!("review-note")); let (package, active) = proposal_activation::activate_with_compatibility( &fixture, &fixture.registry, @@ -703,6 +739,10 @@ async fn late_approval_after_rollback(finish_cancellation: bool, automatic: bool successor["actions"]["correct-name"]["inputs"].as_array_mut().unwrap().push( json!({"id":"review-note","type":"string","maximumLength":32,"required":false,"classification":"internal"}), ); + successor["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] + .as_array_mut() + .unwrap() + .push(json!("review-note")); let (package, active) = proposal_activation::activate_with_compatibility( &fixture, &fixture.registry, @@ -1163,6 +1203,10 @@ async fn failed_review_stays_withdrawn_after_rollback(accepted: bool) { successor["actions"]["correct-name"]["inputs"].as_array_mut().unwrap().push( json!({"id":"review-note","type":"string","maximumLength":32,"required":false,"classification":"internal"}), ); + successor["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] + .as_array_mut() + .unwrap() + .push(json!("review-note")); let (package, active) = proposal_activation::activate_with_compatibility( &fixture, &fixture.registry, @@ -1349,6 +1393,10 @@ async fn activated_automatic_proposal_preserves_requester_recovery(rollback: boo successor["actions"]["correct-name"]["inputs"].as_array_mut().unwrap().push( json!({"id":"review-note","type":"string","maximumLength":32,"required":false,"classification":"internal"}), ); + successor["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] + .as_array_mut() + .unwrap() + .push(json!("review-note")); let (mut package, mut active) = proposal_activation::activate_with_compatibility( &fixture, &fixture.registry, @@ -1607,8 +1655,71 @@ async fn activation_work_snapshot(client: &impl tokio_postgres::GenericClient) - } async fn activation_statement_counts(extra_pending: usize) -> Vec<(String, i64)> { - let authority = Authority::start(false, true).await; - let (fixture, source) = automatic_fixture(&authority).await; + let authority = Authority::start_with_results(false, true, [ResultReply::Approved; 2]).await; + let (fixture, source) = reviewed_fixture_options(&authority, true, false, true).await; + // A competing, approved application changes the frozen target through the + // public workflow before the older submission reaches its executor. + let versioned_proposal = submitted_proposal(&fixture, "batch-versioned-canary").await; + let client = &fixture.http.client; + let metadata = client.registry_contract(Some("clerk")).await.unwrap().value; + let action = metadata.select_action("competing-name", "clerk").unwrap(); + let mut input = versioned_proposal.input().unwrap().clone(); + input.insert("value".into(), json!("Competing")); + let competing = client + .start_proposal( + &action, + &BRegActionInvocationRequest::new(&action, input, None).unwrap(), + &BRegIdempotencyKey::parse("batch-competing-start").unwrap(), + ) + .await + .unwrap() + .value; + let competing = client + .execute_proposal( + &client + .prepare_proposal( + &competing, + "submit", + json!({}), + &BRegIdempotencyKey::parse("batch-competing-submit").unwrap(), + ) + .unwrap(), + ) + .await + .unwrap() + .value; + let applied = client.execute_proposal(&client.prepare_proposal(&competing,"apply", + json!({"submissionVersion":competing.submission_version(),"effectDigest":competing.effect_digest().unwrap()}), + &BRegIdempotencyKey::parse("batch-competing-apply").unwrap()).unwrap()).await.unwrap().value; + assert_eq!( + applied.state(), + registry_breg_client::BRegProposalState::Applied + ); + let versioned = Uuid::parse_str(versioned_proposal.id()).unwrap(); + let accepted = retained_binding(&fixture, versioned).await; + accept(&fixture, versioned, &accepted).await; + *authority.state.accepted.lock().unwrap() = Some(accepted.clone()); + reconcile_with_result_id(&fixture, &accepted, authority.state.result_id).await; + assert!(fixture + .mutations + .run_automatic_proposal_once_for_test() + .await + .unwrap()); + let blocked = client + .read_proposal(&versioned_proposal) + .await + .unwrap() + .value; + assert_eq!( + blocked.status(), + Some(registry_breg_client::BRegProposalStatus::AwaitingParty), + "application observation: {}", + serde_json::to_value(&blocked).unwrap()["applicationStatus"] + ); + assert_eq!( + serde_json::to_value(&blocked).unwrap()["applicationStatus"]["recovery"], + "rebase" + ); // Bound and unbound rounds exercise the same cases as ordinary withdrawal. // The counters are fixture-only; the native activation tests above separately // exercise the closed-catalog gate that intentionally refuses these triggers. @@ -1674,10 +1785,6 @@ async fn activation_statement_counts(extra_pending: usize) -> Vec<(String, i64)> // A fresh second submission leaves an older round and job behind. Only the // current round may be withdrawn, but every unfinished application must close. - let versioned = submitted(&fixture, "batch-versioned-canary").await; - let accepted = retained_binding(&fixture, versioned).await; - accept(&fixture, versioned, &accepted).await; - reconcile(&fixture, &accepted).await; let proposal = fixture .http .client @@ -1720,6 +1827,8 @@ async fn activation_statement_counts(extra_pending: usize) -> Vec<(String, i64)> .unwrap() .value; assert_eq!(current.submission_version(), 2); + // No public command revives an old job or review: forge orphaned history + // only to exercise activation's set-based cleanup of every version. fixture .database .admin @@ -1741,6 +1850,10 @@ async fn activation_statement_counts(extra_pending: usize) -> Vec<(String, i64)> successor["actions"]["correct-name"]["inputs"].as_array_mut().unwrap().push( json!({"id":"review-note","type":"string","maximumLength":32,"required":false,"classification":"internal"}), ); + successor["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] + .as_array_mut() + .unwrap() + .push(json!("review-note")); let project = parse_project_json(&serde_json::to_vec(&successor).unwrap()).unwrap(); let candidate = compile_project(&project, &[], CompileProfile::Authoring).unwrap(); let (mut admin, task) = fixture.database.connect_admin().await; diff --git a/crates/registry-breg/tests/task_grant_row_findings.rs b/crates/registry-breg/tests/task_grant_row_findings.rs index 1cf99fe509..a59c1622f6 100644 --- a/crates/registry-breg/tests/task_grant_row_findings.rs +++ b/crates/registry-breg/tests/task_grant_row_findings.rs @@ -49,7 +49,7 @@ fn project(rows: Value, classification: &str) -> Value { "actions":[ {"action":"relabel-note","operations":["invoke"],"targets":[{"recordType":"note","rowBoundaries":rows.clone()}],"results":["relabelled"]}, {"action":"correct-case","operations":["start"],"targets":[{"recordType":"case","rowBoundaries":rows.clone()}]}], - "proposals":[{"action":"correct-case","operations":["get","edit"],"ownership":"caller","targets":[{"recordType":"case","rowBoundaries":rows}]}]}} + "proposals":[{"action":"correct-case","operations":["get","edit"],"ownership":"caller","readableInputs":["case-ref","new-label"],"targets":[{"recordType":"case","rowBoundaries":rows}]}]}} } }) } @@ -123,6 +123,10 @@ fn public_record_types_and_standing_profiles_draw_no_finding() { .expect("action permissions") .remove(0); permissions["proposals"][0]["operations"] = json!(["edit"]); + permissions["proposals"][0] + .as_object_mut() + .expect("proposal grant") + .remove("readableInputs"); let registry = compile(&standing); assert_eq!(unbound_paths(®istry), Vec::::new()); } diff --git a/crates/registry-bregctl/src/explain_report.rs b/crates/registry-bregctl/src/explain_report.rs index 51cef5e916..93033c46fe 100644 --- a/crates/registry-bregctl/src/explain_report.rs +++ b/crates/registry-bregctl/src/explain_report.rs @@ -593,6 +593,16 @@ fn lifecycle(value: &Value, lines: &mut Lines) { &format!("turn {}: {}", text(&turn["turn"]), text(&turn["condition"])), ); } + for status in items(&state["statuses"]) { + lines.listed( + 2, + &format!( + "status {}: {}", + text(&status["status"]), + text(&status["condition"]) + ), + ); + } } lines.heading("Transitions:"); for transition in items(&lifecycle["transitions"]) { @@ -732,6 +742,14 @@ mod tests { "submitted", "turn official:", "turn nobody:", + "status draft:", + "status awaiting-party:", + "status in-review:", + "status approved:", + "status processing:", + "status applied:", + "status rejected:", + "status cancelled:", "Transitions:", "recovers", "dependency-outage", diff --git a/crates/registry-bregctl/src/hook_lifecycle.rs b/crates/registry-bregctl/src/hook_lifecycle.rs index b1c1ab0fbb..2fbe2e93ea 100644 --- a/crates/registry-bregctl/src/hook_lifecycle.rs +++ b/crates/registry-bregctl/src/hook_lifecycle.rs @@ -169,14 +169,18 @@ pub(crate) fn sample( Transition::Edited => ("draft", "draft", "party"), Transition::Submitted => ("draft", "submitted", "official"), Transition::Revised | Transition::Rebased => ("submitted", "draft", "party"), - Transition::Retried => ("submitted", "submitted", "official"), + Transition::Retried | Transition::Added | Transition::Answered => { + ("submitted", "submitted", "official") + } Transition::Cancelled => ("draft", "cancelled", "nobody"), Transition::Applied => ("submitted", "applied", "nobody"), Transition::Rejected => ("submitted", "rejected", "nobody"), - Transition::ReviewReturned => ("submitted", "submitted", "party"), + Transition::ReviewReturned | Transition::Asked => { + ("submitted", "submitted", "party") + } }; let authority_kind = match transition { - Transition::Rejected | Transition::ReviewReturned => "review", + Transition::Rejected | Transition::ReviewReturned | Transition::Asked => "review", _ => "caller", }; ( diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index 85868684d6..03b7b342dc 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -9515,7 +9515,7 @@ const EVENTS_EXPLANATION: ExplainFormat = ExplainFormat { kind: "BRegEventsExplanation", }; const LIFECYCLE_EXPLANATION: ExplainFormat = ExplainFormat { - api_version: "id.registrystack.org/formats/breg/lifecycle-explanation/v1alpha8", + api_version: "id.registrystack.org/formats/breg/lifecycle-explanation/v1alpha9", kind: "BRegLifecycleExplanation", }; diff --git a/crates/registry-bregctl/tests/explain_contract.rs b/crates/registry-bregctl/tests/explain_contract.rs index 84dc603246..44fcf9a3c0 100644 --- a/crates/registry-bregctl/tests/explain_contract.rs +++ b/crates/registry-bregctl/tests/explain_contract.rs @@ -59,7 +59,7 @@ fn envelope(contract: &str) -> (&'static str, &'static str) { "BRegEventsExplanation", ), "LifecycleExplanation" => ( - "id.registrystack.org/formats/breg/lifecycle-explanation/v1alpha8", + "id.registrystack.org/formats/breg/lifecycle-explanation/v1alpha9", "BRegLifecycleExplanation", ), _ => panic!("unknown contract {contract}"), @@ -650,6 +650,12 @@ fn explain_events_matches_contract() { #[test] fn explain_lifecycle_matches_contract() { let report = explain_lifecycle_report(); + assert_eq!( + report["explanation"]["apiVersion"], + "id.registrystack.org/formats/breg/lifecycle-explanation/v1alpha9" + ); + let submitted = &report["explanation"]["lifecycles"][0]["states"][1]; + assert_eq!(submitted["statuses"].as_array().unwrap().len(), 4); assert_matches_contract("lifecycle", "LifecycleExplanation", &report["explanation"]); } diff --git a/crates/registry-casework-breg/src/lib.rs b/crates/registry-casework-breg/src/lib.rs index 2a3e21dfe4..ce2738b6c4 100644 --- a/crates/registry-casework-breg/src/lib.rs +++ b/crates/registry-casework-breg/src/lib.rs @@ -186,7 +186,8 @@ impl BregContextProvider { ) -> Result { self.validate_identity(identity)?; let binding = self.read_binding(client, profile, display).await?; - self.read_bound(client, identity, &binding, display).await + self.read_bound(client, identity, &binding, display, display) + .await } fn validate_identity( @@ -243,6 +244,7 @@ impl BregContextProvider { identity: &ReviewContextIdentity, binding: &BRegProposalReviewBinding, display: bool, + include_answers: bool, ) -> Result { if identity.contract != self.export.contract || identity.subject.source != self.export.source_namespace @@ -250,18 +252,24 @@ impl BregContextProvider { { return Err(ReviewContextError::ContractChanged); } - let document = client - .read_proposal_review_by_id(binding, &identity.subject.id) - .await - .map_err(|error| match error { - // A context reply without the owning closed contract is not - // the interface this paired provider was authorized to use. - BaseRegistryClientError::InvalidRequest { .. } if display => { - ReviewContextError::ContractChanged - } - error => map_error(error), - })? - .value; + let document = if include_answers { + client + .read_proposal_review_by_id(binding, &identity.subject.id) + .await + } else { + client + .read_proposal_review_by_id_without_answers(binding, &identity.subject.id) + .await + } + .map_err(|error| match error { + // A context reply without the owning closed contract is not + // the interface this paired provider was authorized to use. + BaseRegistryClientError::InvalidRequest { .. } if display => { + ReviewContextError::ContractChanged + } + error => map_error(error), + })? + .value; self.validate_bound(identity, document) } @@ -430,8 +438,22 @@ impl BregContextProvider { { return Err(ReviewContextError::Invalid); } + let mut answers = std::collections::BTreeMap::new(); + for ask in document.context.asks { + if let Some(answer) = ask.answer { + let id = uuid::Uuid::parse_str(&ask.id).map_err(|_| ReviewContextError::Invalid)?; + let answer = serde_json::from_value( + serde_json::to_value(answer).map_err(|_| ReviewContextError::Invalid)?, + ) + .map_err(|_| ReviewContextError::Invalid)?; + if answers.insert(id, answer).is_some() { + return Err(ReviewContextError::Invalid); + } + } + } let display_reference = Some(document.context.reference); Ok(HumanDisplayObservation { + answers, identity: identity.clone(), reviewable: document.reviewable, display_reference, @@ -456,8 +478,18 @@ impl ReviewContextProvider for BregContextProvider { let token = BearerToken::new(request.credential.expose().to_owned()) .map_err(|_| ReviewContextError::Denied)?; let client = self.client.with_bearer_token(token); + self.validate_identity(request.identity)?; + let binding = self + .read_binding(&client, request.source_profile_id, true) + .await?; let document = self - .read(&client, request.identity, request.source_profile_id, true) + .read_bound( + &client, + request.identity, + &binding, + true, + request.include_answers, + ) .await?; self.display_observation(request.identity, document) } @@ -502,7 +534,9 @@ impl ReviewContextProvider for BregContextProvider { let document = self .read(&client, request.identity, request.source_profile_id, true) .await?; - self.display_observation(request.identity, document) + let mut view = self.display_observation(request.identity, document)?; + view.answers.clear(); + Ok(view) } async fn delegated_display_batch( &self, @@ -530,6 +564,14 @@ impl ReviewContextProvider for BregContextProvider { let client = self.client.with_bearer_token(token); self.display_batch_with_client(identities, source_profile_id, &client) .await + .into_iter() + .map(|result| { + result.map(|mut observation| { + observation.answers.clear(); + observation + }) + }) + .collect() } async fn service_status( &self, diff --git a/crates/registry-casework-breg/tests/context_provider.rs b/crates/registry-casework-breg/tests/context_provider.rs index c6932ffc07..e0d35cf323 100644 --- a/crates/registry-casework-breg/tests/context_provider.rs +++ b/crates/registry-casework-breg/tests/context_provider.rs @@ -197,6 +197,45 @@ fn provider(server: &MockServer, export: BregContextExport) -> BregContextProvid .unwrap(); BregContextProvider::new("provider".into(), export, client, "status".into()).unwrap() } +#[tokio::test] +async fn preflight_omits_answers_and_only_display_opts_in_under_the_same_human_bearer() { + let server = MockServer::start().await; + let export = export(); + let identity = identity(&export); + let provider = provider(&server, export); + mocks(&server, "reviewer", "human-bearer", true, DIGEST).await; + for include_answers in [false, true] { + let observed = provider + .human_display(HumanDisplayRequest { + identity: &identity, + source_profile_id: "reviewer", + credential: EphemeralCredential::new("human-bearer"), + include_answers, + }) + .await + .unwrap(); + assert!(observed.answers.is_empty()); + assert_eq!(observed.fields["reference"], "REF-42"); + } + let requests = server.received_requests().await.unwrap(); + let contexts: Vec<_> = requests + .iter() + .filter(|r| r.url.path().ends_with("/review-context")) + .collect(); + assert_eq!(contexts.len(), 2); + assert!(!contexts[0] + .url + .query_pairs() + .any(|(key, _)| key == "include")); + assert!(contexts[1] + .url + .query_pairs() + .any(|(key, value)| key == "include" && value == "answers")); + assert!(contexts + .iter() + .all(|r| r.headers["authorization"] == "Bearer human-bearer")); +} + #[tokio::test] async fn human_display_uses_exact_caller_bearer_and_status_discloses_no_values() { let server = MockServer::start().await; @@ -207,6 +246,7 @@ async fn human_display_uses_exact_caller_bearer_and_status_discloses_no_values() mocks(&server, "status", "status-bearer", false, DIGEST).await; let display = provider .human_display(HumanDisplayRequest { + include_answers: true, identity: &identity, source_profile_id: "reviewer", credential: EphemeralCredential::new("human-bearer"), @@ -250,6 +290,7 @@ async fn unrelated_registry_revision_change_preserves_the_exact_context_contract .await; let display = provider .human_display(HumanDisplayRequest { + include_answers: true, identity: &identity, source_profile_id: "reviewer", credential: EphemeralCredential::new("human-bearer"), @@ -376,6 +417,7 @@ async fn canonical_document_fields_roundtrip_with_human_bearer_without_fetching_ let provider = provider(&server, export); let displayed = provider .human_display(HumanDisplayRequest { + include_answers: true, identity: &identity, source_profile_id: "proposal-reviewer", credential: EphemeralCredential::new("human-bearer"), @@ -437,6 +479,7 @@ async fn missing_or_changed_producer_contract_refuses_without_releasing_fields() assert_eq!( provider .human_display(HumanDisplayRequest { + include_answers: true, identity: &identity, source_profile_id: "reviewer", credential: EphemeralCredential::new("human-bearer"), @@ -516,6 +559,7 @@ async fn changed_request_source_type_or_contract_refuses_before_source_io() { assert_eq!( provider .human_display(HumanDisplayRequest { + include_answers: true, identity: &identity, source_profile_id: "reviewer", credential: EphemeralCredential::new("human-bearer"), @@ -573,6 +617,7 @@ async fn changed_observed_action_or_subject_refuses_the_exact_binding() { assert_eq!( provider .human_display(HumanDisplayRequest { + include_answers: true, identity: &identity, source_profile_id: "reviewer", credential: EphemeralCredential::new("human-bearer"), @@ -611,6 +656,7 @@ async fn current_metadata_must_advertise_the_exact_profile_action_and_purpose() assert_eq!( provider .human_display(HumanDisplayRequest { + include_answers: true, identity: &identity, source_profile_id: "reviewer", credential: EphemeralCredential::new("human-bearer"), @@ -659,6 +705,7 @@ async fn current_row_disclosure_refusal_never_falls_back_to_service_credentials( assert_eq!( provider .human_display(HumanDisplayRequest { + include_answers: true, identity: &identity, source_profile_id: "reviewer", credential: EphemeralCredential::new("human-bearer"), @@ -700,6 +747,7 @@ async fn display_fields_must_match_the_exported_schema() { assert_eq!( provider .human_display(HumanDisplayRequest { + include_answers: true, identity: &identity, source_profile_id: "reviewer", credential: EphemeralCredential::new("human-bearer"), @@ -851,3 +899,54 @@ async fn batch_refuses_substitution_and_preserves_per_item_concealment() { } } } + +#[tokio::test] +async fn intrinsic_answers_are_validated_and_transported_beside_authored_fields_under_the_human_bearer( +) { + let server = MockServer::start().await; + let export = export(); + let identity = identity(&export); + let provider = provider(&server, export.clone()); + mocks(&server, "reviewer", "human-bearer", true, DIGEST).await; + let ask = uuid::Uuid::from_u128(7); + let file = uuid::Uuid::from_u128(8); + let download=format!("/v1/proposals/{ID}/additions/{file}?submissionVersion=1&reviewAskId={ask}&effectDigest={}&contextSchemaDigest={}",DIGEST.replace(':',"%3A"),export.contract.schema_digest.as_str().replace(':',"%3A")); + let answer = json!({"text":"source answer stays live","documents":[{"id":file,"sha256":"b".repeat(64),"contentType":"text/plain","byteSize":5,"verificationStatus":"approved","download":{"method":"GET","operation":"get-review-context","accessProfile":"reviewer","path":download}}],"answeredAt":"2026-11-27T01:00:00Z"}); + Mock::given(method("GET")).and(path(format!("/v1/proposals/{ID}/review-context"))).and(query_param("accessProfile","reviewer")).and(header("authorization","Bearer human-bearer")).respond_with(response(json!({"id":ID,"actionId":"correct-address","actionRevision":DIGEST,"submissionVersion":1,"revision":2,"effectDigest":DIGEST,"authority":"provider","policy":{"id":"check","version":"1","digest":DIGEST},"subject":{"source":"source","subjectType":"proposal","id":ID,"version":"1","digest":DIGEST},"context":{"reference":"native-proposal","contract":export.contract,"fields":{"reference":"REF-42"},"asks":[{"id":ask,"text":"Why?","wants":[{"kind":"answer"}],"askedAt":"2026-11-27T00:00:00Z","state":"answered","answer":answer}]},"reviewable":true}))).with_priority(1).mount(&server).await; + let display = provider + .human_display(HumanDisplayRequest { + include_answers: true, + identity: &identity, + source_profile_id: "reviewer", + credential: EphemeralCredential::new("human-bearer"), + }) + .await + .expect("closed authored schema does not consume intrinsic answers"); + let unsolicited = provider + .human_display(HumanDisplayRequest { + include_answers: false, + identity: &identity, + source_profile_id: "reviewer", + credential: EphemeralCredential::new("human-bearer"), + }) + .await; + assert!( + unsolicited.is_err(), + "a preflight response must not smuggle unsolicited answers through the client" + ); + assert_eq!( + display.fields, + std::collections::BTreeMap::from([("reference".into(), json!("REF-42"))]) + ); + assert_eq!(display.answers.len(), 1); + assert_eq!( + serde_json::to_value(&display.answers[&ask]).unwrap(), + answer + ); + assert!(server + .received_requests() + .await + .unwrap() + .iter() + .all(|request| request.headers.get("authorization").unwrap() == "Bearer human-bearer")); +} diff --git a/crates/registry-casework-breg/tests/support/peer_version.rs b/crates/registry-casework-breg/tests/support/peer_version.rs index 7603eaf69c..3c49e2d7de 100644 --- a/crates/registry-casework-breg/tests/support/peer_version.rs +++ b/crates/registry-casework-breg/tests/support/peer_version.rs @@ -49,6 +49,7 @@ async fn read_peer( peer_metadata(&server, version, malformed).await; let result = provider .human_display(HumanDisplayRequest { + include_answers: true, identity: &identity, source_profile_id: "reviewer", credential: EphemeralCredential::new("human-bearer"), diff --git a/crates/registry-casework-client-node/__test__/ask-limit.test.js b/crates/registry-casework-client-node/__test__/ask-limit.test.js new file mode 100644 index 0000000000..59a59e9763 --- /dev/null +++ b/crates/registry-casework-client-node/__test__/ask-limit.test.js @@ -0,0 +1,39 @@ +'use strict'; +const assert = require('node:assert/strict'); +const http = require('node:http'); +const { test } = require('node:test'); +const { CaseworkClient } = require('../client'); + +test('the ask limit exposes its safe problem detail and is never retried', async () => { + let attempts = 0; + const detail = 'This review request has reached its limit of 50 asks. Continue the review without opening another ask.'; + const server = http.createServer(async (request, response) => { + for await (const chunk of request) { assert.ok(chunk.length); } + attempts += 1; + response.writeHead(409, { + 'content-type': 'application/problem+json', + traceparent: '00-0123456789abcdef0123456789abcdef-0123456789abcdef-01', + }); + response.end(JSON.stringify({ + type: 'https://id.registrystack.org/problems/registry-casework/review/ask-limit-reached', + title: 'Review ask limit reached', status: 409, detail, + code: 'review.ask-limit-reached', traceId: '0123456789abcdef0123456789abcdef', + })); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + const client = new CaseworkClient({baseUrl: `http://127.0.0.1:${server.address().port}/`}); + await assert.rejects( + client.askApplicant('synthetic-token', 'staff', '00000000-0000-4000-8000-000000000001', 2, 'ask-51', {text: 'Why?', wants: []}), + error => { + assert.equal(error.kind, 'problem'); + assert.equal(error.code, 'review.ask-limit-reached'); + assert.equal(error.detail, detail); + return true; + }, + ); + assert.equal(attempts, 1); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); diff --git a/crates/registry-casework-client-node/__test__/ask-timing.test-d.ts b/crates/registry-casework-client-node/__test__/ask-timing.test-d.ts new file mode 100644 index 0000000000..315a3b1f11 --- /dev/null +++ b/crates/registry-casework-client-node/__test__/ask-timing.test-d.ts @@ -0,0 +1,13 @@ +import type { ReviewClockOccurrence, ReviewContextAsk, ReviewPolicyClosure, ReviewStageAsksPolicy, ReviewTaskMarker } from '../client' + +const marker: ReviewTaskMarker = 'expired' +const state: ReviewClockOccurrence['state'] = 'paused' +const asks: ReviewStageAsksPolicy = { answerWithin: { hours: 48 }, onDue: 'return-to-reviewer', pauseClocks: true } +const resubmission: ReviewPolicyClosure['resubmission'] = 'resume-at-returning-stage' +void marker; void state; void asks; void resubmission +const dueAt: ReviewContextAsk['dueAt'] = '2026-11-27T01:00:00Z' +void dueAt + +// @ts-expect-error expiry does not authorise an automatic decision +const unsupported: ReviewStageAsksPolicy = { onDue: 'approve' } +void unsupported diff --git a/crates/registry-casework-client-node/__test__/facade.test-d.ts b/crates/registry-casework-client-node/__test__/facade.test-d.ts index 33e2c5f695..356d9099ae 100644 --- a/crates/registry-casework-client-node/__test__/facade.test-d.ts +++ b/crates/registry-casework-client-node/__test__/facade.test-d.ts @@ -1,6 +1,7 @@ +import './ask-timing.test-d' import { CaseworkClient, CaseworkClientError, submissionDigest, type ContentDigest, type SubjectBinding, type PolicyBinding, type ReviewCreateRequest, type ReviewRequestAccepted, - type ReviewTask, type SupervisoryReviewTask, type StaffingDiagnostic, type ReviewTaskDecisionRequest, type ReviewStaffingQuery, + type ReviewTask, type SupervisoryReviewTask, type StaffingDiagnostic, type ReviewTaskDecisionRequest, type ReviewStaffingQuery, type ReviewTaskMarker, type ReviewCaseloadMoveRequest, type ReviewClockRecomputeRequest, type ReviewPolicyClosure, type ReviewStagePolicy, type RoutingRule } from '../client' const client = new CaseworkClient({ baseUrl: 'https://casework.example.test/', attemptTimeoutMilliseconds: 1500, maximumResponseBytes: 1500, maximumMutationRetries: 0 }) @@ -58,6 +59,7 @@ const decision: ReviewTaskDecisionRequest = { decision: { type: 'approve', outco const bareApproval: ReviewTaskDecisionRequest = { decision: { type: 'approve' } } void bareApproval void client.decideReviewTask(token, profile, id, 2, 'decision-1', decision) +void client.askApplicant(token, profile, id, 2, 'ask-1', { text: 'Send the signed form.', wants: [{ kind: 'answer' }] }).then(({ value }) => { const marker: ReviewTaskMarker | undefined = value.task.marker; void marker }) void client.reviewHistory(token, profile, id, { limit: 25 }) void client.ownReviewDecisions(token, profile, { limit: 25 }) void client.supervisoryReviewTasks(token, 'supervisor', { requestId: id, limit: 25 }) @@ -120,3 +122,6 @@ void client.previewReviewTaskTemplates(token, profile, { taskId: id, sourceCrede void client.reviewTasks(token, profile, undefined, undefined, { token: 'source' }) // @ts-expect-error credentials are opaque strings, not decoded claim objects void client.reviewTasks(token, profile, undefined, undefined, { sourceProfile: 'source-reader', token: { sub: 'person' } }) + +const liveAnswer: import("../client").ReviewContextAnswer = { text: "Why", documents: [], answeredAt: "2026-11-27T00:00:00Z" } +void liveAnswer diff --git a/crates/registry-casework-client-node/__test__/facade.test.js b/crates/registry-casework-client-node/__test__/facade.test.js index 8c5c7ca924..d5da8d8edc 100644 --- a/crates/registry-casework-client-node/__test__/facade.test.js +++ b/crates/registry-casework-client-node/__test__/facade.test.js @@ -189,6 +189,7 @@ test('review task context uses the exact route and forwards the optional source source: 'professional-licences', type: 'change-request', id: 'correction-42', version: '1', digest: `sha256:${'a'.repeat(64)}`, }, + asks: [{"askId": "00000000-0000-4000-8000-000000000007", "taskId": "00000000-0000-0000-0000-000000000000", "text": "Why?", "wants": [{"kind": "answer"}], "askedAt": "2026-11-27T00:00:00Z", "state": "open", "answer": {"text": "source answer from BReg", "documents": [], "answeredAt": "2026-11-27T01:00:00Z"}}], requesterReference: 'correction-42', policy: { id: 'registry-correction', version: '1', digest: POLICY_DIGEST }, policyClosure: { @@ -228,6 +229,7 @@ test('review task context uses the exact route and forwards the optional source 'reviewer', ); + assert.deepEqual(result.value.asks[0].answer, {"text": "source answer from BReg", "documents": [], "answeredAt": "2026-11-27T01:00:00Z"}); assert.equal(result.value.context.projection.displayReference, 'Correction 42'); assert.equal(observed.path, '/v1/review-tasks/00000000-0000-0000-0000-000000000000/context'); assert.equal(observed.headers.authorization, 'Bearer one-call-secret'); diff --git a/crates/registry-casework-client-node/__test__/staffing.test.js b/crates/registry-casework-client-node/__test__/staffing.test.js index c0c048449c..39dcecc808 100644 --- a/crates/registry-casework-client-node/__test__/staffing.test.js +++ b/crates/registry-casework-client-node/__test__/staffing.test.js @@ -65,6 +65,30 @@ test('partial selectors, duplicate clock tasks, and invalid preview IDs fail bef ]) await assert.rejects(call, error => error.kind === 'invalid-request' && !error.message.includes('private-canary')); assert.equal(requests.length, 0); }); +test('askApplicant sends the ask under the revision and checks the waiting task', async t => { + const waiting = { ...task, state: { held: { holder: { issuer: 'https://issuer.example', subject: 'staff-1' } } }, revision: 3, marker: 'waiting' }; + const ask = { askId: previewId, requestId: previewId, subject, text: 'Send the signed form.', wants: [{ kind: 'answer' }], askedAt: '2026-10-14T00:00:00Z', state: 'open' }; + const { client, requests } = await fixture(t, () => ({ task: waiting, ask })); + const body = { text: 'Send the signed form.', wants: [{ kind: 'answer' }] }; + const asked = await client.askApplicant('staff-token', 'staff', id, 2, 'ask-1', body); + assert.equal(asked.value.task.marker, 'waiting'); + assert.equal(asked.value.ask.state, 'open'); + assert.equal(requests[0].path, `/tenant/v1/review-tasks/${id}/asks`); + assert.equal(requests[0].headers['if-match'], '"2"'); + assert.equal(requests[0].headers['idempotency-key'], 'ask-1'); + assert.deepEqual(requests[0].body, body); + for (const call of [ + () => client.askApplicant('staff-token', 'staff', id, 2, 'ask-2', { text: '', wants: [] }), + () => client.askApplicant('staff-token', 'staff', id, 2, 'ask-3', { text: 'x', wants: [{ kind: 'answer' }, { kind: 'answer' }] }), + () => client.askApplicant('staff-token', 'staff', id, 2, 'ask-4', { text: 'x', wants: [], extra: true }), + ]) await assert.rejects(call, error => error.kind === 'invalid-request'); + assert.equal(requests.length, 1); +}); +test('askApplicant refuses a response that did not mark the task waiting', async t => { + const ask = { askId: previewId, requestId: previewId, subject, text: 'x', wants: [], askedAt: '2026-10-14T00:00:00Z', state: 'open' }; + const { client } = await fixture(t, () => ({ task: { ...task, revision: 3 }, ask })); + await assert.rejects(() => client.askApplicant('staff-token', 'staff', id, 2, 'ask-1', { text: 'x', wants: [] }), error => error.kind === 'protocol'); +}); test('staffing responses cannot substitute another subject or reference', async t => { const { client } = await fixture(t, () => task); await assert.rejects(() => client.nextReviewTask('staff-token', 'staff', { subjectSource: subject.source, subjectType: subject.type, subjectId: 'another', subjectVersion: subject.version, subjectDigest: subject.digest }), error => error.kind === 'protocol'); diff --git a/crates/registry-casework-client-node/client.d.ts b/crates/registry-casework-client-node/client.d.ts index 59aaecf02e..58df0dc542 100644 --- a/crates/registry-casework-client-node/client.d.ts +++ b/crates/registry-casework-client-node/client.d.ts @@ -146,6 +146,13 @@ export type KnownCaseworkProblemCode = | 'request.unprocessable' | 'request.unsupported-media-type' | 'review.distinct-approver-required' + | 'review.ask-already-open' + | 'review.ask-answer-time-invalid' + | 'review.ask-limit-reached' + | 'review.ask-not-offered' + | 'review.ask-not-open' + | 'review.ask-producer-unsupported' + | 'review.ask-task-inactive' | 'review.initiator-excluded' | 'review.initiator-required' | 'review.query-too-broad' @@ -268,7 +275,8 @@ export type ReviewCancelResponse = export interface ReviewPageQuery { cursor?: Uuid; limit?: SafeInteger } export type ReviewTaskOwnership = 'assigned-to-me' | 'unclaimed' export type ReviewTaskSort = 'due' | 'subject' | 'reference' -export interface ReviewStaffingPageQuery { queue?: string; ownership?: ReviewTaskOwnership; reference?: string; sort?: ReviewTaskSort; cursor?: Uuid; limit?: SafeInteger } +export type ReviewTaskMarker = 'waiting' | 'answered' | 'expired' +export interface ReviewStaffingPageQuery { queue?: string; ownership?: ReviewTaskOwnership; marker?: ReviewTaskMarker; reference?: string; sort?: ReviewTaskSort; cursor?: Uuid; limit?: SafeInteger } /** A subject selector is absent or names every component of its immutable binding. */ export type ReviewStaffingQuery = ReviewStaffingPageQuery & ( | { subjectSource?: never; subjectType?: never; subjectId?: never; subjectVersion?: never; subjectDigest?: never } @@ -310,6 +318,7 @@ export interface ReviewTask { staffingDiagnostic?: StaffingDiagnostic decidedByCaller?: boolean decisionReceipt?: ReviewDecisionReceipt + marker?: ReviewTaskMarker } export interface ReviewTaskPage { items: ReadonlyArray; nextCursor?: Uuid; status: PageStatus } export type SupervisoryReviewTaskState = 'open' | 'held' | 'decided' @@ -328,6 +337,52 @@ export interface ReviewSourceProjection { binding: SubjectBinding; displayRefere export type ReviewTaskContextData = | { mode: 'submitted'; snapshot: Readonly> } | { mode: 'current-source'; reference: string; bindingStatus: ReviewSourceBindingStatus; projection?: ReviewSourceProjection } +export type ReviewAskWant = { kind: 'answer' } | { kind: 'document' } +export type ReviewAskState = 'open' | 'answered' | 'expired' | 'closed' +export interface ReviewTaskAskRequest { text: string; wants: ReadonlyArray } +export interface ReviewAsk { + askId: Uuid + requestId: Uuid + subject: SubjectBinding + text: string + wants: ReadonlyArray + askedAt: string + dueAt?: string + state: ReviewAskState + answeredAt?: string + closedAt?: string +} +export interface ReviewTaskAsked { task: ReviewTask; ask: ReviewAsk } +export interface ReviewAnswerDownload { + method: 'GET' + operation: string + accessProfile: string + path: string +} +export interface ReviewAnswerDocument { + id: string + sha256: string + contentType: string + byteSize: number + verificationStatus?: string + download?: ReviewAnswerDownload +} +export interface ReviewContextAnswer { + text?: string + documents: ReadonlyArray + answeredAt: string +} +export interface ReviewContextAsk { + askId: Uuid + taskId: Uuid + text: string + wants: ReadonlyArray + askedAt: string + dueAt?: string + state: ReviewAskState + answeredAt?: string + answer?: ReviewContextAnswer +} export interface ReviewTaskContext { taskId: Uuid requestId: Uuid @@ -337,6 +392,7 @@ export interface ReviewTaskContext { policyClosure: ReviewPolicyClosure resultConstraints?: JsonObject context: ReviewTaskContextData + asks?: ReadonlyArray } export type ReviewClockCorrelation = | { scope: 'subject'; source: string; subjectType: string; id: string } @@ -346,7 +402,7 @@ export interface ReviewClockOccurrence { clockId: string requestId: Uuid correlation: ReviewClockCorrelation - state: 'running' | 'completed' | 'cancelled' | 'source-facts-missing' + state: 'running' | 'paused' | 'completed' | 'cancelled' | 'source-facts-missing' policyDigest: ContentDigest anchorAt: string dueAt?: string @@ -370,14 +426,16 @@ export interface ReviewAccountabilityRecord { occurredAt: string; retainedUntil: string decisionReceipt?: ReviewDecisionReceipt } -export interface ReviewStagePolicy { id: string; label?: string; publicProgressCode?: string; queue: string; decidingProfiles: ReadonlyArray; requiredApprovals: SafeInteger; outcomes?: ReadonlyArray; negativeDecisions?: 'settle' | 'advise'; excludeInitiator?: boolean; excludePreviousStageReviewers?: boolean } +export interface ReviewStageAsksPolicy { answerWithin?: ElapsedDuration; onDue?: 'return-to-reviewer'; pauseClocks?: boolean } +export interface ReviewStagePolicy { id: string; label?: string; publicProgressCode?: string; queue: string; decidingProfiles: ReadonlyArray; requiredApprovals: SafeInteger; outcomes?: ReadonlyArray; negativeDecisions?: 'settle' | 'advise'; asks?: ReviewStageAsksPolicy; excludeInitiator?: boolean; excludePreviousStageReviewers?: boolean } export interface ReviewRetentionPolicy { terminalRetentionDays: SafeInteger; accountabilityRetentionDays: SafeInteger } export interface ReviewContextContract { id: string; revision: ContentDigest; schemaDigest: ContentDigest } export type ReviewContextPolicy = { mode: 'submitted' } | { mode: 'current-source'; provider: string; contract: ReviewContextContract } export type ReviewContextCapability = 'human-display' | 'service-status' | 'task-grant-context' | 'routing-context' export interface ReviewContextProviderPolicy { id: string; capabilities: ReadonlyArray; sourceNamespace: string; deploymentRef: string; serviceProfiles?: Partial> } -export interface ReviewPolicy { id: string; label?: string; version: string; purpose: 'approval' | 'answer'; context: ReviewContextPolicy; routing?: ReadonlyArray; stages: ReadonlyArray; clocks?: ReadonlyArray; retention: ReviewRetentionPolicy; displaySchema: JsonValue; resultSchema?: JsonValue; outcomes?: ReadonlyArray<{ id: string; label: string; settlement: 'approved' | 'rejected' | 'changes-requested' | 'answered'; reasonRequired: boolean; publicReason: 'required' | 'optional' | 'none'; resultRequired?: boolean }> } +export interface ReviewPolicy { id: string; label?: string; version: string; purpose: 'approval' | 'answer'; resubmission?: 'first-stage' | 'resume-at-returning-stage'; context: ReviewContextPolicy; routing?: ReadonlyArray; stages: ReadonlyArray; clocks?: ReadonlyArray; retention: ReviewRetentionPolicy; displaySchema: JsonValue; resultSchema?: JsonValue; outcomes?: ReadonlyArray<{ id: string; label: string; settlement: 'approved' | 'rejected' | 'changes-requested' | 'answered'; reasonRequired: boolean; publicReason: 'required' | 'optional' | 'none'; resultRequired?: boolean }> } export interface ReviewPolicyClosure { + resubmission?: 'first-stage' | 'resume-at-returning-stage' identity: PolicyBinding label?: string purpose: 'approval' | 'answer' @@ -423,6 +481,7 @@ export class CaseworkClient { reviewTaskDraft(token: string, profile: string, taskId: Uuid, sourceProfile?: string, sourceCredential?: HumanSourceCredential | null): Promise> saveReviewTaskDraft(token: string, profile: string, taskId: Uuid, expectedRevision: SafeInteger, idempotencyKey: string, draft: ReviewTaskDraftInput, sourceProfile?: string, sourceCredential?: HumanSourceCredential | null): Promise> deleteReviewTaskDraft(token: string, profile: string, taskId: Uuid, expectedRevision: SafeInteger, idempotencyKey: string, sourceProfile?: string, sourceCredential?: HumanSourceCredential | null): Promise> + askApplicant(token: string, profile: string, taskId: Uuid, expectedRevision: SafeInteger, idempotencyKey: string, ask: ReviewTaskAskRequest, sourceProfile?: string | null, sourceCredential?: HumanSourceCredential | null): Promise> decideReviewTask(token: string, profile: string, taskId: Uuid, expectedRevision: SafeInteger, idempotencyKey: string, decision: ReviewTaskDecisionRequest, sourceProfile?: string | null, sourceCredential?: HumanSourceCredential | null): Promise> reviewHistory(token: string, profile: string, requestId: Uuid, query?: ReviewPageQuery | null, sourceProfile?: string | null, sourceCredential?: HumanSourceCredential | null): Promise> addReviewNote(token: string, profile: string, requestId: Uuid, idempotencyKey: string, note: ReviewNoteRequest, sourceProfile?: string | null, sourceCredential?: HumanSourceCredential | null): Promise> diff --git a/crates/registry-casework-client-node/client.js b/crates/registry-casework-client-node/client.js index b77a9d875d..a278b99483 100644 --- a/crates/registry-casework-client-node/client.js +++ b/crates/registry-casework-client-node/client.js @@ -165,7 +165,7 @@ function humanSourceCredentialValue(value) { return source; } -const sourceCredentialIndexes = new Map([["nextReviewTask", 4], ["reviewTasks", 4], ["supervisoryReviewTasks", 4], ["ownReviewDecisions", 4], ["reviewTask", 4], ["reviewTaskContext", 4], ["approveReviewTaskGrant", 7], ["claimReviewTask", 6], ["assignReviewTask", 7], ["delegateReviewTask", 7], ["reviewTaskDraft", 4], ["saveReviewTaskDraft", 7], ["deleteReviewTaskDraft", 6], ["decideReviewTask", 7], ["reviewHistory", 5], ["addReviewNote", 6], ["reviewClocks", 4], ["reviewTaskHoldings", 4], ["previewClockRecompute", 3], ["applyClockRecompute", 4], ["previewCaseloadMove", 4], ["applyCaseloadMove", 5]]); +const sourceCredentialIndexes = new Map([["nextReviewTask", 4], ["reviewTasks", 4], ["supervisoryReviewTasks", 4], ["ownReviewDecisions", 4], ["reviewTask", 4], ["reviewTaskContext", 4], ["approveReviewTaskGrant", 7], ["claimReviewTask", 6], ["assignReviewTask", 7], ["delegateReviewTask", 7], ["reviewTaskDraft", 4], ["saveReviewTaskDraft", 7], ["deleteReviewTaskDraft", 6], ["decideReviewTask", 7], ["askApplicant", 7], ["reviewHistory", 5], ["addReviewNote", 6], ["reviewClocks", 4], ["reviewTaskHoldings", 4], ["previewClockRecompute", 3], ["applyClockRecompute", 4], ["previewCaseloadMove", 4], ["applyCaseloadMove", 5]]); for (const [method, jsonIndexes] of [ ['description', []], ['createOrRecoverReviewRequest', [3]], @@ -192,6 +192,7 @@ for (const [method, jsonIndexes] of [ ['saveReviewTaskDraft', [5]], ['deleteReviewTaskDraft', []], ['decideReviewTask', [5]], + ['askApplicant', [5]], ['reviewHistory', [3]], ['addReviewNote', [4]], ['reviewClocks', []], diff --git a/crates/registry-casework-client-node/index.d.ts b/crates/registry-casework-client-node/index.d.ts index c77ea8b4a9..abeb3ad3ec 100644 --- a/crates/registry-casework-client-node/index.d.ts +++ b/crates/registry-casework-client-node/index.d.ts @@ -38,6 +38,7 @@ export declare class CaseworkClient { reviewTaskDraft(token: string, profile: string, taskId: string, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise saveReviewTaskDraft(token: string, profile: string, taskId: string, expectedRevision: number, idempotencyKey: string, draft: any, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise deleteReviewTaskDraft(token: string, profile: string, taskId: string, expectedRevision: number, idempotencyKey: string, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise + askApplicant(token: string, profile: string, taskId: string, expectedRevision: number, idempotencyKey: string, ask: any, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise decideReviewTask(token: string, profile: string, taskId: string, expectedRevision: number, idempotencyKey: string, decision: any, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise reviewHistory(token: string, profile: string, requestId: string, query?: any | undefined | null, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise addReviewNote(token: string, profile: string, requestId: string, idempotencyKey: string, note: any, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise diff --git a/crates/registry-casework-client-node/src/lib.rs b/crates/registry-casework-client-node/src/lib.rs index 4e5e4e2649..8a6a1efef9 100644 --- a/crates/registry-casework-client-node/src/lib.rs +++ b/crates/registry-casework-client-node/src/lib.rs @@ -15,8 +15,8 @@ use registry_casework_client::{ ReviewCancelRequest, ReviewCaseloadApplyRequest, ReviewCaseloadMoveRequest, ReviewClockRecomputeApplyRequest, ReviewClockRecomputeRequest, ReviewCreateRequest, ReviewNoteRequest, ReviewPageQuery, ReviewRequestAccepted, ReviewResultResponse, - ReviewStaffingQuery, ReviewTaskDecisionRequest, ReviewTaskDraftInput, SubmissionDigest, - SupervisoryReviewTaskQuery, + ReviewStaffingQuery, ReviewTaskAskRequest, ReviewTaskDecisionRequest, ReviewTaskDraftInput, + SubmissionDigest, SupervisoryReviewTaskQuery, }; use serde::Serialize; use serde_json::{json, Value}; @@ -830,6 +830,45 @@ impl CaseworkClient { ) } + #[napi] + #[allow(clippy::too_many_arguments)] + pub async fn ask_applicant( + &self, + token: String, + profile: String, + task_id: String, + expected_revision: i64, + idempotency_key: String, + ask: Value, + source_profile: Option, + source_credential: Option, + ) -> Result { + safe_revision(expected_revision)?; + let token = bearer(token)?; + let source_token = source_credential + .as_ref() + .map(|source| bearer(source.token.clone())) + .transpose()?; + let ask: ReviewTaskAskRequest = input(ask)?; + outcome( + self.inner + .ask_applicant( + optional_source_auth( + &token, + &profile, + source_profile.as_deref(), + source_credential.as_ref(), + source_token.as_ref(), + ), + uuid(&task_id)?, + expected_revision, + &idempotency_key, + &ask, + ) + .await, + ) + } + #[napi] #[allow(clippy::too_many_arguments)] pub async fn decide_review_task( diff --git a/crates/registry-casework-client-py/python/registry_casework_client/__init__.pyi b/crates/registry-casework-client-py/python/registry_casework_client/__init__.pyi index b634a753cf..20f06e36d7 100644 --- a/crates/registry-casework-client-py/python/registry_casework_client/__init__.pyi +++ b/crates/registry-casework-client-py/python/registry_casework_client/__init__.pyi @@ -355,6 +355,13 @@ KnownCaseworkProblemCode: TypeAlias = Literal[ "request.not-found", "request.unprocessable", "request.unsupported-media-type", + "review.ask-already-open", + "review.ask-answer-time-invalid", + "review.ask-limit-reached", + "review.ask-not-offered", + "review.ask-not-open", + "review.ask-producer-unsupported", + "review.ask-task-inactive", "review.distinct-approver-required", "review.initiator-excluded", "review.initiator-required", "review.query-too-broad", @@ -512,6 +519,7 @@ class ReviewPageQuery(TypedDict, total=False): limit: SafeInteger ReviewTaskOwnership: TypeAlias = Literal["assigned-to-me", "unclaimed"] ReviewTaskSort: TypeAlias = Literal["due", "subject", "reference"] +ReviewTaskMarker: TypeAlias = Literal["waiting", "answered", "expired"] class ReviewStaffingQuery(ReviewPageQuery, total=False): subjectSource: str subjectType: str @@ -522,6 +530,7 @@ class ReviewStaffingQuery(ReviewPageQuery, total=False): sort: ReviewTaskSort queue: str ownership: ReviewTaskOwnership + marker: ReviewTaskMarker class SupervisoryReviewTaskQuery(ReviewPageQuery, total=False): queue: str requestId: Uuid @@ -577,6 +586,7 @@ class _ReviewTaskOptional(TypedDict, total=False): displayReference: str decidedByCaller: bool decisionReceipt: ReviewDecisionReceipt + marker: ReviewTaskMarker class ReviewTask(_ReviewTaskOptional): subject: SubjectBinding requesterReference: str @@ -625,8 +635,62 @@ class ReviewSourceContext(_ReviewSourceContextOptional): reference: str bindingStatus: ReviewSourceBindingStatus ReviewTaskContextData: TypeAlias = ReviewSubmittedContext | ReviewSourceContext +class ReviewAnswerWant(TypedDict): + kind: Literal["answer"] +class ReviewDocumentWant(TypedDict): + kind: Literal["document"] +ReviewAskWant: TypeAlias = ReviewAnswerWant | ReviewDocumentWant +ReviewAskState: TypeAlias = Literal["open", "answered", "expired", "closed"] +class ReviewTaskAskRequest(TypedDict): + text: str + wants: list[ReviewAskWant] +class _ReviewAskOptional(TypedDict, total=False): + dueAt: str + answeredAt: str + closedAt: str +class ReviewAsk(_ReviewAskOptional): + askId: Uuid + requestId: Uuid + subject: SubjectBinding + text: str + wants: list[ReviewAskWant] + askedAt: str + state: ReviewAskState +class ReviewTaskAsked(TypedDict): + task: ReviewTask + ask: ReviewAsk +class ReviewAnswerDownload(TypedDict): + method: Literal["GET"] + operation: str + accessProfile: str + path: str +class _ReviewAnswerDocumentOptional(TypedDict, total=False): + verificationStatus: str + download: ReviewAnswerDownload +class ReviewAnswerDocument(_ReviewAnswerDocumentOptional): + id: str + sha256: str + contentType: str + byteSize: int +class _ReviewContextAnswerOptional(TypedDict, total=False): + text: str +class ReviewContextAnswer(_ReviewContextAnswerOptional): + documents: list[ReviewAnswerDocument] + answeredAt: str +class _ReviewContextAskOptional(TypedDict, total=False): + dueAt: str + answeredAt: str + answer: ReviewContextAnswer +class ReviewContextAsk(_ReviewContextAskOptional): + askId: Uuid + taskId: Uuid + text: str + wants: list[ReviewAskWant] + askedAt: str + state: ReviewAskState class _ReviewTaskContextOptional(TypedDict, total=False): resultConstraints: JsonObject + asks: list[ReviewContextAsk] class ReviewTaskContext(_ReviewTaskContextOptional): taskId: Uuid requestId: Uuid @@ -654,7 +718,7 @@ class ReviewClockOccurrence(_ReviewClockOccurrenceOptional): clockId: str requestId: Uuid correlation: ReviewClockCorrelation - state: Literal["running", "completed", "cancelled", "source-facts-missing"] + state: Literal["running", "paused", "completed", "cancelled", "source-facts-missing"] policyDigest: ContentDigest anchorAt: str class ReviewTaskDraftInput(TypedDict): @@ -740,6 +804,10 @@ class ReviewContextProviderPolicy(TypedDict): sourceNamespace: str deploymentRef: str serviceProfiles: NotRequired[dict[ReviewContextCapability, str]] +class ReviewStageAsksPolicy(TypedDict, total=False): + answerWithin: ElapsedDuration + onDue: Literal["return-to-reviewer"] + pauseClocks: bool class ReviewStagePolicy(TypedDict): id: str label: NotRequired[str] @@ -749,6 +817,7 @@ class ReviewStagePolicy(TypedDict): requiredApprovals: SafeInteger outcomes: NotRequired[list[str]] negativeDecisions: NotRequired[Literal["settle", "advise"]] + asks: NotRequired[ReviewStageAsksPolicy] excludeInitiator: NotRequired[bool] excludePreviousStageReviewers: NotRequired[bool] class ReviewRetentionPolicy(TypedDict): @@ -762,6 +831,7 @@ class ReviewOutcomePolicy(TypedDict): publicReason: Literal["required", "optional", "none"] resultRequired: NotRequired[bool] class _ReviewPolicyOptional(TypedDict, total=False): + resubmission: Literal["first-stage", "resume-at-returning-stage"] label: str routing: list[RoutingRule] clocks: list[str] @@ -847,6 +917,7 @@ class CaseworkClient: def review_task_draft(self, token: str, profile: str, task_id: Uuid, source_profile: str | None = None, source_credential: HumanSourceCredential | None = None) -> Complete[ReviewTaskDraft | None]: ... def save_review_task_draft(self, token: str, profile: str, task_id: Uuid, expected_revision: SafeInteger, idempotency_key: str, draft: ReviewTaskDraftInput, source_profile: str | None = None, source_credential: HumanSourceCredential | None = None) -> Complete[ReviewTaskDraft]: ... def delete_review_task_draft(self, token: str, profile: str, task_id: Uuid, expected_revision: SafeInteger, idempotency_key: str, source_profile: str | None = None, source_credential: HumanSourceCredential | None = None) -> Complete[None]: ... + def ask_applicant(self, token: str, profile: str, task_id: Uuid, expected_revision: SafeInteger, idempotency_key: str, ask: ReviewTaskAskRequest, source_profile: str | None = None, source_credential: HumanSourceCredential | None = None) -> Complete[ReviewTaskAsked]: ... def decide_review_task(self, token: str, profile: str, task_id: Uuid, expected_revision: SafeInteger, idempotency_key: str, decision: ReviewTaskDecisionRequest, source_profile: str | None = None, source_credential: HumanSourceCredential | None = None) -> Complete[None]: ... def review_history(self, token: str, profile: str, request_id: Uuid, query: ReviewPageQuery | None = None, source_profile: str | None = None, source_credential: HumanSourceCredential | None = None) -> Complete[ReviewHistoryPage]: ... def add_review_note(self, token: str, profile: str, request_id: Uuid, idempotency_key: str, note: ReviewNoteRequest, source_profile: str | None = None, source_credential: HumanSourceCredential | None = None) -> Complete[ReviewHistoryEntry]: ... diff --git a/crates/registry-casework-client-py/src/lib.rs b/crates/registry-casework-client-py/src/lib.rs index 30de759360..7553e1c6c2 100644 --- a/crates/registry-casework-client-py/src/lib.rs +++ b/crates/registry-casework-client-py/src/lib.rs @@ -16,8 +16,8 @@ use casework_client_sdk::{ HolidaySetRevisionInput, OwnReviewDecisionQuery, ReviewCancelRequest, ReviewCaseloadApplyRequest, ReviewCaseloadMoveRequest, ReviewClockRecomputeApplyRequest, ReviewClockRecomputeRequest, ReviewCreateRequest, ReviewNoteRequest, ReviewPageQuery, - ReviewRequestAccepted, ReviewResultResponse, ReviewStaffingQuery, ReviewTaskDecisionRequest, - ReviewTaskDraftInput, SubmissionDigest, SupervisoryReviewTaskQuery, + ReviewRequestAccepted, ReviewResultResponse, ReviewStaffingQuery, ReviewTaskAskRequest, + ReviewTaskDecisionRequest, ReviewTaskDraftInput, SubmissionDigest, SupervisoryReviewTaskQuery, }; use pyo3::{ exceptions::{PyException, PyRuntimeError}, @@ -1180,6 +1180,38 @@ impl CaseworkClient { ) } + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (token, profile, task_id, expected_revision, idempotency_key, ask, source_profile=None, source_credential=None))] + fn ask_applicant<'py>( + &self, + py: Python<'py>, + token: &str, + profile: &str, + task_id: &str, + expected_revision: i64, + idempotency_key: &str, + ask: &Bound<'_, PyAny>, + source_profile: Option<&str>, + source_credential: Option<&Bound<'_, PyAny>>, + ) -> PyResult> { + let token = bearer(py, token)?; + let source_credential = parse_human_source_credential(py, source_credential)?; + let task_id = uuid(py, task_id)?; + let ask: ReviewTaskAskRequest = input(py, ask)?; + complete( + py, + py.detach(|| { + self.runtime.block_on(self.inner.ask_applicant( + auth(&token, profile, source_profile, source_credential.as_ref()), + task_id, + expected_revision, + idempotency_key, + &ask, + )) + }), + ) + } + #[allow(clippy::too_many_arguments)] #[pyo3(signature = (token, profile, task_id, expected_revision, idempotency_key, decision, source_profile=None, source_credential=None))] fn decide_review_task<'py>( diff --git a/crates/registry-casework-client-py/tests/python/test_ask_limit.py b/crates/registry-casework-client-py/tests/python/test_ask_limit.py new file mode 100644 index 0000000000..56c96f9bf1 --- /dev/null +++ b/crates/registry-casework-client-py/tests/python/test_ask_limit.py @@ -0,0 +1,52 @@ +"""The request ask limit is a known, non-retryable problem.""" +import json +import threading +import unittest +from http.server import BaseHTTPRequestHandler, HTTPServer + +from bootstrap import ensure_built + +ensure_built() +from registry_casework_client import CaseworkClient, CaseworkClientError # noqa: E402 + + +class AskLimitTests(unittest.TestCase): + def test_the_ask_limit_preserves_its_detail_without_retrying(self): + attempts = [] + detail = "This review request has reached its limit of 50 asks. Continue the review without opening another ask." + + class Handler(BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers["content-length"])) + attempts.append(self.path) + body = json.dumps({ + "type": "https://id.registrystack.org/problems/registry-casework/review/ask-limit-reached", + "title": "Review ask limit reached", "status": 409, + "detail": detail, "code": "review.ask-limit-reached", + "traceId": "0123456789abcdef0123456789abcdef", + }).encode() + self.send_response(409) + self.send_header("content-type", "application/problem+json") + self.send_header("traceparent", "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01") + self.send_header("content-length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *_): + return + + server = HTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + client = CaseworkClient(f"http://127.0.0.1:{server.server_port}/") + with self.assertRaises(CaseworkClientError) as caught: + client.ask_applicant("synthetic-token", "staff", "00000000-0000-4000-8000-000000000001", 2, "ask-51", {"text": "Why?", "wants": []}) + self.assertEqual(caught.exception.kind, "problem") + self.assertEqual(caught.exception.code, "review.ask-limit-reached") + self.assertEqual(caught.exception.detail, detail) + self.assertEqual(len(attempts), 1) + finally: + server.shutdown() + thread.join() + server.server_close() diff --git a/crates/registry-casework-client-py/tests/python/test_capabilities.py b/crates/registry-casework-client-py/tests/python/test_capabilities.py index f960ba7e0b..3c11dc3cac 100644 --- a/crates/registry-casework-client-py/tests/python/test_capabilities.py +++ b/crates/registry-casework-client-py/tests/python/test_capabilities.py @@ -17,7 +17,7 @@ def test_all_canonical_operations_are_exported(self) -> None: "preview_review_task_templates", "list_review_task_grants", "approve_review_task_grant", "revoke_review_task_grant", "assign_review_task", "delegate_review_task", "review_task_draft", - "save_review_task_draft", "delete_review_task_draft", "decide_review_task", + "save_review_task_draft", "delete_review_task_draft", "decide_review_task", "ask_applicant", "review_history", "add_review_note", "review_clocks", "review_accountability", diff --git a/crates/registry-casework-client-py/tests/python/test_native_requests.py b/crates/registry-casework-client-py/tests/python/test_native_requests.py index 19873a8479..3e0fca252f 100644 --- a/crates/registry-casework-client-py/tests/python/test_native_requests.py +++ b/crates/registry-casework-client-py/tests/python/test_native_requests.py @@ -125,6 +125,7 @@ def do_GET(self) -> None: # noqa: N802 "version": "1", "digest": f"sha256:{'a' * 64}", }, + "asks": [{'askId': '00000000-0000-4000-8000-000000000007', 'taskId': '00000000-0000-4000-8000-000000000001', 'text': 'Why?', 'wants': [{'kind': 'answer'}], 'askedAt': '2026-11-27T00:00:00Z', 'state': 'open', 'answer': {'text': 'source answer from BReg', 'documents': [], 'answeredAt': '2026-11-27T01:00:00Z'}}], "requesterReference": "correction-42", "policy": { "id": "registry-correction", @@ -449,6 +450,7 @@ def test_review_task_context_uses_exact_route_and_source_profile(self) -> None: context["value"]["context"]["projection"]["displayReference"], "Correction 42", ) + self.assertEqual(context["value"]["asks"][0]["answer"], {'text': 'source answer from BReg', 'documents': [], 'answeredAt': '2026-11-27T01:00:00Z'}) observation = _Handler.observations[0] self.assertEqual( observation["path"], f"/tenant/v1/review-tasks/{ITEM_ID}/context" @@ -533,6 +535,10 @@ def test_review_optional_arguments_may_be_omitted(self) -> None: "", "staff", ITEM_ID, 1, "decision-key", {"decision": {"type": "approve", "outcome": "approved"}}, ), + lambda: self.client.ask_applicant( + "", "staff", ITEM_ID, 1, "ask-key", + {"text": "Send the form.", "wants": [{"kind": "answer"}]}, + ), lambda: self.client.review_history("", "staff", ITEM_ID), lambda: self.client.add_review_note( "", "staff", ITEM_ID, "note-key", {"audience": "requester", "note": "Note"} diff --git a/crates/registry-casework-client-py/tests/python/test_typing_contract.py b/crates/registry-casework-client-py/tests/python/test_typing_contract.py index 6adf86a220..22d54be5d9 100644 --- a/crates/registry-casework-client-py/tests/python/test_typing_contract.py +++ b/crates/registry-casework-client-py/tests/python/test_typing_contract.py @@ -12,6 +12,24 @@ class TypingContractTests(unittest.TestCase): + def test_ask_timing_and_resubmission_types_match_the_wire(self) -> None: + module = ast.parse(STUB.read_text(encoding="utf-8")) + classes = {node.name: node for node in module.body if isinstance(node, ast.ClassDef)} + aliases = {node.target.id: ast.unparse(node.value) for node in module.body if isinstance(node, ast.AnnAssign) and node.value is not None} + self.assertEqual(aliases["ReviewTaskMarker"], "Literal['waiting', 'answered', 'expired']") + fields = lambda name: {node.target.id: ast.unparse(node.annotation) for node in classes[name].body if isinstance(node, ast.AnnAssign)} + self.assertEqual(fields("ReviewClockOccurrence")["state"], "Literal['running', 'paused', 'completed', 'cancelled', 'source-facts-missing']") + self.assertEqual(fields("ReviewStagePolicy")["asks"], "NotRequired[ReviewStageAsksPolicy]") + self.assertEqual(fields("ReviewStageAsksPolicy"), { + "answerWithin": "ElapsedDuration", + "onDue": "Literal['return-to-reviewer']", + "pauseClocks": "bool", + }) + self.assertEqual(fields("_ReviewPolicyOptional")["resubmission"], "Literal['first-stage', 'resume-at-returning-stage']") + self.assertEqual(fields("_ReviewContextAskOptional")["dueAt"], "str") + self.assertEqual(fields("_ReviewContextAskOptional")["answer"], "ReviewContextAnswer") + self.assertEqual(fields("ReviewContextAnswer")["documents"], "list[ReviewAnswerDocument]") + def test_client_configuration_uses_the_canonical_authored_names(self) -> None: module = ast.parse(STUB.read_text(encoding="utf-8")) client = next( @@ -162,7 +180,7 @@ def test_review_parity_inventory_is_closed_and_bounded(self) -> None: } self.assertEqual( optional_task_fields, - {"decidedByCaller": "bool", "decisionReceipt": "ReviewDecisionReceipt", "deadlineAt": "str | None", "displayReference": "str", "staffingDiagnostic": "StaffingDiagnostic"}, + {"decidedByCaller": "bool", "decisionReceipt": "ReviewDecisionReceipt", "deadlineAt": "str | None", "displayReference": "str", "marker": "ReviewTaskMarker", "staffingDiagnostic": "StaffingDiagnostic"}, ) self.assertEqual( ast.unparse(aliases["ReviewTaskOwnership"].value), @@ -247,6 +265,7 @@ def test_review_parity_inventory_is_closed_and_bounded(self) -> None: "save_review_task_draft", "delete_review_task_draft", "decide_review_task", + "ask_applicant", ): method_arguments = { argument.arg: ast.unparse(argument.annotation) diff --git a/crates/registry-casework-client/src/client.rs b/crates/registry-casework-client/src/client.rs index 152882b688..911a6df9f6 100644 --- a/crates/registry-casework-client/src/client.rs +++ b/crates/registry-casework-client/src/client.rs @@ -5,15 +5,15 @@ use registry_casework_core::{ AbsenceInput, AbsenceList, AbsenceRecord, AbsencesQuery, AssignmentRequest, BootstrapDirectoryRequest, DelegateRequest, Description, DirectoryResponse, DirectoryTargetPage, DirectoryTargetsQuery, HolidaySetDocument, HolidaySetRevisionInput, - OwnReviewDecisionPage, PageStatus, ReviewAccountabilityRecord, ReviewCancelRequest, - ReviewCancelResponse, ReviewCaseloadApplyRequest, ReviewCaseloadMoveRequest, - ReviewCaseloadPreview, ReviewCaseloadResult, ReviewClockOccurrence, + OwnReviewDecisionPage, PageStatus, ReviewAccountabilityRecord, ReviewAskState, + ReviewCancelRequest, ReviewCancelResponse, ReviewCaseloadApplyRequest, + ReviewCaseloadMoveRequest, ReviewCaseloadPreview, ReviewCaseloadResult, ReviewClockOccurrence, ReviewClockRecomputeApplyRequest, ReviewClockRecomputePreview, ReviewClockRecomputeRequest, ReviewClockRecomputeResult, ReviewContextPolicy, ReviewCreateRequest, ReviewHistoryAudience, ReviewHistoryEntry, ReviewHistoryPage, ReviewNoteRequest, ReviewPolicyClosure, ReviewRequestAccepted, ReviewRequestView, ReviewResultFeedPage, ReviewSourceBindingStatus, ReviewStaffingQuery, ReviewTask, ReviewTaskContext, ReviewTaskContextData, ReviewTaskDraft, - ReviewTaskDraftInput, ReviewTaskPage, ReviewTaskState, ReviewValidationError, + ReviewTaskDraftInput, ReviewTaskMarker, ReviewTaskPage, ReviewTaskState, ReviewValidationError, ReviewValidationReason, SupervisoryReviewTaskPage, CASEWORK_PROBLEM_TYPE_BASE, CASEWORK_PROFILE_HEADER, DIRECTORY_TARGETS_PATH, IDEMPOTENCY_KEY_HEADER, MAXIMUM_CASEWORK_IDEMPOTENCY_KEY_BYTES, MAXIMUM_CASEWORK_PROFILE_BYTES, SOURCE_PROFILE_HEADER, @@ -43,7 +43,8 @@ use uuid::Uuid; use crate::{ wire::ClientResponse, CaseworkAuth, CaseworkClientConfig, CaseworkClientError, CaseworkComplete, CaseworkProblemCode, CaseworkProtocolFailure, DelegatedStaffReadAuth, - ReviewPageQuery, ReviewResultResponse, ReviewTaskDecisionRequest, SupervisoryReviewTaskQuery, + ReviewPageQuery, ReviewResultResponse, ReviewTaskAskRequest, ReviewTaskAsked, + ReviewTaskDecisionRequest, SupervisoryReviewTaskQuery, }; const JSON_MEDIA_TYPE: &str = "application/json"; @@ -824,6 +825,49 @@ impl CaseworkClient { self.send_keyed_empty(request, StatusCode::NO_CONTENT).await } + /// Ask the applicant for more. The holder names the task revision it read. + /// The response is checked to be the same task, one revision later and + /// waiting, with an open ask of the same request. + pub async fn ask_applicant( + &self, + auth: CaseworkAuth<'_>, + task_id: Uuid, + expected_revision: i64, + idempotency_key: &str, + ask: &ReviewTaskAskRequest, + ) -> Result, CaseworkClientError> { + ask.check() + .map_err(|_| CaseworkClientError::invalid_request("the ask is invalid"))?; + validate_mutation(expected_revision, idempotency_key)?; + let request = self.mutation_headers( + self.authorized( + self.http + .post(self.url(&["v1", "review-tasks", &task_id.to_string(), "asks"])?) + .json(ask), + &auth, + )?, + expected_revision, + idempotency_key, + )?; + let complete: CaseworkComplete = + self.send_keyed_json(request, StatusCode::OK).await?; + let asked = &complete.value; + if asked.task.task_id != task_id + || expected_revision.checked_add(1) != Some(asked.task.revision) + || asked.task.marker != Some(ReviewTaskMarker::Waiting) + || asked.ask.request_id != asked.task.request_id + || asked.ask.state != ReviewAskState::Open + || asked.ask.check().is_err() + { + return Err(protocol( + StatusCode::OK, + CaseworkProtocolFailure::Body, + Some(complete.trace_id), + )); + } + Ok(complete) + } + pub async fn review_history( &self, auth: CaseworkAuth<'_>, diff --git a/crates/registry-casework-client/src/error.rs b/crates/registry-casework-client/src/error.rs index 6c729b88df..56b7010061 100644 --- a/crates/registry-casework-client/src/error.rs +++ b/crates/registry-casework-client/src/error.rs @@ -60,6 +60,13 @@ pub enum CaseworkProblemCode { RequestNotFound, RequestUnprocessable, RequestUnsupportedMediaType, + ReviewAskAlreadyOpen, + ReviewAskAnswerTimeInvalid, + ReviewAskLimitReached, + ReviewAskNotOffered, + ReviewAskNotOpen, + ReviewAskProducerUnsupported, + ReviewAskTaskInactive, ReviewDistinctApproverRequired, ReviewInitiatorExcluded, ReviewInitiatorRequired, @@ -84,7 +91,7 @@ impl CaseworkProblemCode { /// /// `Unknown` is absent: it carries whatever a newer Casework service /// answered, so it names no registered code. - pub const ALL: [Self; 37] = [ + pub const ALL: [Self; 44] = [ Self::AbsenceCoverCycle, Self::AbsenceInvalidPeriod, Self::AbsenceOverlap, @@ -107,6 +114,13 @@ impl CaseworkProblemCode { Self::RequestNotFound, Self::RequestUnprocessable, Self::RequestUnsupportedMediaType, + Self::ReviewAskAlreadyOpen, + Self::ReviewAskAnswerTimeInvalid, + Self::ReviewAskLimitReached, + Self::ReviewAskNotOffered, + Self::ReviewAskNotOpen, + Self::ReviewAskProducerUnsupported, + Self::ReviewAskTaskInactive, Self::ReviewDistinctApproverRequired, Self::ReviewInitiatorExcluded, Self::ReviewInitiatorRequired, @@ -152,6 +166,13 @@ impl CaseworkProblemCode { Self::ReviewQueryTooBroad => REVIEW_QUERY_TOO_BROAD_PROBLEM, Self::ReviewPolicyMismatch => REVIEW_POLICY_MISMATCH_PROBLEM, Self::ReviewResultExpired => REVIEW_RESULT_EXPIRED_PROBLEM, + Self::ReviewAskAlreadyOpen => "review.ask-already-open", + Self::ReviewAskLimitReached => "review.ask-limit-reached", + Self::ReviewAskAnswerTimeInvalid => "review.ask-answer-time-invalid", + Self::ReviewAskNotOffered => "review.ask-not-offered", + Self::ReviewAskNotOpen => "review.ask-not-open", + Self::ReviewAskProducerUnsupported => "review.ask-producer-unsupported", + Self::ReviewAskTaskInactive => "review.ask-task-inactive", Self::ReviewDistinctApproverRequired => "review.distinct-approver-required", Self::ReviewInitiatorExcluded => REVIEW_INITIATOR_EXCLUDED_PROBLEM, Self::ReviewInitiatorRequired => REVIEW_INITIATOR_REQUIRED_PROBLEM, @@ -195,6 +216,13 @@ impl CaseworkProblemCode { REVIEW_QUERY_TOO_BROAD_PROBLEM => Self::ReviewQueryTooBroad, REVIEW_POLICY_MISMATCH_PROBLEM => Self::ReviewPolicyMismatch, REVIEW_RESULT_EXPIRED_PROBLEM => Self::ReviewResultExpired, + "review.ask-already-open" => Self::ReviewAskAlreadyOpen, + "review.ask-limit-reached" => Self::ReviewAskLimitReached, + "review.ask-answer-time-invalid" => Self::ReviewAskAnswerTimeInvalid, + "review.ask-not-offered" => Self::ReviewAskNotOffered, + "review.ask-not-open" => Self::ReviewAskNotOpen, + "review.ask-producer-unsupported" => Self::ReviewAskProducerUnsupported, + "review.ask-task-inactive" => Self::ReviewAskTaskInactive, "review.distinct-approver-required" => Self::ReviewDistinctApproverRequired, REVIEW_INITIATOR_EXCLUDED_PROBLEM => Self::ReviewInitiatorExcluded, REVIEW_INITIATOR_REQUIRED_PROBLEM => Self::ReviewInitiatorRequired, @@ -238,13 +266,21 @@ impl CaseworkProblemCode { Self::RequestNotFound => 404, Self::RequestMethodNotAllowed => 405, Self::IdempotencyKeyReused + | Self::ReviewAskAlreadyOpen + | Self::ReviewAskLimitReached + | Self::ReviewAskNotOffered + | Self::ReviewAskNotOpen + | Self::ReviewAskProducerUnsupported + | Self::ReviewAskTaskInactive | Self::ReviewPolicyMismatch | Self::ReviewSubmissionConflict | Self::ReviewTaskNotHeld => 409, Self::PreconditionFailed => 412, Self::RequestBodyTooLarge => 413, Self::RequestUnsupportedMediaType => 415, - Self::RequestUnprocessable | Self::ReviewInitiatorRequired => 422, + Self::RequestUnprocessable + | Self::ReviewAskAnswerTimeInvalid + | Self::ReviewInitiatorRequired => 422, Self::ReviewQueryTooBroad => 422, Self::PreconditionRequired => 428, Self::SourceVersionMismatch => 502, @@ -337,6 +373,34 @@ impl CaseworkProblemCode { "Unsupported media type", "Send a JSON request body with Content-Type application/json.", ), + Self::ReviewAskLimitReached => ( + "Review ask limit reached", + "This review request has reached its limit of 50 asks. Continue the review without opening another ask.", + ), + Self::ReviewAskAlreadyOpen => ( + "Review ask already open", + "Wait for the open ask on this request to be answered or closed before asking again.", + ), + Self::ReviewAskAnswerTimeInvalid => ( + "Review ask answer time invalid", + "Report the time the applicant's answer was committed: not before the ask was made and no more than five minutes ahead of Casework's clock.", + ), + Self::ReviewAskNotOffered => ( + "Review ask not offered", + "The active stage of this review policy does not let a reviewer ask the applicant.", + ), + Self::ReviewAskNotOpen => ( + "Review ask not open", + "This ask was already answered or closed, or the applicant answered after its due date.", + ), + Self::ReviewAskProducerUnsupported => ( + "Review ask producer unsupported", + "The producer of this request does not read asks, so the reviewer cannot ask the applicant.", + ), + Self::ReviewAskTaskInactive => ( + "Review ask task inactive", + "Ask from a task at the active stage of a request that is still under review.", + ), Self::ReviewDistinctApproverRequired => ("Distinct approver required", "Each approval in this stage must be supplied by a different reviewer."), Self::ReviewInitiatorExcluded => ( "Review initiator excluded", @@ -812,6 +876,23 @@ mod tests { ); } + #[test] + fn the_ask_limit_problem_is_registered_under_conflict() { + let code = CaseworkProblemCode::ALL + .iter() + .find(|code| code.code() == "review.ask-limit-reached"); + assert!( + code.is_some(), + "the canonical client must recognise the ask-limit refusal" + ); + assert_eq!(code.unwrap().expected_status(), Some(409)); + assert_eq!( + CaseworkProblemCode::parse("review.ask-limit-reached"), + *code.unwrap() + ); + assert_eq!(code.unwrap().expected_text(),Some(("Review ask limit reached","This review request has reached its limit of 50 asks. Continue the review without opening another ask."))); + } + #[test] fn review_lifecycle_problems_have_exact_recovery_contracts() { for (value, expected, status, title, detail) in [ @@ -843,6 +924,48 @@ mod tests { "Review submission conflict", "The same producer, source subject, version, and policy were already submitted with different canonical content.", ), + ( + "review.ask-already-open", + CaseworkProblemCode::ReviewAskAlreadyOpen, + 409, + "Review ask already open", + "Wait for the open ask on this request to be answered or closed before asking again.", + ), + ( + "review.ask-answer-time-invalid", + CaseworkProblemCode::ReviewAskAnswerTimeInvalid, + 422, + "Review ask answer time invalid", + "Report the time the applicant's answer was committed: not before the ask was made and no more than five minutes ahead of Casework's clock.", + ), + ( + "review.ask-not-offered", + CaseworkProblemCode::ReviewAskNotOffered, + 409, + "Review ask not offered", + "The active stage of this review policy does not let a reviewer ask the applicant.", + ), + ( + "review.ask-not-open", + CaseworkProblemCode::ReviewAskNotOpen, + 409, + "Review ask not open", + "This ask was already answered or closed, or the applicant answered after its due date.", + ), + ( + "review.ask-producer-unsupported", + CaseworkProblemCode::ReviewAskProducerUnsupported, + 409, + "Review ask producer unsupported", + "The producer of this request does not read asks, so the reviewer cannot ask the applicant.", + ), + ( + "review.ask-task-inactive", + CaseworkProblemCode::ReviewAskTaskInactive, + 409, + "Review ask task inactive", + "Ask from a task at the active stage of a request that is still under review.", + ), ( "review.task-not-held", CaseworkProblemCode::ReviewTaskNotHeld, diff --git a/crates/registry-casework-client/src/lib.rs b/crates/registry-casework-client/src/lib.rs index 015c5b7231..fe32e33c96 100644 --- a/crates/registry-casework-client/src/lib.rs +++ b/crates/registry-casework-client/src/lib.rs @@ -38,21 +38,24 @@ pub use registry_casework_core::{ DirectoryTargetPage, DirectoryTargetPurpose, DirectoryTargetsQuery, DirectoryTeamUpdateRequest, ElapsedDuration, EqualsPredicate, HolidaySetDocument, HolidaySetRevisionInput, HumanIdentity, IssuerPrincipal, OneOfPredicate, OwnReviewDecision, OwnReviewDecisionPage, Page, PageStatus, - PolicyBinding, PolicySelection, QueueRecord, ReviewAccountabilityRecord, ReviewCancelRequest, - ReviewCancelResponse, ReviewCaseloadApplyRequest, ReviewCaseloadMoveRequest, - ReviewCaseloadPreview, ReviewCaseloadResult, ReviewCaseloadTask, ReviewClockOccurrence, - ReviewClockRecomputeApplyRequest, ReviewClockRecomputePreview, ReviewClockRecomputeRequest, - ReviewClockRecomputeResult, ReviewClockRecomputeTask, ReviewCompletion, ReviewCompletionType, - ReviewContext, ReviewContextCapability, ReviewContextContract, ReviewContextPolicy, + PolicyBinding, PolicySelection, QueueRecord, ReviewAccountabilityRecord, ReviewAnswerDocument, + ReviewAnswerDownload, ReviewAsk, ReviewAskOnDue, ReviewAskState, ReviewAskWant, + ReviewCancelRequest, ReviewCancelResponse, ReviewCaseloadApplyRequest, + ReviewCaseloadMoveRequest, ReviewCaseloadPreview, ReviewCaseloadResult, ReviewCaseloadTask, + ReviewClockOccurrence, ReviewClockRecomputeApplyRequest, ReviewClockRecomputePreview, + ReviewClockRecomputeRequest, ReviewClockRecomputeResult, ReviewClockRecomputeTask, + ReviewClockState, ReviewCompletion, ReviewCompletionType, ReviewContext, ReviewContextAnswer, + ReviewContextAsk, ReviewContextCapability, ReviewContextContract, ReviewContextPolicy, ReviewContextProviderPolicy, ReviewCreateRequest, ReviewDecisionReceipt, ReviewDecisionType, ReviewHistoryAudience, ReviewHistoryEntry, ReviewHistoryPage, ReviewNegativeDecisionMode, ReviewNoteRequest, ReviewPolicy, ReviewPolicyClosure, ReviewPolicyDependencies, ReviewPurpose, - ReviewRequestAccepted, ReviewRequestLifecycle, ReviewRequestView, ReviewResult, - ReviewResultFeedEntry, ReviewResultFeedPage, ReviewResultStatus, ReviewSourceBindingStatus, - ReviewSourceProjection, ReviewStaffingQuery, ReviewStagePolicy, ReviewTask, ReviewTaskContext, + ReviewRequestAccepted, ReviewRequestLifecycle, ReviewRequestView, ReviewResubmissionPolicy, + ReviewResult, ReviewResultFeedEntry, ReviewResultFeedPage, ReviewResultStatus, + ReviewSourceBindingStatus, ReviewSourceProjection, ReviewStaffingQuery, ReviewStageAsksPolicy, + ReviewStagePolicy, ReviewTask, ReviewTaskAskRequest, ReviewTaskAsked, ReviewTaskContext, ReviewTaskContextData, ReviewTaskDecisionRequest, ReviewTaskDraft, ReviewTaskDraftInput, - ReviewTaskOwnership, ReviewTaskPage, ReviewTaskSort, ReviewTaskState, ReviewValidationError, - ReviewValidationReason, RoutingCondition, RoutingPredicate, RoutingRule, + ReviewTaskMarker, ReviewTaskOwnership, ReviewTaskPage, ReviewTaskSort, ReviewTaskState, + ReviewValidationError, ReviewValidationReason, RoutingCondition, RoutingPredicate, RoutingRule, SchedulingTaskPermission, SourceContextBinding, StaffingDiagnostic, StageClockAnchor, StageClockAnchorType, SubjectBinding, SubjectClockAnchor, SubjectClockAnchorType, SubmissionDigest, SupervisoryReviewTask, SupervisoryReviewTaskPage, SupervisoryReviewTaskState, diff --git a/crates/registry-casework-client/src/wire.rs b/crates/registry-casework-client/src/wire.rs index 65bb6d9f60..403f7418ae 100644 --- a/crates/registry-casework-client/src/wire.rs +++ b/crates/registry-casework-client/src/wire.rs @@ -198,6 +198,8 @@ struct ReviewStagePolicyWire { outcomes: Option>, #[serde(default)] negative_decisions: registry_casework_core::ReviewNegativeDecisionMode, + #[serde(default, skip_serializing_if = "Option::is_none")] + asks: Option, #[serde(default)] exclude_initiator: bool, #[serde(default)] @@ -226,6 +228,8 @@ struct ReviewOutcomePolicyWire { #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct ReviewPolicyWire { + #[serde(default, skip_serializing_if = "Option::is_none")] + resubmission: Option, id: String, #[serde(default, skip_serializing_if = "Option::is_none")] label: Option, @@ -659,8 +663,59 @@ response_wire!(ReviewTaskWire => registry_casework_core::ReviewTask { #[serde(default)] staffing_diagnostic: Option, #[serde(default)] decided_by_caller: Option, #[serde(default)] decision_receipt: Option, + #[serde(default)] marker: Option, }); +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct ReviewAskWire { + ask_id: uuid::Uuid, + request_id: uuid::Uuid, + subject: SubjectBindingWire, + text: String, + wants: Vec, + asked_at: chrono::DateTime, + #[serde(default, skip_serializing_if = "Option::is_none")] + due_at: Option>, + state: registry_casework_core::ReviewAskState, + #[serde(default, skip_serializing_if = "Option::is_none")] + answered_at: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + closed_at: Option>, +} + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ReviewTaskAskedWire { + task: ReviewTaskWire, + ask: ReviewAskWire, +} + +impl ClientResponse for registry_casework_core::ReviewTaskAsked { + type Wire = Validated; + + fn from_wire(wire: Self::Wire) -> Self { + wire.into_inner() + } +} + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct ReviewContextAskWire { + ask_id: uuid::Uuid, + task_id: uuid::Uuid, + text: String, + wants: Vec, + asked_at: chrono::DateTime, + #[serde(default, skip_serializing_if = "Option::is_none")] + due_at: Option>, + state: registry_casework_core::ReviewAskState, + #[serde(default, skip_serializing_if = "Option::is_none")] + answered_at: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + answer: Option, +} + #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub(crate) struct ReviewTaskPageWire { @@ -940,6 +995,8 @@ pub(crate) struct ReviewTaskContextWire { #[serde(default)] result_constraints: Option, context: ReviewTaskContextDataWire, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + asks: Vec, } impl ClientResponse for registry_casework_core::ReviewTaskContext { @@ -949,3 +1006,38 @@ impl ClientResponse for registry_casework_core::ReviewTaskContext { wire.into_inner() } } + +#[cfg(test)] +mod fix_round_tests { + use super::*; + + #[test] + fn absent_resubmission_stays_absent_on_the_client_wire() { + let policy: ReviewPolicyWire = serde_json::from_value(serde_json::json!({ + "id":"review", "version":"1", "purpose":"approval", "context":{"mode":"submitted"}, + "stages":[], "retention":{"terminalRetentionDays":1,"accountabilityRetentionDays":1}, "displaySchema":{} + })).unwrap(); + assert!(serde_json::to_value(policy) + .unwrap() + .get("resubmission") + .is_none()); + } + + #[test] + fn reviewer_ask_due_at_survives_client_decoding() { + let value = serde_json::json!({"askId":uuid::Uuid::new_v4(), "taskId":uuid::Uuid::new_v4(), "text":"Why?", "wants":[{"kind":"answer"}], "askedAt":"2026-11-27T00:00:00Z", "dueAt":"2026-11-27T01:00:00Z", "state":"open"}); + let wire: ReviewContextAskWire = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(serde_json::to_value(wire).unwrap()["dueAt"], value["dueAt"]); + } + + #[test] + fn reviewer_ask_answer_survives_client_decoding() { + let value = serde_json::json!({"askId":uuid::Uuid::new_v4(), "taskId":uuid::Uuid::new_v4(), "text":"Why?", "wants":[{"kind":"answer"}], "askedAt":"2026-11-27T00:00:00Z", "state":"answered", + "answeredAt":"2026-11-27T01:00:00Z", "answer":{"text":"Synthetic answer","documents":[],"answeredAt":"2026-11-27T01:00:00Z"}}); + let wire: ReviewContextAskWire = serde_json::from_value(value.clone()).unwrap(); + assert_eq!( + serde_json::to_value(wire).unwrap()["answer"], + value["answer"] + ); + } +} diff --git a/crates/registry-casework-client/tests/http_boundary.rs b/crates/registry-casework-client/tests/http_boundary.rs index 908adbec6d..db38d96c48 100644 --- a/crates/registry-casework-client/tests/http_boundary.rs +++ b/crates/registry-casework-client/tests/http_boundary.rs @@ -242,6 +242,7 @@ fn json_fixture_response(value: Value) -> impl IntoResponse { #[tokio::test] async fn review_policy_refuses_a_valid_snapshot_for_another_identifier() { let snapshot = fixture_closure(ReviewPolicy { + resubmission: Default::default(), id: "returned-kind".to_owned(), label: None, version: "1".to_owned(), @@ -257,6 +258,7 @@ async fn review_policy_refuses_a_valid_snapshot_for_another_identifier() { required_approvals: 1, outcomes: None, negative_decisions: ReviewNegativeDecisionMode::Settle, + asks: None, exclude_initiator: false, exclude_previous_stage_reviewers: false, }], @@ -308,6 +310,7 @@ async fn review_policy_refuses_a_valid_snapshot_for_another_identifier() { #[tokio::test] async fn review_policy_refuses_unverified_governed_response_members() { let snapshot = fixture_closure(ReviewPolicy { + resubmission: Default::default(), id: "requested-kind".to_owned(), label: None, version: "1".to_owned(), @@ -323,6 +326,7 @@ async fn review_policy_refuses_unverified_governed_response_members() { required_approvals: 1, outcomes: None, negative_decisions: ReviewNegativeDecisionMode::Settle, + asks: None, exclude_initiator: false, exclude_previous_stage_reviewers: false, }], @@ -377,6 +381,7 @@ async fn review_policy_refuses_unverified_governed_response_members() { #[tokio::test] async fn review_policy_refuses_duplicate_additive_response_members() { let snapshot = fixture_closure(ReviewPolicy { + resubmission: Default::default(), id: "requested-kind".to_owned(), label: None, version: "1".to_owned(), @@ -392,6 +397,7 @@ async fn review_policy_refuses_duplicate_additive_response_members() { required_approvals: 1, outcomes: None, negative_decisions: ReviewNegativeDecisionMode::Settle, + asks: None, exclude_initiator: false, exclude_previous_stage_reviewers: false, }], @@ -2321,6 +2327,7 @@ async fn review_task_context_preserves_the_frozen_source_neutral_shape() { fn context_body(strategy: ReviewContextPolicy, display_schema: Value, context: Value) -> Value { let snapshot = fixture_closure(ReviewPolicy { + resubmission: Default::default(), id: "standalone-answer".to_owned(), label: None, version: "1".to_owned(), @@ -2336,6 +2343,7 @@ fn context_body(strategy: ReviewContextPolicy, display_schema: Value, context: V required_approvals: 1, outcomes: None, negative_decisions: ReviewNegativeDecisionMode::Settle, + asks: None, exclude_initiator: false, exclude_previous_stage_reviewers: false, }], @@ -3502,6 +3510,7 @@ async fn empty_not_found_response() -> axum::http::Response { async fn task_context_response() -> impl IntoResponse { let snapshot = fixture_closure(ReviewPolicy { + resubmission: Default::default(), id: "standalone-answer".to_owned(), label: None, version: "1".to_owned(), @@ -3517,6 +3526,7 @@ async fn task_context_response() -> impl IntoResponse { required_approvals: 1, outcomes: None, negative_decisions: ReviewNegativeDecisionMode::Settle, + asks: None, exclude_initiator: false, exclude_previous_stage_reviewers: false, }], @@ -3689,3 +3699,189 @@ fn approval_outcomes() -> Vec { result_required: false, }] } + +fn asked_body(task_id: Uuid, revision: i64, marker: Option<&str>, ask_state: &str) -> Value { + let request_id = Uuid::from_u128(9); + let mut task = json!({ + "taskId": task_id, + "requestId": request_id, + "stageIndex": 0, + "stageId": "review", + "queue": "reviews", + "revision": revision, + "eligibleProfiles": ["staff"], + "state": {"held": {"holder": {"issuer": "https://issuer.example.test", "subject": "someone"}}}, + }); + if let Some(marker) = marker { + task["marker"] = json!(marker); + } + let mut body = json!({ + "task": task, + "ask": { + "askId": Uuid::from_u128(11), + "requestId": request_id, + "subject": { + "source":"registry", "type":"record", "id":"record-1", "version":"1", + "digest":ContentDigest::for_bytes(b"record-1") + }, + "text": "Send the signed form.", + "wants": [{"kind": "answer"}], + "askedAt": "2026-10-14T00:00:00.000000Z", + "state": ask_state, + "futureAskMember": true, + }, + }); + enrich_tasks(&mut body); + body +} + +async fn ask_over( + body: Value, + task_id: Uuid, + ask: ®istry_casework_client::ReviewTaskAskRequest, +) -> Result< + registry_casework_client::CaseworkComplete, + CaseworkClientError, +> { + let app = Router::new() + .route( + "/v1/review-tasks/{task}/asks", + post(task_context_fixture_response), + ) + .with_state(body); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind fixture"); + let address = listener.local_addr().expect("fixture address"); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.expect("serve fixture"); + }); + let client = CaseworkClient::new(CaseworkClientConfig::new( + Url::parse(&format!("http://{address}/")).expect("fixture URL"), + )) + .expect("client"); + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let outcome = client + .ask_applicant(CaseworkAuth::new(&token, "staff"), task_id, 2, "ask-1", ask) + .await; + server.abort(); + outcome +} + +fn the_ask() -> registry_casework_client::ReviewTaskAskRequest { + registry_casework_client::ReviewTaskAskRequest { + text: "Send the signed form.".to_owned(), + wants: vec![registry_casework_client::ReviewAskWant::Answer {}], + } +} + +#[tokio::test] +async fn ask_applicant_returns_the_waiting_task_and_the_open_ask() { + let task_id = Uuid::from_u128(7); + let asked = ask_over( + asked_body(task_id, 3, Some("waiting"), "open"), + task_id, + &the_ask(), + ) + .await + .expect("a conforming ask response") + .value; + assert_eq!( + asked.task.marker, + Some(registry_casework_client::ReviewTaskMarker::Waiting) + ); + assert_eq!( + asked.ask.state, + registry_casework_client::ReviewAskState::Open + ); +} + +#[tokio::test] +async fn ask_applicant_refuses_a_response_that_breaks_its_postconditions() { + let task_id = Uuid::from_u128(7); + let refused = |outcome: Result<_, CaseworkClientError>| { + matches!( + outcome, + Err(CaseworkClientError::Protocol { + status: 200, + failure: CaseworkProtocolFailure::Body, + .. + }) + ) + }; + // The task carries no waiting marker. + assert!(refused( + ask_over(asked_body(task_id, 3, None, "open"), task_id, &the_ask()).await + )); + // The revision did not advance by one. + assert!(refused( + ask_over( + asked_body(task_id, 4, Some("waiting"), "open"), + task_id, + &the_ask() + ) + .await + )); + // The ask is not open. + assert!(refused( + ask_over( + asked_body(task_id, 3, Some("waiting"), "answered"), + task_id, + &the_ask() + ) + .await + )); + // The response is for another task. + assert!(refused( + ask_over( + asked_body(Uuid::from_u128(8), 3, Some("waiting"), "open"), + task_id, + &the_ask() + ) + .await + )); +} + +#[tokio::test] +async fn ask_applicant_refuses_an_invalid_ask_before_sending() { + let task_id = Uuid::from_u128(7); + let mut ask = the_ask(); + ask.text = String::new(); + assert!(matches!( + ask_over( + asked_body(task_id, 3, Some("waiting"), "open"), + task_id, + &ask + ) + .await, + Err(CaseworkClientError::InvalidRequest { .. }) + )); +} + +#[tokio::test] +async fn review_task_context_carries_the_asks_and_tasks_the_marker() { + let mut body = context_body( + ReviewContextPolicy::Submitted, + json!({ + "type": "object", + "additionalProperties": false, + "properties": {"summary": {"type": "string"}} + }), + json!({"mode": "submitted", "snapshot": {"summary": "Frozen review"}}), + ); + body["asks"] = json!([{ + "askId": Uuid::from_u128(11), + "taskId": Uuid::nil(), + "text": "Send the signed form.", + "wants": [{"kind": "document"}], + "askedAt": "2026-10-14T00:00:00Z", + "state": "answered", + "answeredAt": "2026-10-14T01:00:00Z", + }]); + let context = serve_context(body).await.expect("context with asks").value; + assert_eq!(context.asks.len(), 1); + assert_eq!( + context.asks[0].state, + registry_casework_client::ReviewAskState::Answered + ); +} diff --git a/crates/registry-casework-core/examples/wire-schemas.rs b/crates/registry-casework-core/examples/wire-schemas.rs index 08c2f185d7..0b2cb9f75d 100644 --- a/crates/registry-casework-core/examples/wire-schemas.rs +++ b/crates/registry-casework-core/examples/wire-schemas.rs @@ -57,6 +57,8 @@ fn main() -> Result<(), Box> { ReviewCreateRequest, ReviewCancelRequest, ReviewTaskDecisionRequest, + ReviewTaskAskRequest, + ReviewAskAnswer, ReviewTaskDraftInput, ReviewRequestQuery, AssignmentRequest, @@ -80,6 +82,9 @@ fn main() -> Result<(), Box> { ReviewRequestView, ReviewResult, ReviewResultFeedPage, + ReviewAskFeedPage, + ReviewAsk, + ReviewTaskAsked, ReviewCancelResponse, ReviewTask, ReviewTaskPage, diff --git a/crates/registry-casework-core/src/adapter.rs b/crates/registry-casework-core/src/adapter.rs index 3c25503b15..76677940b3 100644 --- a/crates/registry-casework-core/src/adapter.rs +++ b/crates/registry-casework-core/src/adapter.rs @@ -20,6 +20,9 @@ pub struct ReviewContextIdentity { /// The caller's bearer is borrowed for this read and cannot become a stored credential. #[derive(Debug)] pub struct HumanDisplayRequest<'a> { + /// Request live applicant answers only for a displayed task context. + /// Preflight and inbox observations omit them. + pub include_answers: bool, pub identity: &'a ReviewContextIdentity, pub source_profile_id: &'a str, pub credential: EphemeralCredential<'a>, @@ -110,6 +113,9 @@ pub struct HumanDisplayObservation { pub reviewable: bool, pub display_reference: Option, pub fields: BTreeMap, + /// Read live for task-context disclosure, never part of authored display fields. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub answers: BTreeMap, } /// Status deliberately contains no business fields or display reference. @@ -210,6 +216,7 @@ pub trait ReviewContextProvider: Send + Sync { for identity in identities { results.push( self.human_display(HumanDisplayRequest { + include_answers: false, identity, source_profile_id, credential: EphemeralCredential::new(credential), @@ -345,6 +352,27 @@ mod tests { ); } + #[test] + fn human_source_answers_are_a_sibling_of_authored_fields() { + let digest = format!("sha256:{}", "a".repeat(64)); + let ask = uuid::Uuid::new_v4(); + let value = serde_json::json!({ + "identity":{"subject":{"source":"source","type":"proposal","id":"subject","version":"1","digest":digest}, + "contract":{"id":"urn:context","revision":digest,"schemaDigest":digest}}, + "reviewable":true,"displayReference":null,"fields":{"summary":"Synthetic summary"}, + "answers":{(ask.to_string()):{"text":"Synthetic answer","documents":[],"answeredAt":"2026-11-27T10:00:00Z"}} + }); + let observed = serde_json::from_value::(value.clone()); + assert!( + observed.is_ok(), + "intrinsic answers must not be authored fields: {:?}", + observed.err() + ); + let emitted = serde_json::to_value(observed.unwrap()).unwrap(); + assert_eq!(emitted["answers"], value["answers"]); + assert_eq!(emitted["fields"], value["fields"]); + } + #[test] fn delegated_display_is_a_distinct_default_denial() { let digest = diff --git a/crates/registry-casework-core/src/config.rs b/crates/registry-casework-core/src/config.rs index eece1a3f27..63f5c447cb 100644 --- a/crates/registry-casework-core/src/config.rs +++ b/crates/registry-casework-core/src/config.rs @@ -1445,6 +1445,7 @@ impl CaseworkProject { } } let mut exclusion_reported = producer.trusted_initiator_issuer.is_some(); + let mut asks_reported = producer.reads_asks; for (policy_index, policy_id) in producer.review_policies.iter().enumerate() { let Some(policy) = self .review_policies @@ -1478,6 +1479,25 @@ impl CaseworkProject { ), ); } + if !asks_reported { + if let Some(stage_index) = + policy.stages.iter().position(|stage| stage.asks.is_some()) + { + findings.add( + ConfigFinding::new( + "casework.review-producer.asks-not-read", + format!("{at}/readsAsks"), + "a review policy this producer submits lets a stage ask the applicant, and this producer does not read asks", + "Write readsAsks: true on the producer, or remove asks from the stage.", + ) + .with_related( + format!("{}/stages/{stage_index}/asks", keyed("reviewPolicies", &policy.id)), + "asks is written here", + ), + ); + asks_reported = true; + } + } if !exclusion_reported { if let Some(stage_index) = policy .stages @@ -1955,6 +1975,12 @@ pub struct ReviewProducerPolicy { pub retention: ProducerRetention, #[serde(default, skip_serializing_if = "Option::is_none")] pub completion: Option, + /// Whether this producer reads reviewer asks through the ask feed and + /// answers them. A review policy whose stage declares `asks` needs it + /// on every producer that submits to the policy. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + #[cfg_attr(feature = "schema", schemars(extend("default" = false)))] + pub reads_asks: bool, } /// How long Casework keeps what a producer needs to recover a submission. diff --git a/crates/registry-casework-core/src/lib.rs b/crates/registry-casework-core/src/lib.rs index 719f3ce911..7e8ad60cd9 100644 --- a/crates/registry-casework-core/src/lib.rs +++ b/crates/registry-casework-core/src/lib.rs @@ -15,6 +15,7 @@ mod lifecycle; mod model; mod policy; mod review; +mod review_answer; mod routing; #[cfg(feature = "schema")] pub mod schema; @@ -45,6 +46,7 @@ pub use registry_platform_calendar::{ pub use registry_review_protocol as review_protocol; pub use registry_review_protocol::*; pub use review::*; +pub use review_answer::*; pub use routing::*; pub use staffing::*; pub use task_grant::*; diff --git a/crates/registry-casework-core/src/review.rs b/crates/registry-casework-core/src/review.rs index 3e323b22c6..14cfcb3019 100644 --- a/crates/registry-casework-core/src/review.rs +++ b/crates/registry-casework-core/src/review.rs @@ -262,12 +262,66 @@ pub struct ReviewStagePolicy { #[serde(default, skip_serializing_if = "ReviewNegativeDecisionMode::is_settle")] #[cfg_attr(feature = "schema", schemars(extend("default" = "settle")))] pub negative_decisions: ReviewNegativeDecisionMode, + /// Lets the reviewer who holds a task at this stage ask the subject's + /// owner for more. Omission offers no ask and keeps the policy bytes + /// unchanged. Only an approval policy may declare it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub asks: Option, #[serde(default)] pub exclude_initiator: bool, #[serde(default)] pub exclude_previous_stage_reviewers: bool, } +/// `asks: {}` offers an ask without a deadline or clock pause. +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[cfg_attr( + feature = "schema", + schemars(extend("allOf" = [{ + "if": {"properties": {"pauseClocks": {"const": true}}, "required": ["pauseClocks"]}, + "then": {"required": ["answerWithin"]} + }])) +)] +pub struct ReviewStageAsksPolicy { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub answer_within: Option, + #[serde(default, skip_serializing_if = "ReviewAskOnDue::is_default")] + pub on_due: ReviewAskOnDue, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub pause_clocks: bool, +} + +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum ReviewAskOnDue { + #[default] + ReturnToReviewer, +} + +impl ReviewAskOnDue { + const fn is_default(&self) -> bool { + matches!(self, Self::ReturnToReviewer) + } +} + +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum ReviewResubmissionPolicy { + #[default] + FirstStage, + ResumeAtReturningStage, +} + +impl ReviewResubmissionPolicy { + const fn is_default(&self) -> bool { + matches!(self, Self::FirstStage) + } +} + #[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "kebab-case")] @@ -445,6 +499,8 @@ impl ReviewStagePolicy { #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ReviewPolicy { + #[serde(default, skip_serializing_if = "ReviewResubmissionPolicy::is_default")] + pub resubmission: ReviewResubmissionPolicy, #[serde(deserialize_with = "crate::typed::local_id")] #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] pub id: String, @@ -668,6 +724,35 @@ impl ReviewPolicy { } tag(ReviewPolicyError::FinalStageAdvisory, advisory_stages); + let mut asks = Findings::default(); + for (index, stage) in self.stages.iter().enumerate() { + if stage + .asks + .as_ref() + .is_some_and(|asks| asks.pause_clocks && asks.answer_within.is_none()) + { + asks.push( + "casework.review-policy.ask-pause-requires-answer-within", + format!("/stages/{index}/asks/answerWithin"), + "pausing clocks requires an ask deadline", + "Set answerWithin on this stage's asks, or disable pauseClocks.", + ); + } + } + if self.purpose == ReviewPurpose::Answer { + for (index, stage) in self.stages.iter().enumerate() { + if stage.asks.is_some() { + asks.push( + "casework.review-policy.asks-in-answer-policy", + format!("/stages/{index}/asks"), + "an answer review policy cannot let a stage ask the applicant", + "Remove asks, or make the review policy's purpose approval.", + ); + } + } + } + tag(ReviewPolicyError::StageAsks, asks); + match self.purpose { ReviewPurpose::Approval => { let mut payload = Findings::default(); @@ -917,6 +1002,7 @@ impl ReviewPolicy { dependencies: crate::ReviewPolicyDependencies, ) -> Result { let snapshot = ReviewPolicyClosure { + resubmission: self.resubmission, identity: ReviewPolicyIdentity { id: self.id.clone(), version: self.version.clone(), @@ -954,6 +1040,8 @@ pub struct ReviewPolicyIdentity { #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ReviewPolicyClosure { + #[serde(default, skip_serializing_if = "ReviewResubmissionPolicy::is_default")] + pub resubmission: ReviewResubmissionPolicy, pub dependencies: crate::ReviewPolicyDependencies, #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option, @@ -1113,6 +1201,7 @@ impl ReviewPolicyClosure { fn as_policy(&self) -> ReviewPolicy { ReviewPolicy { + resubmission: self.resubmission, id: self.identity.id.clone(), label: self.label.clone(), version: self.identity.version.clone(), @@ -1230,6 +1319,98 @@ pub struct ReviewTask { /// context remains subject to the source's current disclosure. #[serde(default, skip_serializing_if = "Option::is_none")] pub decision_receipt: Option, + /// An ask is waiting for the applicant, answered, or expired. The marker stays with the task + /// through release and reassignment and clears when the task is decided. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub marker: Option, +} + +/// What an ask of the applicant means for the task that made it. +#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum ReviewTaskMarker { + Waiting, + Answered, + Expired, +} + +impl ReviewTaskMarker { + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Waiting => "waiting", + Self::Answered => "answered", + Self::Expired => "expired", + } + } +} + +/// A reviewer's ask of the applicant, sent by the task holder. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReviewTaskAskRequest { + #[cfg_attr( + feature = "schema", + schemars( + length(min = 1, max = MAXIMUM_PUBLIC_REASON_BYTES), + extend("x-maximum-utf8-bytes" = MAXIMUM_PUBLIC_REASON_BYTES) + ) + )] + pub text: String, + #[cfg_attr( + feature = "schema", + schemars(length(max = registry_review_protocol::MAXIMUM_ASK_WANTS)) + )] + pub wants: Vec, +} + +impl ReviewTaskAskRequest { + /// The text is plain and bounded like a public reason. The wants are + /// distinct and at most the protocol's bound. + pub fn check(&self) -> Result<(), registry_review_protocol::ProtocolError> { + check_public_reason(&self.text)?; + let distinct = self + .wants + .iter() + .enumerate() + .all(|(index, want)| !self.wants[..index].contains(want)); + if self.wants.len() > registry_review_protocol::MAXIMUM_ASK_WANTS || !distinct { + return Err(registry_review_protocol::ProtocolError::AskWants); + } + Ok(()) + } +} + +/// The ask a holder opened and the task as it now stands. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReviewTaskAsked { + pub task: ReviewTask, + pub ask: registry_review_protocol::ReviewAsk, +} + +/// An ask as a reviewer reads it in the task context. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReviewContextAsk { + pub ask_id: Uuid, + /// The task that asked. + pub task_id: Uuid, + pub text: String, + pub wants: Vec, + pub asked_at: DateTime, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub due_at: Option>, + pub state: registry_review_protocol::ReviewAskState, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub answered_at: Option>, + /// Live source content. Casework retains only its own answer notification time. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub answer: Option, } #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] @@ -1345,6 +1526,9 @@ pub struct ReviewTaskContext { #[serde(default, skip_serializing_if = "Option::is_none")] pub result_constraints: Option, pub context: ReviewTaskContextData, + /// The asks of the applicant on this request, oldest first. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub asks: Vec, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] @@ -1434,6 +1618,7 @@ pub struct ReviewAccountabilityRecord { #[serde(rename_all = "kebab-case")] pub enum ReviewClockState { Running, + Paused, Completed, Cancelled, SourceFactsMissing, @@ -1666,12 +1851,28 @@ pub struct ReviewProgress { pub active_stage: u16, #[serde(default)] pub decisions: Vec, + /// Reviewers who decided a stage, up to and including the returning stage, + /// of the earlier rounds a resumed request continues. Each counts as a + /// previous-stage reviewer of every stage of this request above the stage + /// they decided. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub prior_stage_reviewers: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub result_constraints: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub settlement: Option, } +/// A reviewer of an earlier round and the lowest stage index they decided in +/// it. Earlier rounds' indices are compared with the resumed request's stages. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PriorStageReviewer { + pub reviewer: IssuerPrincipal, + pub stage_index: u16, +} + impl ReviewProgress { pub fn new( request_id: Uuid, @@ -1688,6 +1889,7 @@ impl ReviewProgress { initiator, active_stage: 0, decisions: Vec::new(), + prior_stage_reviewers: Vec::new(), result_constraints, settlement: None, }) @@ -1785,10 +1987,11 @@ pub fn record_review_decision( return Err(ReviewDecisionError::InitiatorExcluded); } if stage.exclude_previous_stage_reviewers - && progress - .decisions - .iter() - .any(|recorded| recorded.stage_id != stage.id && recorded.reviewer == decision.reviewer) + && (progress.decisions.iter().any(|recorded| { + recorded.stage_id != stage.id && recorded.reviewer == decision.reviewer + }) || progress.prior_stage_reviewers.iter().any(|prior| { + prior.reviewer == decision.reviewer && prior.stage_index < progress.active_stage + })) { return Err(ReviewDecisionError::PreviousStageReviewerExcluded); } @@ -2018,6 +2221,8 @@ pub enum ReviewPolicyError { Stages, #[error("the final review stage cannot be advisory")] FinalStageAdvisory, + #[error("stage asks require an approval policy and a due date when pausing clocks")] + StageAsks, #[error("review stage identifiers, queues, or deciding profiles are invalid")] StageIdentity, #[error("review clock identifiers must be unique and bounded")] @@ -2992,6 +3197,7 @@ mod tests { required_approvals, outcomes: None, negative_decisions: ReviewNegativeDecisionMode::Settle, + asks: None, exclude_initiator: true, exclude_previous_stage_reviewers: true, } @@ -2999,6 +3205,7 @@ mod tests { fn approval_policy(stages: Vec) -> ReviewPolicy { ReviewPolicy { + resubmission: ReviewResubmissionPolicy::default(), id: "registry-correction".to_owned(), label: None, version: "1".to_owned(), @@ -3049,6 +3256,7 @@ mod tests { fn answer_policy() -> ReviewPolicy { ReviewPolicy { + resubmission: ReviewResubmissionPolicy::default(), id: "standalone-question".to_owned(), label: None, version: "1".to_owned(), @@ -3116,6 +3324,7 @@ mod tests { staffing_diagnostic: None, decided_by_caller: None, decision_receipt: None, + marker: None, } } @@ -3340,6 +3549,54 @@ mod tests { ); } + #[test] + fn a_resumed_request_excludes_reviewers_of_the_earlier_rounds_prior_stages() { + // (earlier round's stage, active stage, stage flag, excluded) + for (decided_stage, active_stage, exclude, excluded) in [ + (0, 1, true, true), + (0, 1, false, false), + // A reviewer of the returning stage may review it again. + (1, 1, true, false), + (1, 2, true, true), + (1, 2, false, false), + ] { + let stages = ["first", "second", "third"] + .into_iter() + .map(|id| { + let mut policy = stage(id, 1); + policy.exclude_previous_stage_reviewers = exclude; + policy + }) + .collect(); + let snapshot = approval_policy(stages) + .closure_with(crate::ReviewPolicyDependencies::default()) + .unwrap(); + let request_id = Uuid::from_u128(101); + let mut progress = ReviewProgress::new(request_id, None, None, &snapshot).unwrap(); + progress.active_stage = active_stage; + progress.prior_stage_reviewers = vec![PriorStageReviewer { + reviewer: person("a"), + stage_index: decided_stage, + }]; + let stage_id = snapshot.stages[usize::from(active_stage)].id.clone(); + let returning = task(request_id, active_stage, &stage_id, 1, "a"); + let decided = record_review_decision( + &snapshot, + &mut progress, + &returning, + approve(&returning, person("a")), + ); + if excluded { + assert_eq!( + decided, + Err(ReviewDecisionError::PreviousStageReviewerExcluded) + ); + } else { + assert!(decided.is_ok(), "{decided:?}"); + } + } + } + #[test] fn empty_or_zero_count_stages_are_refused_and_insufficient_staffing_stays_open() { assert_eq!( @@ -3485,6 +3742,7 @@ mod tests { required_approvals: MAXIMUM_REVIEW_APPROVALS_PER_STAGE, outcomes: None, negative_decisions: ReviewNegativeDecisionMode::Settle, + asks: None, exclude_initiator: true, exclude_previous_stage_reviewers: true, }) @@ -4450,6 +4708,142 @@ mod tests { ); } + #[test] + fn a_stage_without_asks_keeps_its_policy_bytes_and_digest() { + let plain = approval_policy(vec![stage("review", 1)]); + let encoded = serde_json::to_value(&plain.stages[0]).unwrap(); + assert!(encoded.get("asks").is_none()); + + let mut asking = plain.clone(); + asking.stages[0].asks = Some(ReviewStageAsksPolicy::default()); + let encoded = serde_json::to_value(&asking.stages[0]).unwrap(); + assert_eq!(encoded["asks"], json!({})); + let decoded: ReviewStagePolicy = serde_json::from_value(encoded).unwrap(); + assert_eq!(decoded.asks, Some(ReviewStageAsksPolicy::default())); + + let defaults = crate::ReviewPolicyDependencies::default(); + let plain_digest = plain.digest_with(&defaults).unwrap(); + assert_ne!(plain_digest, asking.digest_with(&defaults).unwrap()); + // The same policy without the member decodes and digests as before. + let without: ReviewPolicy = + serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap(); + assert_eq!(plain_digest, without.digest_with(&defaults).unwrap()); + } + + #[test] + fn asks_reject_unknown_options() { + let refused = serde_json::from_value::(json!({ + "id": "review", "queue": "review", "decidingProfiles": ["reviewer"], + "requiredApprovals": 1, "asks": {"dueDays": 3} + })); + assert!(refused.is_err()); + } + + #[test] + fn ask_timing_options_and_resubmission_round_trip_without_changing_defaults() { + let original = approval_policy(vec![stage("review", 1)]); + let original_bytes = serde_json::to_value(&original).unwrap(); + let dependencies = crate::ReviewPolicyDependencies::default(); + let original_digest = original.digest_with(&dependencies).unwrap(); + let mut configured = original_bytes.clone(); + configured["stages"][0]["asks"] = json!({ + "answerWithin": {"hours": 48}, + "onDue": "return-to-reviewer", + "pauseClocks": true + }); + configured["resubmission"] = json!("resume-at-returning-stage"); + let policy: ReviewPolicy = serde_json::from_value(configured).expect("timing options"); + let encoded = serde_json::to_value(&policy).unwrap(); + assert_eq!( + encoded["stages"][0]["asks"]["answerWithin"], + json!({"hours": 48}) + ); + assert_eq!(encoded["stages"][0]["asks"]["pauseClocks"], true); + assert_eq!(encoded["resubmission"], "resume-at-returning-stage"); + assert_ne!(policy.digest_with(&dependencies).unwrap(), original_digest); + let mut defaults = original_bytes.clone(); + defaults["resubmission"] = json!("first-stage"); + let defaults: ReviewPolicy = serde_json::from_value(defaults).unwrap(); + assert_eq!(serde_json::to_value(&defaults).unwrap(), original_bytes); + assert_eq!( + defaults.digest_with(&dependencies).unwrap(), + original_digest + ); + let asks: ReviewStageAsksPolicy = serde_json::from_value(json!({ + "pauseClocks": false, "onDue": "return-to-reviewer" + })) + .unwrap(); + assert_eq!(serde_json::to_value(asks).unwrap(), json!({})); + } + + #[test] + fn only_an_approval_policy_may_declare_asks() { + let mut approval = approval_policy(vec![stage("review", 1)]); + approval.stages[0].asks = Some(ReviewStageAsksPolicy::default()); + assert_eq!(approval.check(), Ok(())); + + let mut answer = answer_policy(); + answer.stages[0].asks = Some(ReviewStageAsksPolicy::default()); + assert_eq!(answer.check(), Err(ReviewPolicyError::StageAsks)); + let finding = answer + .findings() + .into_iter() + .find(|finding| finding.code == "casework.review-policy.asks-in-answer-policy") + .expect("an answer policy that asks is reported"); + assert_eq!(finding.pointer, "/stages/0/asks"); + } + + #[test] + fn pausing_asks_require_a_due_date() { + let mut policy = approval_policy(vec![stage("review", 1)]); + policy.stages[0].asks = Some(ReviewStageAsksPolicy { + pause_clocks: true, + ..Default::default() + }); + let finding = policy + .findings() + .into_iter() + .find(|finding| { + finding.code == "casework.review-policy.ask-pause-requires-answer-within" + }) + .expect("unbounded clock pause must be reported"); + assert_eq!(finding.pointer, "/stages/0/asks/answerWithin"); + assert_eq!(policy.check(), Err(ReviewPolicyError::StageAsks)); + policy.stages[0].asks.as_mut().unwrap().answer_within = + Some(crate::ElapsedDuration::Hours(1)); + assert_eq!(policy.check(), Ok(())); + } + + #[test] + fn an_ask_request_bounds_its_text_and_wants() { + use registry_review_protocol::ReviewAskWant; + let ask = |text: &str, wants: Vec| ReviewTaskAskRequest { + text: text.to_owned(), + wants, + }; + assert_eq!( + ask("Send the form.", vec![ReviewAskWant::Answer {}]).check(), + Ok(()) + ); + assert_eq!(ask("Send the form.", vec![]).check(), Ok(())); + assert!(ask("", vec![]).check().is_err()); + assert!(ask(" ", vec![]).check().is_err()); + assert!(ask("bell\u{7}", vec![]).check().is_err()); + assert!(ask(&"x".repeat(MAXIMUM_PUBLIC_REASON_BYTES + 1), vec![]) + .check() + .is_err()); + assert!(ask( + "ok", + vec![ReviewAskWant::Answer {}, ReviewAskWant::Answer {}] + ) + .check() + .is_err()); + let refused = serde_json::from_value::( + json!({"text": "ok", "wants": [], "dueAt": "2026-12-01T00:00:00Z"}), + ); + assert!(refused.is_err()); + } + #[test] fn approval_policies_declare_an_approved_outcome() { let mut policy = approval_policy(vec![stage("review", 1)]); diff --git a/crates/registry-casework-core/src/review_answer.rs b/crates/registry-casework-core/src/review_answer.rs new file mode 100644 index 0000000000..77d203ac65 --- /dev/null +++ b/crates/registry-casework-core/src/review_answer.rs @@ -0,0 +1,52 @@ +//! Live source answers, separate from authored display fields and persisted review state. +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReviewContextAnswer { + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schema", schemars(length(max = 2000), extend("x-maximum-utf8-bytes" = 2000)))] + pub text: Option, + #[cfg_attr(feature = "schema", schemars(length(max = 32)))] + pub documents: Vec, + pub answered_at: DateTime, +} + +impl std::fmt::Debug for ReviewContextAnswer { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ReviewContextAnswer") + .field("text", &"") + .field("document_count", &self.documents.len()) + .field("answered_at", &self.answered_at) + .finish() + } +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReviewAnswerDocument { + pub id: String, + #[cfg_attr(feature = "schema", schemars(regex(pattern = "^[0-9a-f]{64}$")))] + pub sha256: String, + pub content_type: String, + pub byte_size: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub verification_status: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub download: Option, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReviewAnswerDownload { + #[cfg_attr(feature = "schema", schemars(regex(pattern = "^GET$")))] + pub method: String, + pub operation: String, + pub access_profile: String, + pub path: String, +} diff --git a/crates/registry-casework-core/src/schema.rs b/crates/registry-casework-core/src/schema.rs index b8ceb6d254..5e61e739eb 100644 --- a/crates/registry-casework-core/src/schema.rs +++ b/crates/registry-casework-core/src/schema.rs @@ -331,6 +331,34 @@ mod tests { .any(|required| required == "negativeDecisions")); } + #[test] + fn project_schema_requires_an_answer_deadline_when_asks_pause_clocks() { + let documents = project_documents().unwrap(); + let document: Value = serde_json::from_str(&documents[PROJECT_SCHEMA_FILE]).unwrap(); + let schema = compiled(&document); + let authored = + include_str!("../../../products/casework/examples/stage-outcomes/casework.yaml"); + let decoded = crate::CaseworkProject::read("casework.yaml", authored.as_bytes()).unwrap(); + let mut project = decoded.document.to_json_value(); + for asks in [ + serde_json::json!({}), + serde_json::json!({"pauseClocks":false}), + serde_json::json!({"pauseClocks":true,"answerWithin":{"hours":1}}), + ] { + project["reviewPolicies"]["grant-review"]["stages"][0]["asks"] = asks; + assert!( + schema.is_valid(&project), + "bounded or unpaused asks remain valid" + ); + } + project["reviewPolicies"]["grant-review"]["stages"][0]["asks"] = + serde_json::json!({"pauseClocks":true}); + assert!( + !schema.is_valid(&project), + "editors must refuse an unbounded clock pause" + ); + } + #[test] fn project_schema_and_reader_refuse_duplicate_stage_outcomes() { let documents = project_documents().unwrap(); diff --git a/crates/registry-casework-core/src/staffing.rs b/crates/registry-casework-core/src/staffing.rs index 7431d46f22..cf446f8909 100644 --- a/crates/registry-casework-core/src/staffing.rs +++ b/crates/registry-casework-core/src/staffing.rs @@ -25,6 +25,9 @@ pub struct ReviewStaffingQuery { pub subject_version: Option, pub subject_digest: Option, pub reference: Option, + /// Lists tasks by their ask marker: waiting, answered, or expired. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub marker: Option, #[serde(default)] pub sort: ReviewTaskSort, pub cursor: Option, @@ -220,6 +223,19 @@ pub struct ReviewClockRecomputeResult { mod tests { use super::*; #[test] + fn a_query_without_a_marker_serializes_without_one() { + // The query is hashed into the staffing cursors it mints, so a query + // that names no marker must hash as it did before markers existed. + let value = serde_json::to_value(ReviewStaffingQuery::default()).unwrap(); + assert!(value.get("marker").is_none()); + let value = serde_json::to_value(ReviewStaffingQuery { + marker: Some(crate::ReviewTaskMarker::Waiting), + ..Default::default() + }) + .unwrap(); + assert_eq!(value["marker"], "waiting"); + } + #[test] fn exact_subject_filter_rejects_partial_binding() { let q = ReviewStaffingQuery { subject_id: Some("canary".into()), diff --git a/crates/registry-casework-core/tests/policy_compiler.rs b/crates/registry-casework-core/tests/policy_compiler.rs index 8ccf6531c3..a54557d1b7 100644 --- a/crates/registry-casework-core/tests/policy_compiler.rs +++ b/crates/registry-casework-core/tests/policy_compiler.rs @@ -891,3 +891,46 @@ fn a_producer_names_its_receipt_retention_in_its_findings() { == "casework.review-producer.receipt-retention-exceeds-result-retention" && item.path == retention)); } + +#[test] +fn a_stage_that_asks_needs_every_producer_of_the_policy_to_read_asks() { + let mut value = project_value(); + value["reviewPolicies"]["notice-review"]["stages"][0]["asks"] = json!({}); + let Err(ConfigLoadError::Refused(report)) = + CaseworkProject::from_slice(&serde_json::to_vec(&value).unwrap()) + else { + panic!("the project must be refused"); + }; + assert!(report + .diagnostics() + .iter() + .any(|item| item.code == "casework.review-producer.asks-not-read" + && item.path == "/trustedProducers/notice-service/readsAsks")); + + value["trustedProducers"]["notice-service"]["readsAsks"] = json!(true); + CaseworkProject::from_slice(&serde_json::to_vec(&value).unwrap()) + .expect("a producer that reads asks may submit to a policy that asks"); +} + +#[test] +fn a_producer_that_does_not_read_asks_is_named_once_however_many_policies_ask() { + let mut value = project_value(); + let mut second = value["reviewPolicies"]["notice-review"].clone(); + second["label"] = json!("notice review copy"); + value["reviewPolicies"]["notice-review"]["stages"][0]["asks"] = json!({}); + second["stages"][0]["asks"] = json!({}); + value["reviewPolicies"]["notice-review-copy"] = second; + value["trustedProducers"]["notice-service"]["reviewPolicies"] = + json!(["notice-review", "notice-review-copy"]); + let Err(ConfigLoadError::Refused(report)) = + CaseworkProject::from_slice(&serde_json::to_vec(&value).unwrap()) + else { + panic!("the project must be refused"); + }; + let named = report + .diagnostics() + .iter() + .filter(|item| item.code == "casework.review-producer.asks-not-read") + .count(); + assert_eq!(named, 1); +} diff --git a/crates/registry-casework/migrations/0202_review_asks.sql b/crates/registry-casework/migrations/0202_review_asks.sql new file mode 100644 index 0000000000..ab8d027c6b --- /dev/null +++ b/crates/registry-casework/migrations/0202_review_asks.sql @@ -0,0 +1,94 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- +-- A reviewer who holds a task can ask the subject's owner for more. The ask +-- belongs to the request and names the task that asked. The producer reads the +-- ask through its own feed and reports the answer without carrying its text. + +CREATE TABLE casework_review_asks ( + ask_id uuid PRIMARY KEY, + request_id uuid NOT NULL REFERENCES casework_review_requests(request_id) ON DELETE CASCADE, + task_id uuid NOT NULL, + stage_index integer NOT NULL CHECK (stage_index >= 0), + text text NOT NULL CHECK (octet_length(text) BETWEEN 1 AND 2000), + wants jsonb NOT NULL CHECK (jsonb_typeof(wants) = 'array' AND jsonb_array_length(wants) <= 8), + state text NOT NULL CHECK (state IN ('open','answered','expired','closed')), + asked_at timestamptz NOT NULL, + asked_by_ref text NOT NULL CHECK (octet_length(asked_by_ref) BETWEEN 1 AND 256), + answered_at timestamptz, + closed_at timestamptz, + due_at timestamptz, + CHECK (due_at IS NULL OR due_at > asked_at), + UNIQUE (ask_id, request_id), + FOREIGN KEY (task_id, request_id, stage_index) + REFERENCES casework_review_tasks(task_id, request_id, stage_index) ON DELETE CASCADE, + CHECK ((state = 'answered') = (answered_at IS NOT NULL)), + CHECK ((state IN ('expired','closed')) = (closed_at IS NOT NULL)), + CHECK (answered_at IS NULL OR answered_at >= asked_at) +); +-- One ask is open on a request at a time. +CREATE UNIQUE INDEX casework_review_ask_open_idx + ON casework_review_asks(request_id) + WHERE state = 'open'; +CREATE INDEX casework_review_ask_request_idx + ON casework_review_asks(request_id, asked_at, ask_id); + +-- The producer's ask feed. An event announces that an ask opened, was answered, +-- expired or closed. The producer reads the ask next. +CREATE TABLE casework_review_ask_events ( + event_id uuid PRIMARY KEY, + feed_position bigint GENERATED ALWAYS AS IDENTITY UNIQUE, + request_id uuid NOT NULL, + ask_id uuid NOT NULL, + producer_id text NOT NULL, + change text NOT NULL CHECK (change IN ('opened','answered','expired','closed')), + changed_at timestamptz NOT NULL, + FOREIGN KEY (ask_id, request_id) + REFERENCES casework_review_asks(ask_id, request_id) ON DELETE CASCADE, + FOREIGN KEY (request_id, producer_id) + REFERENCES casework_review_requests(request_id, producer_id) ON DELETE CASCADE +); +CREATE INDEX casework_review_ask_feed_idx + ON casework_review_ask_events(producer_id, feed_position); +CREATE INDEX casework_review_ask_events_request_idx + ON casework_review_ask_events(request_id); + +-- A task marker tells reviewers that an ask waits for the applicant, was +-- answered or expired. It stays with the task through release and +-- reassignment and clears when the task is decided or closed. +ALTER TABLE casework_review_tasks + ADD COLUMN ask_marker text CHECK (ask_marker IN ('waiting','answered','expired')); +ALTER TABLE casework_review_tasks + ADD CONSTRAINT casework_review_task_ask_marker_check + CHECK (ask_marker IS NULL OR state IN ('open','claimed')); + +CREATE INDEX casework_review_ask_due_idx + ON casework_review_asks(due_at, request_id) WHERE state='open' AND due_at IS NOT NULL; + +ALTER TABLE casework_review_clock_occurrences + DROP CONSTRAINT casework_review_clock_occurrences_state_check, + ADD CONSTRAINT casework_review_clock_occurrences_state_check + CHECK (state IN ('running','paused','completed','cancelled','source-facts-missing')), + ADD COLUMN paused_at timestamptz, + ADD COLUMN paused_duration_micros bigint NOT NULL DEFAULT 0 CHECK (paused_duration_micros >= 0), + ADD COLUMN paused_ask_id uuid, + ADD COLUMN paused_state text CHECK (paused_state IN ('running','source-facts-missing')), + ADD CONSTRAINT casework_review_clock_pause_check + CHECK ((state='paused') = (paused_at IS NOT NULL) + AND (state='paused') = (paused_state IS NOT NULL) + AND (state='paused') = (paused_ask_id IS NOT NULL)); + +-- A request that resumes an earlier round at its returning stage keeps the +-- staff who decided the earlier rounds' stages up to and including that stage, +-- each with the lowest stage index they decided. Each counts as a +-- previous-stage reviewer of every stage of the resumed request above that +-- index, so separation of duties holds across rounds as within one request +-- and outlives the erasure of the earlier round. The rows hold staff +-- identifiers and stage indices only and are erased with the resumed +-- request's own decisions. +CREATE TABLE casework_review_prior_stage_reviewers ( + request_id uuid NOT NULL REFERENCES casework_review_requests(request_id) ON DELETE CASCADE, + actor_issuer text NOT NULL CHECK (octet_length(actor_issuer) BETWEEN 1 AND 2048), + actor_subject text NOT NULL CHECK (octet_length(actor_subject) BETWEEN 1 AND 2048), + stage_index integer NOT NULL CHECK (stage_index BETWEEN 0 AND 65535), + PRIMARY KEY (request_id, actor_issuer, actor_subject) +); diff --git a/crates/registry-casework/src/auth/delegated.rs b/crates/registry-casework/src/auth/delegated.rs index 1f1fba6d1a..84a4d35618 100644 --- a/crates/registry-casework/src/auth/delegated.rs +++ b/crates/registry-casework/src/auth/delegated.rs @@ -76,7 +76,14 @@ impl crate::CaseworkService { Some(&reader.credential_context), Some(&reader.policy_id), ) - .await; + .await + .map(|mut page| { + // A delegated institutional read carries no ask state. + for task in &mut page.items { + task.marker = None; + } + page + }); let terminal = delegated_audit_outcome(&outcome); audit.conclude_without_change(terminal).await?; outcome diff --git a/crates/registry-casework/src/http.rs b/crates/registry-casework/src/http.rs index 0db408d148..d9d0f7dda0 100644 --- a/crates/registry-casework/src/http.rs +++ b/crates/registry-casework/src/http.rs @@ -101,6 +101,15 @@ pub fn router_with_recorder(state: HttpState, recorder: Arc) -> .route( "/v1/review-requests/{request_id}/cancel", post(cancel_review_request), + ) + .route("/v1/review-asks", get(review_ask_feed)) + .route( + "/v1/review-requests/{request_id}/asks/{ask_id}", + get(get_review_ask), + ) + .route( + "/v1/review-requests/{request_id}/asks/{ask_id}/answer", + post(answer_review_ask), ); let app = Router::new() .route(HEALTH_PATH, get(health)) @@ -170,6 +179,7 @@ pub fn router_with_recorder(state: HttpState, recorder: Arc) -> "/v1/review-tasks/{task_id}/decisions", post(decide_review_task), ) + .route("/v1/review-tasks/{task_id}/asks", post(ask_applicant)) .route( "/v1/review-requests/{request_id}/history", get(review_history), @@ -896,6 +906,87 @@ async fn cancel_review_request( .into_response()) } +async fn review_ask_feed( + RequestState(state): RequestState, + headers: HeaderMap, + Query(query): Query, +) -> Result, HttpError> { + reject_source_profile(&headers)?; + let (actor, _) = authenticate(&state, &headers).await?; + Ok(Json( + state + .service + .review_ask_feed(&actor, query.cursor, page_limit(&state, query.limit)?) + .await + .map_err(HttpError::from)?, + )) +} + +async fn get_review_ask( + RequestState(state): RequestState, + headers: HeaderMap, + Path((request_id, ask_id)): Path<(Uuid, Uuid)>, +) -> Result { + reject_source_profile(&headers)?; + let (actor, _) = authenticate(&state, &headers).await?; + match state.service.review_ask(&actor, request_id, ask_id).await { + Ok(ask) => Ok(Json(ask).into_response()), + Err(ReviewRuntimeError::NotFound) => Ok(bare_not_found()), + Err(error) => Err(HttpError::from(error)), + } +} + +async fn answer_review_ask( + RequestState(state): RequestState, + headers: HeaderMap, + Path((request_id, ask_id)): Path<(Uuid, Uuid)>, + StrictJson(answer): StrictJson, +) -> Result { + reject_source_profile(&headers)?; + let (actor, _) = authenticate(&state, &headers).await?; + match state + .service + .answer_review_ask( + &actor, + request_id, + ask_id, + answer, + idempotency_key(&headers)?, + ) + .await + { + Ok(ask) => Ok(Json(ask).into_response()), + Err(ReviewRuntimeError::NotFound) => Ok(bare_not_found()), + Err(error) => Err(HttpError::from(error)), + } +} + +async fn ask_applicant( + RequestState(state): RequestState, + headers: HeaderMap, + Path(task_id): Path, + StrictJson(request): StrictJson, +) -> Result { + let source_profile_id = source_profile_optional(&headers)?; + let (actor, token) = authenticate(&state, &headers).await?; + Ok(Json( + state + .service + .ask_applicant( + &actor, + task_id, + request, + source_profile_id, + token, + if_match(&headers)?, + idempotency_key(&headers)?, + ) + .await + .map_err(HttpError::from)?, + ) + .into_response()) +} + async fn claim_review_task( RequestState(state): RequestState, headers: HeaderMap, @@ -1724,6 +1815,13 @@ pub enum HttpError { SourceBadGateway, SourceVersionMismatch, SourceVersionUnavailable, + ReviewAskAlreadyOpen, + ReviewAskLimitReached, + ReviewAskAnswerTimeInvalid, + ReviewAskNotOffered, + ReviewAskNotOpen, + ReviewAskProducerUnsupported, + ReviewAskTaskInactive, ReviewDistinctApproverRequired, ReviewInitiatorExcluded, ReviewInitiatorRequired, @@ -1797,6 +1895,13 @@ impl From for HttpError { ReviewRuntimeError::SubmissionConflict => Self::ReviewSubmissionConflict, ReviewRuntimeError::ResultExpired => Self::ReviewResultExpired, ReviewRuntimeError::TaskNotHeld => Self::ReviewTaskNotHeld, + ReviewRuntimeError::ReviewAskAlreadyOpen => Self::ReviewAskAlreadyOpen, + ReviewRuntimeError::ReviewAskLimitReached => Self::ReviewAskLimitReached, + ReviewRuntimeError::ReviewAskAnswerTimeInvalid => Self::ReviewAskAnswerTimeInvalid, + ReviewRuntimeError::ReviewAskNotOffered => Self::ReviewAskNotOffered, + ReviewRuntimeError::ReviewAskNotOpen => Self::ReviewAskNotOpen, + ReviewRuntimeError::ReviewAskProducerUnsupported => Self::ReviewAskProducerUnsupported, + ReviewRuntimeError::ReviewAskTaskInactive => Self::ReviewAskTaskInactive, ReviewRuntimeError::DistinctApproverRequired => Self::ReviewDistinctApproverRequired, ReviewRuntimeError::InitiatorExcluded => Self::ReviewInitiatorExcluded, ReviewRuntimeError::InitiatorRequired => Self::ReviewInitiatorRequired, @@ -1871,6 +1976,13 @@ impl HttpError { | Self::SourceVersionMismatch | Self::SourceVersionUnavailable | Self::ReviewInitiatorRequired + | Self::ReviewAskAlreadyOpen + | Self::ReviewAskLimitReached + | Self::ReviewAskAnswerTimeInvalid + | Self::ReviewAskNotOffered + | Self::ReviewAskNotOpen + | Self::ReviewAskProducerUnsupported + | Self::ReviewAskTaskInactive | Self::ReviewResultExpired | Self::ReviewSubmissionConflict | Self::ReviewTaskNotHeld @@ -1934,6 +2046,13 @@ impl HttpError { Self::SourceBadGateway => ProblemCode::SourceBadGateway, Self::SourceVersionMismatch => ProblemCode::SourceVersionMismatch, Self::SourceVersionUnavailable => ProblemCode::SourceVersionUnavailable, + Self::ReviewAskAlreadyOpen => ProblemCode::ReviewAskAlreadyOpen, + Self::ReviewAskLimitReached => ProblemCode::ReviewAskLimitReached, + Self::ReviewAskAnswerTimeInvalid => ProblemCode::ReviewAskAnswerTimeInvalid, + Self::ReviewAskNotOffered => ProblemCode::ReviewAskNotOffered, + Self::ReviewAskNotOpen => ProblemCode::ReviewAskNotOpen, + Self::ReviewAskProducerUnsupported => ProblemCode::ReviewAskProducerUnsupported, + Self::ReviewAskTaskInactive => ProblemCode::ReviewAskTaskInactive, Self::ReviewDistinctApproverRequired => ProblemCode::ReviewDistinctApproverRequired, Self::ReviewInitiatorExcluded => ProblemCode::ReviewInitiatorExcluded, Self::ReviewInitiatorRequired => ProblemCode::ReviewInitiatorRequired, @@ -3075,6 +3194,13 @@ mod tests { HttpError::SourceBadGateway, HttpError::SourceVersionMismatch, HttpError::SourceVersionUnavailable, + HttpError::ReviewAskAlreadyOpen, + HttpError::ReviewAskLimitReached, + HttpError::ReviewAskAnswerTimeInvalid, + HttpError::ReviewAskNotOffered, + HttpError::ReviewAskNotOpen, + HttpError::ReviewAskProducerUnsupported, + HttpError::ReviewAskTaskInactive, HttpError::ReviewDistinctApproverRequired, HttpError::ReviewInitiatorExcluded, HttpError::ReviewInitiatorRequired, diff --git a/crates/registry-casework/src/http/source_credentials.rs b/crates/registry-casework/src/http/source_credentials.rs index a94277ff8b..c12a71f9aa 100644 --- a/crates/registry-casework/src/http/source_credentials.rs +++ b/crates/registry-casework/src/http/source_credentials.rs @@ -66,7 +66,15 @@ fn target(method: &Method, path: &str) -> Option { let admitted = (method == Method::GET && ["", "context", "draft", "task-templates", "task-grants"].contains(&suffix)) || (method == Method::POST - && ["claim", "assign", "delegate", "decisions", "task-grants"].contains(&suffix)) + && [ + "claim", + "assign", + "delegate", + "decisions", + "asks", + "task-grants", + ] + .contains(&suffix)) || ((method == Method::PUT || method == Method::DELETE) && suffix == "draft"); return admitted.then_some(Target::Task(id)); } @@ -237,6 +245,7 @@ impl ReviewContextProvider for VerifiedSourceProvider { } self.inner .human_display(HumanDisplayRequest { + include_answers: request.include_answers, identity: request.identity, source_profile_id: &self.profile, credential: EphemeralCredential::new(&self.token), @@ -313,7 +322,14 @@ mod tests { Some(Target::Task(Uuid::parse_str(id).unwrap())) ); } - for suffix in ["claim", "assign", "delegate", "decisions", "task-grants"] { + for suffix in [ + "claim", + "assign", + "delegate", + "decisions", + "asks", + "task-grants", + ] { assert!(target(&Method::POST, &format!("/v1/review-tasks/{id}/{suffix}")).is_some()); } for method in [Method::PUT, Method::DELETE] { @@ -399,6 +415,7 @@ mod tests { .unwrap() .push(request.credential.expose().to_owned()); Ok(HumanDisplayObservation { + answers: Default::default(), identity: request.identity.clone(), reviewable: true, display_reference: None, @@ -447,6 +464,7 @@ mod tests { }, }; let request = || HumanDisplayRequest { + include_answers: true, identity: &identity, source_profile_id: "source-profile", credential: EphemeralCredential::new("casework-canary"), @@ -462,6 +480,7 @@ mod tests { assert_eq!(tokens, ["source-first-canary", "source-second-canary"]); assert!(first .human_display(HumanDisplayRequest { + include_answers: true, identity: &identity, source_profile_id: "wrong", credential: EphemeralCredential::new("casework-canary") diff --git a/crates/registry-casework/src/problem.rs b/crates/registry-casework/src/problem.rs index 5e44dcec4d..31cb345135 100644 --- a/crates/registry-casework/src/problem.rs +++ b/crates/registry-casework/src/problem.rs @@ -29,6 +29,13 @@ pub enum ProblemCode { RequestNotFound, RequestUnprocessable, RequestUnsupportedMediaType, + ReviewAskAlreadyOpen, + ReviewAskAnswerTimeInvalid, + ReviewAskLimitReached, + ReviewAskNotOffered, + ReviewAskNotOpen, + ReviewAskProducerUnsupported, + ReviewAskTaskInactive, ReviewDistinctApproverRequired, ReviewInitiatorExcluded, ReviewInitiatorRequired, @@ -69,6 +76,13 @@ impl ProblemCode { Self::RequestNotFound, Self::RequestUnprocessable, Self::RequestUnsupportedMediaType, + Self::ReviewAskAlreadyOpen, + Self::ReviewAskAnswerTimeInvalid, + Self::ReviewAskLimitReached, + Self::ReviewAskNotOffered, + Self::ReviewAskNotOpen, + Self::ReviewAskProducerUnsupported, + Self::ReviewAskTaskInactive, Self::ReviewDistinctApproverRequired, Self::ReviewInitiatorExcluded, Self::ReviewInitiatorRequired, @@ -109,6 +123,13 @@ impl ProblemCode { Self::RequestNotFound => REQUEST_NOT_FOUND_PROBLEM, Self::RequestUnprocessable => REQUEST_UNPROCESSABLE_PROBLEM, Self::RequestUnsupportedMediaType => REQUEST_UNSUPPORTED_MEDIA_TYPE_PROBLEM, + Self::ReviewAskAlreadyOpen => "review.ask-already-open", + Self::ReviewAskLimitReached => "review.ask-limit-reached", + Self::ReviewAskAnswerTimeInvalid => "review.ask-answer-time-invalid", + Self::ReviewAskNotOffered => "review.ask-not-offered", + Self::ReviewAskNotOpen => registry_casework_core::REVIEW_ASK_NOT_OPEN_PROBLEM, + Self::ReviewAskProducerUnsupported => "review.ask-producer-unsupported", + Self::ReviewAskTaskInactive => "review.ask-task-inactive", Self::ReviewDistinctApproverRequired => "review.distinct-approver-required", Self::ReviewInitiatorExcluded => "review.initiator-excluded", Self::ReviewInitiatorRequired => "review.initiator-required", @@ -150,6 +171,13 @@ impl ProblemCode { Self::RequestNotFound => "Route not found", Self::RequestUnprocessable => "Request could not be processed", Self::RequestUnsupportedMediaType => "Unsupported media type", + Self::ReviewAskAlreadyOpen => "Review ask already open", + Self::ReviewAskLimitReached => "Review ask limit reached", + Self::ReviewAskAnswerTimeInvalid => "Review ask answer time invalid", + Self::ReviewAskNotOffered => "Review ask not offered", + Self::ReviewAskNotOpen => "Review ask not open", + Self::ReviewAskProducerUnsupported => "Review ask producer unsupported", + Self::ReviewAskTaskInactive => "Review ask task inactive", Self::ReviewDistinctApproverRequired => "Distinct approver required", Self::ReviewInitiatorExcluded => "Review initiator excluded", Self::ReviewInitiatorRequired => "Review initiator required", @@ -211,6 +239,13 @@ Self::RequestUnprocessable=>"The request body does not match the Casework contra Self::RequestUnsupportedMediaType=>{ "Send a JSON request body with Content-Type application/json." }, +Self::ReviewAskAlreadyOpen=>"Wait for the open ask on this request to be answered or closed before asking again.", +Self::ReviewAskLimitReached=>"This review request has reached its limit of 50 asks. Continue the review without opening another ask.", +Self::ReviewAskAnswerTimeInvalid=>"Report the time the applicant's answer was committed: not before the ask was made and no more than five minutes ahead of Casework's clock.", +Self::ReviewAskNotOffered=>"The active stage of this review policy does not let a reviewer ask the applicant.", +Self::ReviewAskNotOpen=>"This ask was already answered or closed, or the applicant answered after its due date.", +Self::ReviewAskProducerUnsupported=>"The producer of this request does not read asks, so the reviewer cannot ask the applicant.", +Self::ReviewAskTaskInactive=>"Ask from a task at the active stage of a request that is still under review.", Self::ReviewDistinctApproverRequired=>"Each approval in this stage must be supplied by a different reviewer.", Self::ReviewInitiatorExcluded=>{ "You submitted this request, and this review stage excludes the person who submitted it. Another reviewer must take it." @@ -270,6 +305,13 @@ Self::ReviewQueryTooBroad=>"Narrow the queue or exact subject query to complete Self::RequestNotFound => 404, Self::RequestUnprocessable => 422, Self::RequestUnsupportedMediaType => 415, + Self::ReviewAskAlreadyOpen => 409, + Self::ReviewAskLimitReached => 409, + Self::ReviewAskAnswerTimeInvalid => 422, + Self::ReviewAskNotOffered => 409, + Self::ReviewAskNotOpen => 409, + Self::ReviewAskProducerUnsupported => 409, + Self::ReviewAskTaskInactive => 409, Self::ReviewDistinctApproverRequired => 403, Self::ReviewInitiatorExcluded => 403, Self::ReviewInitiatorRequired => 422, @@ -357,6 +399,45 @@ const MUTATION: &[ProblemCode] = &[ ProblemCode::AbsenceOverlap, ProblemCode::AbsenceSelfCover, ]; +/// What the producer's answer call can refuse with. +const ASK_ANSWER: &[ProblemCode] = &[ + ProblemCode::AuthenticationRefused, + ProblemCode::ProfileNotAuthorized, + ProblemCode::OperationNotAuthorized, + ProblemCode::RequestInvalid, + ProblemCode::IdempotencyExpired, + ProblemCode::IdempotencyKeyReused, + ProblemCode::ReviewAskAnswerTimeInvalid, + ProblemCode::ReviewAskNotOpen, + ProblemCode::ServiceUnavailable, + ProblemCode::RuntimeFailure, +]; +/// What the reviewer's ask command can refuse with. +const ASK_COMMAND: &[ProblemCode] = &[ + ProblemCode::AuthenticationRefused, + ProblemCode::ProfileNotAuthorized, + ProblemCode::ProfileNotHuman, + ProblemCode::OperationNotAuthorized, + ProblemCode::RequestInvalid, + ProblemCode::RequestNotFound, + ProblemCode::PreconditionRequired, + ProblemCode::PreconditionFailed, + ProblemCode::IdempotencyExpired, + ProblemCode::IdempotencyKeyReused, + ProblemCode::ReviewTaskNotHeld, + ProblemCode::ReviewAskAlreadyOpen, + ProblemCode::ReviewAskLimitReached, + ProblemCode::ReviewAskNotOffered, + ProblemCode::ReviewAskProducerUnsupported, + ProblemCode::ReviewAskTaskInactive, + ProblemCode::SourceVersionMismatch, + ProblemCode::SourceVersionUnavailable, + ProblemCode::SourceBadGateway, + ProblemCode::SourceProfileRequired, + ProblemCode::SourceProfileNotApplicable, + ProblemCode::ServiceUnavailable, + ProblemCode::RuntimeFailure, +]; pub const OPERATION_CONTRACTS: &[OperationContract] = &[ OperationContract { method: "GET", @@ -475,6 +556,42 @@ pub const OPERATION_CONTRACTS: &[OperationContract] = &[ accepts_json: false, problems: READ, }, + OperationContract { + method: "GET", + path: "/v1/review-asks", + success_statuses: &[200], + extracts_path: false, + extracts_query: true, + accepts_json: false, + problems: READ, + }, + OperationContract { + method: "GET", + path: "/v1/review-requests/{request_id}/asks/{ask_id}", + success_statuses: &[200, 404], + extracts_path: true, + extracts_query: false, + accepts_json: false, + problems: READ, + }, + OperationContract { + method: "POST", + path: "/v1/review-requests/{request_id}/asks/{ask_id}/answer", + success_statuses: &[200, 404], + extracts_path: true, + extracts_query: false, + accepts_json: true, + problems: ASK_ANSWER, + }, + OperationContract { + method: "POST", + path: "/v1/review-tasks/{task_id}/asks", + success_statuses: &[200], + extracts_path: true, + extracts_query: false, + accepts_json: true, + problems: ASK_COMMAND, + }, OperationContract { method: "POST", path: "/v1/review-tasks/{task_id}/claim", diff --git a/crates/registry-casework/src/review.rs b/crates/registry-casework/src/review.rs index be918ed818..926bc4bdef 100644 --- a/crates/registry-casework/src/review.rs +++ b/crates/registry-casework/src/review.rs @@ -1,6 +1,10 @@ +mod ask_clocks; +mod asks; mod inbox; mod maintenance; +mod source_answers; mod staffing; +use asks::close_open_asks; use chrono::{DateTime, TimeDelta, Utc}; use deadpool_postgres::GenericClient; use deadpool_postgres::Transaction; @@ -116,6 +120,20 @@ pub enum ReviewRuntimeError { SubmissionConflict, #[error("the retained review result has expired")] ResultExpired, + #[error("the request already has an open ask")] + ReviewAskAlreadyOpen, + #[error("the request has reached its limit of 50 asks")] + ReviewAskLimitReached, + #[error("the answer time precedes the ask or lies in the future")] + ReviewAskAnswerTimeInvalid, + #[error("the stage of this task does not offer asks")] + ReviewAskNotOffered, + #[error("the ask is not open")] + ReviewAskNotOpen, + #[error("the producer of this request does not read asks")] + ReviewAskProducerUnsupported, + #[error("the task is not at the active stage of a request under review")] + ReviewAskTaskInactive, #[error("the review task must be held by the caller")] TaskNotHeld, #[error("the caller initiated this review and its stage excludes them")] @@ -1015,6 +1033,7 @@ impl CaseworkService { && task.decided_by_caller == Some(true) }; let mut retained_author_required = false; + let mut live_answers = std::collections::BTreeMap::new(); let context = match record.context.as_ref().ok_or(ReviewRuntimeError::Corrupt)? { ReviewContext::Submitted { snapshot } => ReviewTaskContextData::Submitted { snapshot: snapshot.clone(), @@ -1053,6 +1072,7 @@ impl CaseworkService { None => { provider .human_display(HumanDisplayRequest { + include_answers: true, identity: &identity, source_profile_id: profile, credential: EphemeralCredential::new(token), @@ -1075,6 +1095,9 @@ impl CaseworkService { .policy .validate_display(&serde_json::to_value(&view.fields)?) .map_err(|error| invalid_provider_display(&record.policy, error))?; + if delegated.is_none() { + live_answers = view.answers; + } ReviewTaskContextData::CurrentSource { reference: binding.reference.clone(), binding_status: ReviewSourceBindingStatus::Current, @@ -1090,6 +1113,20 @@ impl CaseworkService { if retained_author_required && !decision_author(&final_task) { return Err(ReviewRuntimeError::NotFound); } + // Delegated institutional readers get the task context without the + // reviewers' asks of the applicant. + let mut asks = if delegated.is_some() { + Vec::new() + } else { + self.store.review_context_asks(record.request_id).await? + }; + let dropped_answers = source_answers::join(&mut asks, live_answers, delegated.is_some())?; + if dropped_answers != 0 { + tracing::warn!( + dropped_answers, + "Casework dropped unknown or inconsistent source answers" + ); + } Ok(ReviewTaskContext { task_id, request_id: record.request_id, @@ -1099,6 +1136,7 @@ impl CaseworkService { policy_closure: record.policy, result_constraints: record.result_constraints, context, + asks, }) } @@ -1612,6 +1650,7 @@ impl CaseworkService { let view = tokio::time::timeout_at( deadline, provider.human_display(HumanDisplayRequest { + include_answers: false, identity: &identity, source_profile_id: profile, credential: EphemeralCredential::new(token), @@ -1871,7 +1910,7 @@ impl PostgresStore { cursor: Option, limit: usize, ) -> Result { - self.review_tasks_filtered(actor, queue, view, cursor, limit, None) + self.review_tasks_filtered(actor, queue, view, cursor, limit, None, None) .await } @@ -1884,6 +1923,7 @@ impl PostgresStore { cursor: Option, limit: usize, subject: Option<&SubjectBinding>, + marker: Option, ) -> Result { if limit == 0 || limit > 100 || queue.is_some_and(str::is_empty) { return Err(ReviewRuntimeError::Invalid); @@ -1918,7 +1958,7 @@ impl PostgresStore { .query( "SELECT t.task_id,t.request_id,t.stage_index,t.stage_id,t.queue_id,t.state, t.holder_issuer,t.holder_subject,t.revision,r.policy_snapshot, - r.subject_source,r.subject_type,r.subject_id,r.subject_version,r.subject_digest,r.requester_reference,t.deadline_at,t.created_at,t.staffing_diagnostic + r.subject_source,r.subject_type,r.subject_id,r.subject_version,r.subject_digest,r.requester_reference,t.deadline_at,t.created_at,t.staffing_diagnostic,t.ask_marker FROM casework_review_tasks t JOIN casework_review_requests r ON r.request_id=t.request_id JOIN casework_queue_service q ON q.queue_id=t.queue_id @@ -1938,6 +1978,7 @@ impl PostgresStore { AND ($11::uuid IS NULL OR t.request_id=$11) AND ($12::text IS NULL OR (r.subject_source=$12 AND r.subject_type=$13 AND r.subject_id=$14 AND r.subject_version=$15 AND r.subject_digest=$16)) + AND ($17::text IS NULL OR t.ask_marker=$17) ORDER BY t.created_at,t.task_id LIMIT $7", &[ &actor.principal.issuer, @@ -1956,6 +1997,7 @@ impl PostgresStore { &subject.map(|s|s.id.as_str()), &subject.map(|s|s.version.as_str()), &subject.map(|s|s.digest.as_str()), + &marker.map(ReviewTaskMarker::as_str), ], ) .await?; @@ -2004,7 +2046,7 @@ impl PostgresStore { .query( "SELECT t.task_id,t.request_id,t.stage_index,t.stage_id,t.queue_id,t.state, t.holder_issuer,t.holder_subject,t.revision,r.policy_snapshot, - r.subject_source,r.subject_type,r.subject_id,r.subject_version,r.subject_digest,r.requester_reference,t.deadline_at,t.created_at,t.staffing_diagnostic + r.subject_source,r.subject_type,r.subject_id,r.subject_version,r.subject_digest,r.requester_reference,t.deadline_at,t.created_at,t.staffing_diagnostic,t.ask_marker FROM casework_review_decisions d JOIN casework_review_tasks t ON t.task_id=d.task_id JOIN casework_review_requests r ON r.request_id=t.request_id @@ -2197,7 +2239,7 @@ impl PostgresStore { t.holder_issuer,t.holder_subject,t.revision,r.policy_snapshot, r.lifecycle,r.result_available_until,r.result_erased_at, d.decision,d.outcome,d.decided_at, - r.subject_source,r.subject_type,r.subject_id,r.subject_version,r.subject_digest,r.requester_reference,t.deadline_at,t.created_at,t.staffing_diagnostic + r.subject_source,r.subject_type,r.subject_id,r.subject_version,r.subject_digest,r.requester_reference,t.deadline_at,t.created_at,t.staffing_diagnostic,t.ask_marker FROM casework_review_tasks t JOIN casework_review_requests r ON r.request_id=t.request_id JOIN casework_queue_service q ON q.queue_id=t.queue_id @@ -2767,6 +2809,83 @@ impl PostgresStore { }) .collect::, _>>()?; let policy = snapshot; + // The subject lock already serializes submissions. Only this producer's + // earlier round can select a stage, and its approvals are never copied. + // Stages only advance, so the highest-stage changes-requested decision + // is the one that settled a changes-requested request. The reviewers of + // the stages up to and including it stay excluded from the stages above + // the one they decided, where a stage asks for it. + // Erasure removes a later round's subject, so a later round erased + // first (a revision with shorter retention) would no longer match. Any + // later erased request of this producer and policy may be that round, + // so it stops the resumption and the request starts at the first stage. + // The request resumes only when this revision has the earlier round's + // stage ids, in the same order, up to and including the returning + // stage, so earlier stage indices mean the same stages in both rounds. + let returning = if policy.resubmission == ReviewResubmissionPolicy::ResumeAtReturningStage { + let row = transaction + .query_opt( + "SELECT settling.stage_id,r.request_id,settling.stage_index, + jsonb_path_query_array(r.policy_snapshot->'stages','$[*].id') + FROM casework_review_requests r + LEFT JOIN LATERAL ( + SELECT t.stage_id,d.stage_index FROM casework_review_decisions d + JOIN casework_review_tasks t ON t.task_id=d.task_id + WHERE d.request_id=r.request_id AND d.decision='changes-requested' + AND r.lifecycle='changes-requested' + AND r.result_erased_at IS NULL AND r.result_available_until>$8 + AND NOT EXISTS(SELECT 1 FROM casework_review_requests later + WHERE later.producer_id=r.producer_id AND later.policy_id=r.policy_id + AND later.result_erased_at IS NOT NULL + AND (later.created_at,later.request_id)>(r.created_at,r.request_id)) + ORDER BY d.stage_index DESC,d.decided_at DESC,d.decision_id DESC LIMIT 1 + ) settling ON true + WHERE r.producer_id=$1 AND r.producer_issuer=$2 AND r.producer_subject=$3 + AND r.subject_source=$4 AND r.subject_type=$5 AND r.subject_id=$6 + AND r.policy_id=$7 + ORDER BY r.created_at DESC,r.request_id DESC LIMIT 1", + &[ + &producer.id, + &producer.issuer, + &producer.subject, + &request.subject.source, + &request.subject.subject_type, + &request.subject.id, + &request.policy.id, + &now, + ], + ) + .await?; + match row { + Some(row) => match ( + row.get::<_, Option>(0), + row.get::<_, Option>(2), + ) { + (Some(stage_id), Some(settling_index)) => { + let earlier_stage_ids: Vec = + serde_json::from_value(row.get::<_, Value>(3)) + .map_err(|_| ReviewRuntimeError::Corrupt)?; + let index = usize::try_from(settling_index) + .map_err(|_| ReviewRuntimeError::Corrupt)?; + let same_stages = earlier_stage_ids.get(index) == Some(&stage_id) + && policy.stages.len() > index + && policy.stages[..=index] + .iter() + .map(|stage| &stage.id) + .eq(earlier_stage_ids[..=index].iter()); + same_stages + .then(|| (index, stage_id, (row.get::<_, Uuid>(1), settling_index))) + } + _ => None, + }, + None => None, + } + } else { + None + }; + let initial_stage = returning.as_ref().map_or(0, |(index, _, _)| *index); + let initial_stage = + u16::try_from(initial_stage).map_err(|_| ReviewRuntimeError::Corrupt)?; let retained_until = now + TimeDelta::days(i64::from( producer @@ -2871,7 +2990,7 @@ impl PostgresStore { active_stage_index,revision,created_at,updated_at,terminal_at, result_available_until,accountability_retained_until) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18, - $19,$20,$21,$22,$23,'reviewing',0,1,$24,$24,NULL,NULL,NULL)", + $19,$20,$21,$22,$23,'reviewing',$25,1,$24,$24,NULL,NULL,NULL)", &[ &request_id, &producer.id, @@ -2897,6 +3016,7 @@ impl PostgresStore { &completion_destination, &completion_recipient_binding, &now, + &i32::from(initial_stage), ], ) .await?; @@ -2907,8 +3027,35 @@ impl PostgresStore { &[&request_id, &binding_digest], ) .await?; - let tasks = - insert_stage_tasks(&transaction, &self.providers, request_id, &policy, 0, now).await?; + let tasks = insert_stage_tasks( + &transaction, + &self.providers, + request_id, + &policy, + initial_stage, + now, + ) + .await?; + if let Some((_, stage_id, (earlier_request_id, settling_stage_index))) = returning { + transaction.execute( + "INSERT INTO casework_review_history(event_id,request_id,kind,actor_ref,detail,occurred_at) + VALUES($1,$2,'review-resumed-at-stage',NULL,$3,$4)", + &[&Uuid::new_v4(),&request_id,&json!({"stageId":stage_id}),&now], + ).await?; + transaction + .execute( + "INSERT INTO casework_review_prior_stage_reviewers( + request_id,actor_issuer,actor_subject,stage_index) + SELECT $1::uuid,actor_issuer,actor_subject,min(stage_index) FROM ( + SELECT actor_issuer,actor_subject,stage_index FROM casework_review_decisions + WHERE request_id=$2 AND stage_index<=$3 + UNION ALL SELECT actor_issuer,actor_subject,stage_index + FROM casework_review_prior_stage_reviewers WHERE request_id=$2 + ) earlier GROUP BY actor_issuer,actor_subject", + &[&request_id, &earlier_request_id, &settling_stage_index], + ) + .await?; + } insert_initial_review_clocks( &transaction, request_id, @@ -3224,6 +3371,7 @@ impl PostgresStore { &serde_json::to_value(&response)?, ) .await?; + ask_clocks::audit_events(&transaction, request_id, &mut audit).await?; audit.commit(transaction).await?; Ok(response) } @@ -3308,7 +3456,10 @@ impl PostgresStore { .query_opt( "SELECT stage_index FROM casework_review_decisions WHERE request_id=$1 AND actor_issuer=$2 AND actor_subject=$3 - AND (stage_index=$4 OR ($5 AND stage_index<$4)) LIMIT 1", + AND (stage_index=$4 OR ($5 AND stage_index<$4)) + UNION ALL SELECT -1 FROM casework_review_prior_stage_reviewers + WHERE $5 AND request_id=$1 AND actor_issuer=$2 AND actor_subject=$3 AND stage_index<$4 + ORDER BY 1 DESC LIMIT 1", &[ &request_id, &actor.principal.issuer, @@ -3375,7 +3526,7 @@ impl PostgresStore { } let metadata = transaction .query_one( - "SELECT deadline_at,created_at,staffing_diagnostic,state FROM casework_review_tasks WHERE task_id=$1", + "SELECT deadline_at,created_at,staffing_diagnostic,state,ask_marker FROM casework_review_tasks WHERE task_id=$1", &[&task_id], ) .await?; @@ -3398,6 +3549,7 @@ impl PostgresStore { staffing_diagnostic: staffing_diagnostic_from_row(&metadata)?, decided_by_caller: None, decision_receipt: None, + marker: task_marker(metadata.get::<_, Option>(4))?, }; let claim_event_id = Uuid::new_v4(); { @@ -3724,7 +3876,7 @@ impl PostgresStore { )?; let metadata = transaction .query_one( - "SELECT deadline_at,created_at,staffing_diagnostic,state FROM casework_review_tasks WHERE task_id=$1", + "SELECT deadline_at,created_at,staffing_diagnostic,state,ask_marker FROM casework_review_tasks WHERE task_id=$1", &[&task_id], ) .await?; @@ -3749,6 +3901,7 @@ impl PostgresStore { staffing_diagnostic: staffing_diagnostic_from_row(&metadata)?, decided_by_caller: None, decision_receipt: None, + marker: task_marker(metadata.get::<_, Option>(4))?, }; insert_review_idempotency( &transaction, @@ -4155,7 +4308,10 @@ impl PostgresStore { .query_opt( "SELECT 1 FROM casework_review_decisions WHERE request_id=$1 AND actor_issuer=$2 AND actor_subject=$3 - AND stage_index<$4 LIMIT 1", + AND stage_index<$4 + UNION ALL SELECT 1 FROM casework_review_prior_stage_reviewers + WHERE request_id=$1 AND actor_issuer=$2 AND actor_subject=$3 AND stage_index<$4 + LIMIT 1", &[ &request_id, &actor.principal.issuer, @@ -4551,7 +4707,7 @@ impl PostgresStore { .await?; let metadata = transaction .query_one( - "SELECT deadline_at,created_at,staffing_diagnostic,state FROM casework_review_tasks WHERE task_id=$1", + "SELECT deadline_at,created_at,staffing_diagnostic,state,ask_marker FROM casework_review_tasks WHERE task_id=$1", &[&task_id], ) .await?; @@ -4572,6 +4728,7 @@ impl PostgresStore { staffing_diagnostic: staffing_diagnostic_from_row(&metadata)?, decided_by_caller: None, decision_receipt: None, + marker: task_marker(metadata.get::<_, Option>(4))?, }; let actor_ref = actor_reference(&actor.principal); let release_event_id = Uuid::new_v4(); @@ -4695,7 +4852,7 @@ impl PostgresStore { .await?; let metadata = transaction .query_one( - "SELECT deadline_at,created_at,staffing_diagnostic,state FROM casework_review_tasks WHERE task_id=$1", + "SELECT deadline_at,created_at,staffing_diagnostic,state,ask_marker FROM casework_review_tasks WHERE task_id=$1", &[&task_id], ) .await?; @@ -4730,6 +4887,7 @@ impl PostgresStore { staffing_diagnostic: staffing_diagnostic_from_row(&metadata)?, decided_by_caller: None, decision_receipt: None, + marker: task_marker(metadata.get::<_, Option>(4))?, }; check_task_holder(&task.state, &actor.principal).map_err(map_review_decision_error)?; let mut progress = ReviewProgress::new( @@ -4741,6 +4899,8 @@ impl PostgresStore { .map_err(|_| ReviewRuntimeError::Corrupt)?; progress.active_stage = record.active_stage.ok_or(ReviewRuntimeError::Corrupt)?; progress.decisions = load_decisions(&transaction, request_id).await?; + progress.prior_stage_reviewers = + load_prior_stage_reviewers(&transaction, request_id).await?; let decision = Decision { task_id, request_id, @@ -4782,11 +4942,12 @@ impl PostgresStore { transaction .execute( "UPDATE casework_review_tasks - SET state='decided',staffing_diagnostic=NULL,settled_at=$2,revision=revision+1,updated_at=$2 + SET state='decided',ask_marker=NULL,staffing_diagnostic=NULL,settled_at=$2,revision=revision+1,updated_at=$2 WHERE task_id=$1", &[&task_id, &now], ) .await?; + close_open_asks(&transaction, &record, Some(task_id), now).await?; let actor_ref = actor_reference(&actor.principal); let result_digest = result .as_ref() @@ -4837,7 +4998,7 @@ impl PostgresStore { transaction .execute( "UPDATE casework_review_tasks - SET state='closed',staffing_diagnostic=NULL,settled_at=COALESCE(settled_at,$3),updated_at=$3, + SET state='closed',ask_marker=NULL,staffing_diagnostic=NULL,settled_at=COALESCE(settled_at,$3),updated_at=$3, revision=revision+1 WHERE request_id=$1 AND stage_index=$2 AND state IN ('open','claimed')", &[&request_id, &i32::from(stage_index), &now], @@ -4968,6 +5129,7 @@ impl PostgresStore { &serde_json::to_value(&transition)?, ) .await?; + ask_clocks::audit_events(&transaction, request_id, &mut audit).await?; audit.commit(transaction).await?; Ok(transition) } @@ -5352,6 +5514,33 @@ async fn insert_review_activity_clock( Ok(()) } +#[cfg(feature = "postgres-test")] +#[doc(hidden)] +impl PostgresStore { + /// Settle with a supplied application instant for clock-skew regressions. + pub async fn settle_review_at_for_test( + &self, + request_id: Uuid, + now: DateTime, + ) -> Result { + let mut client = self.client().await?; + let transaction = client.transaction().await?; + let record = load_request_by_id(&transaction, request_id, true).await?; + let result = settle_review( + &transaction, + &record, + ReviewResultStatus::Approved, + Some("approved".into()), + None, + None, + now, + ) + .await?; + transaction.commit().await?; + Ok(result) + } +} + async fn settle_review( transaction: &Transaction<'_>, record: &ReviewRequestRecord, @@ -5452,13 +5641,12 @@ async fn settle_review( "INSERT INTO casework_review_completion_outbox( event_id,request_id,destination_id,recipient_binding,generation,state, attempt,next_attempt_at,retained_until) - VALUES($1,$2,$3,$4,1,'pending',0,$5,$6)", + VALUES($1,$2,$3,$4,1,'pending',0,transaction_timestamp(),$5)", &[ &event_id, &record.request_id, &destination, &recipient, - &now, &retained_until, ], ) @@ -5470,12 +5658,13 @@ async fn settle_review( transaction .execute( "UPDATE casework_review_tasks - SET state='closed',staffing_diagnostic=NULL,settled_at=COALESCE(settled_at,$2),updated_at=$2, + SET state='closed',ask_marker=NULL,staffing_diagnostic=NULL,settled_at=COALESCE(settled_at,$2),updated_at=$2, revision=revision+1 WHERE request_id=$1 AND state IN ('open','claimed')", &[&record.request_id, &now], ) .await?; + close_open_asks(transaction, record, None, now).await?; let lifecycle = result_status_name(status); transaction .execute( @@ -5755,6 +5944,18 @@ fn staffing_diagnostic_from_row( } } +fn task_marker( + stored: Option, +) -> Result, ReviewRuntimeError> { + match stored.as_deref() { + None => Ok(None), + Some("waiting") => Ok(Some(registry_casework_core::ReviewTaskMarker::Waiting)), + Some("answered") => Ok(Some(registry_casework_core::ReviewTaskMarker::Answered)), + Some("expired") => Ok(Some(registry_casework_core::ReviewTaskMarker::Expired)), + Some(_) => Err(ReviewRuntimeError::Corrupt), + } +} + fn reviewer_task_from_row( row: &Row, policy: &ReviewPolicyClosure, @@ -5790,6 +5991,7 @@ fn reviewer_task_from_row( staffing_diagnostic: staffing_diagnostic_from_row(row)?, decided_by_caller: None, decision_receipt: None, + marker: task_marker(row.get::<_, Option>("ask_marker"))?, }) } @@ -5893,6 +6095,31 @@ async fn load_decisions( .collect() } +async fn load_prior_stage_reviewers( + transaction: &Transaction<'_>, + request_id: Uuid, +) -> Result, ReviewRuntimeError> { + transaction + .query( + "SELECT actor_issuer,actor_subject,stage_index FROM casework_review_prior_stage_reviewers + WHERE request_id=$1 ORDER BY actor_issuer,actor_subject", + &[&request_id], + ) + .await? + .into_iter() + .map(|row| { + Ok(PriorStageReviewer { + reviewer: IssuerPrincipal { + issuer: row.get(0), + subject: row.get(1), + }, + stage_index: u16::try_from(row.get::<_, i32>(2)) + .map_err(|_| ReviewRuntimeError::Corrupt)?, + }) + }) + .collect() +} + async fn ensure_review_identity_eligible( transaction: &Transaction<'_>, record: &ReviewRequestRecord, @@ -5911,7 +6138,10 @@ async fn ensure_review_identity_eligible( .query_opt( "SELECT 1 FROM casework_review_decisions WHERE request_id=$1 AND actor_issuer=$2 AND actor_subject=$3 - AND (stage_index=$4 OR ($5 AND stage_index<$4)) LIMIT 1", + AND (stage_index=$4 OR ($5 AND stage_index<$4)) + UNION ALL SELECT 1 FROM casework_review_prior_stage_reviewers + WHERE $5 AND request_id=$1 AND actor_issuer=$2 AND actor_subject=$3 AND stage_index<$4 + LIMIT 1", &[ &record.request_id, &person.issuer, @@ -6448,6 +6678,7 @@ fn review_clock_from_row(row: &Row) -> Result(9).as_str() { "running" => ReviewClockState::Running, + "paused" => ReviewClockState::Paused, "completed" => ReviewClockState::Completed, "cancelled" => ReviewClockState::Cancelled, "source-facts-missing" => ReviewClockState::SourceFactsMissing, @@ -6718,7 +6949,7 @@ fn review_service_error(error: ReviewRuntimeError) -> crate::ServiceError { } async fn refresh_review_deadlines( - tx: &Transaction<'_>, + tx: &impl GenericClient, request_id: Uuid, ) -> Result<(), ReviewRuntimeError> { tx.execute("UPDATE casework_review_tasks t SET deadline_at=(SELECT min(c.due_at) FROM casework_review_clock_occurrences c WHERE c.request_id=t.request_id AND (c.task_id=t.task_id OR c.scope='subject') AND c.state IN('running','source-facts-missing')) WHERE t.request_id=$1 AND t.state IN('open','claimed')",&[&request_id]).await?; @@ -6765,6 +6996,10 @@ async fn review_task_staffing_shortfalls( WHERE d.request_id=t.request_id AND d.actor_issuer=m.issuer AND d.actor_subject=m.subject AND (d.stage_index=t.stage_index OR (COALESCE((s.stage->>'excludePreviousStageReviewers')::boolean,false) AND d.stage_index>'excludePreviousStageReviewers')::boolean,false) + AND EXISTS(SELECT 1 FROM casework_review_prior_stage_reviewers p + WHERE p.request_id=t.request_id AND p.actor_issuer=m.issuer AND p.actor_subject=m.subject + AND p.stage_index, +) -> Result<(), ReviewRuntimeError> { + let rows = tx + .query( + "UPDATE casework_review_clock_occurrences SET paused_state=state,state='paused', + paused_at=$2,paused_ask_id=$3,updated_at=$2 + WHERE request_id=$1 AND state IN ('running','source-facts-missing') + RETURNING clock_occurrence_id,clock_id,task_id", + &[&request_id, &now, &ask_id], + ) + .await?; + for row in rows { + insert_history( + tx, + request_id, + &row, + "clock-paused", + json!({"askId":ask_id}), + now, + ) + .await?; + } + refresh_review_deadlines(tx, request_id).await?; + Ok(()) +} + +pub(super) async fn resume( + tx: &impl GenericClient, + request_id: Uuid, + ask_id: Uuid, + now: DateTime, +) -> Result<(), ReviewRuntimeError> { + let rows = tx + .query( + "SELECT clock_occurrence_id,clock_id,task_id,paused_at,paused_state, + due_at,at_risk_at,next_action_at,reminders,steps,anchor_at + FROM casework_review_clock_occurrences + WHERE request_id=$1 AND state='paused' AND paused_ask_id=$2 + ORDER BY clock_occurrence_id FOR UPDATE", + &[&request_id, &ask_id], + ) + .await?; + for row in rows { + let occurrence: Uuid = row.get(0); + let paused_at: DateTime = row.get(3); + let duration = now.signed_duration_since(paused_at).max(TimeDelta::zero()); + let state: String = row.get(4); + let shift = |at: Option>| -> Result<_, ReviewRuntimeError> { + at.map(|at| { + at.checked_add_signed(duration) + .ok_or(ReviewRuntimeError::Corrupt) + }) + .transpose() + }; + let due = shift(row.get(5))?; + let at_risk = shift(row.get(6))?; + let next = shift(row.get(7))?; + let mut reminders: Vec = serde_json::from_value(row.get(8))?; + let mut steps: Vec = serde_json::from_value(row.get(9))?; + // Already applied effects keep their original instants. Only pending + // effects are delayed, and the ledger still prevents double delivery. + let effects = tx.query("SELECT effect_kind,effect_id FROM casework_review_clock_effects WHERE clock_occurrence_id=$1", &[&occurrence]).await?; + let applied = effects + .iter() + .map(|r| (r.get::<_, String>(0), r.get::<_, String>(1))) + .collect::>(); + for reminder in &mut reminders { + if !applied.contains(&("reminder".into(), reminder.id.clone())) { + reminder.at = shift(Some(reminder.at))?.ok_or(ReviewRuntimeError::Corrupt)?; + } + } + for step in &mut steps { + if !applied.contains(&("step".into(), step.id.clone())) { + step.at = shift(Some(step.at))?.ok_or(ReviewRuntimeError::Corrupt)?; + } + } + let anchor: DateTime = row.get(10); + // Keep the original anchor and accumulate the exact wall-time offset. + // Re-evaluation adds this offset after calendar evaluation, since a + // working-day due time cannot be shifted by moving its anchor alone. + let paused_micros = duration + .num_microseconds() + .ok_or(ReviewRuntimeError::Corrupt)?; + tx.execute( + "UPDATE casework_review_clock_occurrences SET state=$2,paused_at=NULL, + paused_state=NULL,paused_ask_id=NULL,due_at=$3,at_risk_at=$4, + next_action_at=$5,reminders=$6,steps=$7,anchor_at=$8,updated_at=$9, + paused_duration_micros=paused_duration_micros+$10 + WHERE clock_occurrence_id=$1", + &[ + &occurrence, + &state, + &due, + &at_risk, + &next, + &serde_json::to_value(reminders)?, + &serde_json::to_value(steps)?, + &anchor, + &now, + &paused_micros, + ], + ) + .await?; + insert_history(tx, request_id, &row, "clock-resumed", json!({ + "askId":ask_id,"pausedSeconds": duration.num_microseconds().ok_or(ReviewRuntimeError::Corrupt)? as f64 / 1_000_000.0 + }), now).await?; + } + refresh_review_deadlines(tx, request_id).await?; + Ok(()) +} + +pub(super) fn shift_evaluation( + evaluation: &mut registry_casework_core::StageClockEvaluation, + paused_micros: i64, +) -> Result<(), ReviewRuntimeError> { + let shift = |at: DateTime| { + at.checked_add_signed(TimeDelta::microseconds(paused_micros)) + .ok_or(ReviewRuntimeError::Corrupt) + }; + evaluation.due_at = shift(evaluation.due_at)?; + evaluation.at_risk_at = evaluation.at_risk_at.map(shift).transpose()?; + for reminder in &mut evaluation.reminders { + reminder.at = shift(reminder.at)?; + } + for step in &mut evaluation.steps { + step.at = shift(step.at)?; + } + Ok(()) +} + +async fn insert_history( + tx: &impl GenericClient, + request_id: Uuid, + row: &Row, + kind: &str, + mut detail: Value, + now: DateTime, +) -> Result<(), ReviewRuntimeError> { + detail["clockOccurrenceId"] = json!(row.get::<_, Uuid>(0)); + detail["clockId"] = json!(row.get::<_, String>(1)); + tx.execute( + "INSERT INTO casework_review_history(event_id,request_id,task_id,kind,actor_ref,detail,occurred_at) + VALUES($1,$2,$3,$4,NULL,$5,$6)", + &[&Uuid::new_v4(),&request_id,&row.get::<_, Option>(2),&kind,&detail,&now], + ).await?; + Ok(()) +} + +/// Caller operations that close asks collect the pause history they produced +/// before committing. Creation already collects every history event it wrote. +pub(super) async fn audit_events( + tx: &impl GenericClient, + request_id: Uuid, + audit: &mut crate::audit::AuditOperation, +) -> Result<(), ReviewRuntimeError> { + for row in tx + .query( + "SELECT event_id,task_id,kind FROM casework_review_history + WHERE request_id=$1 AND kind IN ('clock-paused','clock-resumed') + AND xmin=pg_current_xact_id()::xid ORDER BY event_id", + &[&request_id], + ) + .await? + { + let mut record = json!({"event": format!("casework.review-{}", row.get::<_, String>(2)), "reviewRequestId":request_id,"profileId":"system:clocks"}); + if let Some(task) = row.get::<_, Option>(1) { + record["reviewTaskId"] = json!(task); + } + audit.record(row.get(0), record)?; + } + Ok(()) +} diff --git a/crates/registry-casework/src/review/asks.rs b/crates/registry-casework/src/review/asks.rs new file mode 100644 index 0000000000..f5f360de2f --- /dev/null +++ b/crates/registry-casework/src/review/asks.rs @@ -0,0 +1,797 @@ +//! A reviewer's asks of the applicant. The task holder opens one ask at a time, +//! the producer reads it through its ask feed and reports the answer without +//! carrying its text, and the ask closes with its task or its request. +use super::*; +use chrono::SubsecRound; +use registry_casework_core::{ + ReviewAsk, ReviewAskAnswer, ReviewAskFeedEntry, ReviewAskFeedPage, ReviewAskState, + ReviewAskWant, +}; +use registry_casework_core::{ReviewContextAsk, ReviewTaskAskRequest, ReviewTaskAsked}; + +/// How far ahead of Casework's clock a producer's answer time may lie. The +/// producer records the time it committed the answer, and the two clocks may +/// differ a little. +const ASK_ANSWER_CLOCK_SKEW: TimeDelta = TimeDelta::minutes(5); +const MAXIMUM_ASKS_PER_REQUEST: i64 = 50; + +/// A time Casework stores and then serves or compares. PostgreSQL keeps +/// microseconds and the ask protocol carries them, so a time with a finer clock +/// part is cut before it is stored: otherwise the stored and the served value +/// differ on a platform whose clock reads nanoseconds. +fn stored_time(time: DateTime) -> DateTime { + time.trunc_subsecs(6) +} + +const ASK_COLUMNS: &str = + "ask_id,request_id,task_id,text,wants,state,asked_at,answered_at,closed_at,due_at"; + +impl CaseworkService { + /// Opens an ask from the task the caller holds. + #[allow(clippy::too_many_arguments)] + pub async fn ask_applicant( + &self, + actor: &ActorContext, + task_id: Uuid, + request: ReviewTaskAskRequest, + source_profile_id: Option<&str>, + token: &str, + expected_revision: i64, + idempotency_key: &str, + ) -> Result { + require_human_reviewer(actor)?; + request.check().map_err(|_| ReviewRuntimeError::Invalid)?; + self.preflight_review_source(task_id, source_profile_id, token) + .await?; + let record = self.store.review_request_for_task(task_id).await?; + let producer_reads_asks = self + .project + .trusted_producers + .iter() + .any(|producer| producer.id == record.producer_id && producer.reads_asks); + self.store + .ask_applicant( + actor, + task_id, + request, + producer_reads_asks, + expected_revision, + idempotency_key, + ) + .await + } + + pub async fn review_ask_feed( + &self, + actor: &ActorContext, + cursor: Option, + limit: usize, + ) -> Result { + if limit == 0 || limit > MAXIMUM_REVIEW_FEED_PAGE { + return Err(ReviewRuntimeError::Invalid); + } + let admission = self.producer_for_actor(actor)?; + self.store + .review_ask_feed(&admission.producer, cursor, limit) + .await + } + + pub async fn review_ask( + &self, + actor: &ActorContext, + request_id: Uuid, + ask_id: Uuid, + ) -> Result { + let admission = self.producer_for_actor(actor)?; + self.store + .review_ask(&admission.producer, request_id, ask_id) + .await + } + + pub async fn answer_review_ask( + &self, + actor: &ActorContext, + request_id: Uuid, + ask_id: Uuid, + answer: ReviewAskAnswer, + idempotency_key: &str, + ) -> Result { + answer.check().map_err(|_| ReviewRuntimeError::Invalid)?; + let admission = self.producer_for_actor(actor)?; + self.store + .answer_review_ask( + &admission.producer, + actor, + request_id, + ask_id, + answer, + idempotency_key, + ) + .await + } +} + +impl PostgresStore { + /// Expiry shares the request lock with answering and deciding. The answer + /// time, rather than which transaction wins that lock, decides lateness. + pub(super) async fn expire_due_review_asks( + &self, + maximum: usize, + ) -> Result { + let now = stored_time(Utc::now()); + let limit = + i64::try_from(maximum.clamp(1, 100)).map_err(|_| ReviewRuntimeError::Invalid)?; + let mut client = self.client().await?; + let rows = client + .query( + "SELECT a.ask_id,a.request_id,a.task_id FROM casework_review_asks a + JOIN casework_review_requests r USING(request_id) + WHERE a.state='open' AND a.due_at<$1 AND r.lifecycle='reviewing' + ORDER BY a.due_at,a.ask_id LIMIT $2", + &[&now, &limit], + ) + .await?; + let mut expired = 0; + for row in rows { + // Commit each request before taking another request lock. Holding + // the producer's feed lock while waiting for its next request + // would invert the lock order of an answering producer. + let mut audit = self.begin_background_audit().await?; + let tx = client.transaction().await?; + let ask_id: Uuid = row.get(0); + let request_id: Uuid = row.get(1); + let task_id: Uuid = row.get(2); + if tx.query_opt("SELECT request_id FROM casework_review_requests WHERE request_id=$1 AND lifecycle='reviewing' FOR UPDATE SKIP LOCKED", &[&request_id]).await?.is_none() { + continue; + } + let record = load_request_by_id(&tx, request_id, false).await?; + if tx.execute("UPDATE casework_review_asks SET state='expired',closed_at=$2 WHERE ask_id=$1 AND state='open' AND due_at<$2", &[&ask_id,&now]).await? == 0 { + continue; + } + tx.execute("UPDATE casework_review_tasks SET ask_marker='expired',revision=revision+1,updated_at=$2 WHERE task_id=$1 AND state IN ('open','claimed')", &[&task_id,&now]).await?; + tx.execute("UPDATE casework_review_requests SET revision=revision+1,updated_at=$2 WHERE request_id=$1", &[&request_id,&now]).await?; + insert_ask_event(&tx, &record, ask_id, "expired", now).await?; + super::ask_clocks::resume(&tx, request_id, ask_id, now).await?; + let event_id = Uuid::new_v4(); + tx.execute("INSERT INTO casework_review_history(event_id,request_id,task_id,kind,actor_ref,detail,occurred_at) VALUES($1,$2,$3,'ask-expired',NULL,$4,$5)", &[&event_id,&request_id,&task_id,&json!({"askId":ask_id}),&now]).await?; + audit.record(event_id, json!({"event":"casework.review-ask-expired","profileId":"system:clocks","reviewRequestId":request_id,"reviewTaskId":task_id,"reviewAskId":ask_id}))?; + super::ask_clocks::audit_events(&tx, request_id, &mut audit).await?; + audit.commit(tx).await?; + expired += 1; + } + Ok(expired) + } + + #[allow(clippy::too_many_arguments)] + pub(super) async fn ask_applicant( + &self, + actor: &ActorContext, + task_id: Uuid, + request: ReviewTaskAskRequest, + producer_reads_asks: bool, + expected_revision: i64, + idempotency_key: &str, + ) -> Result { + let now = stored_time(Utc::now()); + let mut audit = self + .begin_audit(crate::audit::request_record( + "review-ask-opened", + Some(actor), + &actor.profile_id, + json!({}), + )) + .await?; + let mut client = self.client().await?; + let transaction = client.transaction().await?; + let request_id = transaction + .query_opt( + "SELECT request_id FROM casework_review_tasks WHERE task_id=$1", + &[&task_id], + ) + .await? + .ok_or(ReviewRuntimeError::NotFound)? + .get::<_, Uuid>(0); + let record = load_request_by_id(&transaction, request_id, true).await?; + ensure_review_mutation_actor_authorized(&transaction, &record, actor, task_id).await?; + let resource = format!("review-task:{task_id}"); + let request_hash = review_request_hash(&(expected_revision, "ask", &request))?; + if let Some(response) = review_idempotent_response( + &transaction, + actor, + "review.task.ask", + &resource, + idempotency_key, + &request_hash, + ) + .await? + { + audit.record_outcome(crate::audit::AuditOutcome::Replayed); + audit.commit(transaction).await?; + return serde_json::from_value(response).map_err(ReviewRuntimeError::from); + } + let row = transaction + .query_one( + "SELECT stage_index,stage_id,queue_id,state,holder_issuer,holder_subject,revision, + deadline_at,created_at,staffing_diagnostic + FROM casework_review_tasks WHERE task_id=$1 FOR UPDATE", + &[&task_id], + ) + .await?; + let stage_index = + u16::try_from(row.get::<_, i32>(0)).map_err(|_| ReviewRuntimeError::Corrupt)?; + if record.lifecycle != ReviewRequestLifecycle::Reviewing + || record.active_stage != Some(stage_index) + { + return Err(ReviewRuntimeError::ReviewAskTaskInactive); + } + if row.get::<_, i64>(6) != expected_revision { + return Err(ReviewRuntimeError::RevisionConflict); + } + if row.get::<_, String>(3) != "claimed" + || row.get::<_, Option>(4).as_deref() != Some(actor.principal.issuer.as_str()) + || row.get::<_, Option>(5).as_deref() != Some(actor.principal.subject.as_str()) + { + return Err(ReviewRuntimeError::TaskNotHeld); + } + let stage = record + .policy + .stages + .get(usize::from(stage_index)) + .ok_or(ReviewRuntimeError::Corrupt)?; + let options = stage.asks.ok_or(ReviewRuntimeError::ReviewAskNotOffered)?; + if !producer_reads_asks { + return Err(ReviewRuntimeError::ReviewAskProducerUnsupported); + } + // The request lock serializes this count with every ask creation, + // across holders, tasks and stages. Terminal asks still count. + let count: i64 = transaction + .query_one( + "SELECT count(*) FROM casework_review_asks WHERE request_id=$1", + &[&request_id], + ) + .await? + .get(0); + if count >= MAXIMUM_ASKS_PER_REQUEST { + return Err(ReviewRuntimeError::ReviewAskLimitReached); + } + let ask_id = Uuid::new_v4(); + let due_at = options + .answer_within + .map(|duration| now + TimeDelta::seconds(duration.seconds())); + let actor_ref = actor_reference(&actor.principal); + let wants = serde_json::to_value(&request.wants)?; + transaction + .execute( + "INSERT INTO casework_review_asks( + ask_id,request_id,task_id,stage_index,text,wants,state,asked_at,asked_by_ref,due_at) + VALUES($1,$2,$3,$4,$5,$6,'open',$7,$8,$9)", + &[ + &ask_id, + &request_id, + &task_id, + &i32::from(stage_index), + &request.text, + &wants, + &now, + &actor_ref, + &due_at, + ], + ) + .await + .map_err(map_open_ask_conflict)?; + insert_ask_event(&transaction, &record, ask_id, "opened", now).await?; + if options.pause_clocks { + super::ask_clocks::pause(&transaction, request_id, ask_id, now).await?; + } + let metadata = transaction + .query_one( + "UPDATE casework_review_tasks + SET ask_marker='waiting',revision=revision+1,updated_at=$2 + WHERE task_id=$1 + RETURNING deadline_at,created_at,staffing_diagnostic,state,ask_marker", + &[&task_id, &now], + ) + .await?; + transaction + .execute( + "UPDATE casework_review_requests SET revision=revision+1,updated_at=$2 + WHERE request_id=$1", + &[&request_id, &now], + ) + .await?; + let task = ReviewTask { + subject: record.subject.clone(), + requester_reference: record.requester_reference.clone(), + deadline_at: metadata.get(0), + created_at: metadata.get(1), + display_reference: None, + task_id, + request_id, + stage_index, + stage_id: row.get(1), + queue: row.get(2), + revision: expected_revision + 1, + eligible_profiles: stage.deciding_profiles.clone(), + state: ReviewTaskState::Held { + holder: actor.principal.clone(), + }, + staffing_diagnostic: staffing_diagnostic_from_row(&metadata)?, + decided_by_caller: None, + decision_receipt: None, + marker: task_marker(metadata.get::<_, Option>(4))?, + }; + let ask = ReviewAsk { + ask_id, + request_id, + subject: record.subject.clone(), + text: request.text, + wants: request.wants, + asked_at: now, + due_at, + state: ReviewAskState::Open, + answered_at: None, + closed_at: None, + }; + ask.check().map_err(|_| ReviewRuntimeError::Corrupt)?; + let history_event_id = Uuid::new_v4(); + transaction + .execute( + "INSERT INTO casework_review_history( + event_id,request_id,task_id,kind,actor_ref,detail,occurred_at) + VALUES($1,$2,$3,'ask-opened',$4,$5,$6)", + &[ + &history_event_id, + &request_id, + &task_id, + &actor_ref, + &json!({"askId": ask_id}), + &now, + ], + ) + .await?; + // The audit record carries identifiers only. The ask text stays in the + // ask row and the producer's copy, so it expires with the review. + audit.record( + history_event_id, + json!({ + "event": "casework.review-ask-opened", + "eventId": history_event_id, + "reviewRequestId": request_id, + "reviewTaskId": task_id, + "reviewAskId": ask_id, + "actor": { + "issuer": actor.principal.issuer, + "subject": actor.principal.subject, + }, + "profileId": actor.profile_id, + }), + )?; + let response = ReviewTaskAsked { task, ask }; + insert_review_idempotency( + &transaction, + request_id, + actor, + "review.task.ask", + &resource, + idempotency_key, + &request_hash, + &serde_json::to_value(&response)?, + ) + .await?; + super::ask_clocks::audit_events(&transaction, request_id, &mut audit).await?; + audit.commit(transaction).await?; + Ok(response) + } + + pub(super) async fn review_ask_feed( + &self, + producer: ®istry_casework_core::ReviewProducerPolicy, + cursor: Option, + limit: usize, + ) -> Result { + let client = self.client().await?; + let position = if let Some(cursor) = cursor { + Some( + client + .query_opt( + "SELECT e.feed_position FROM casework_review_ask_events e + JOIN casework_review_requests r USING(request_id) + WHERE e.producer_id=$1 AND r.producer_issuer=$2 + AND r.producer_subject=$3 AND e.event_id=$4 + AND r.result_erased_at IS NULL + AND (r.result_available_until IS NULL OR r.result_available_until>now())", + &[&producer.id, &producer.issuer, &producer.subject, &cursor], + ) + .await? + .ok_or(ReviewRuntimeError::ResultExpired)? + .get::<_, i64>(0), + ) + } else { + None + }; + let rows = client + .query( + "SELECT e.event_id,e.request_id,e.ask_id,e.changed_at + FROM casework_review_ask_events e + JOIN casework_review_requests r USING(request_id) + WHERE e.producer_id=$1 AND r.producer_issuer=$2 + AND r.producer_subject=$3 AND r.result_erased_at IS NULL + AND (r.result_available_until IS NULL OR r.result_available_until>now()) + AND ($4::bigint IS NULL OR e.feed_position>$4) + ORDER BY e.feed_position LIMIT $5", + &[ + &producer.id, + &producer.issuer, + &producer.subject, + &position, + &i64::try_from(limit + 1).map_err(|_| ReviewRuntimeError::Invalid)?, + ], + ) + .await?; + let next_cursor = (rows.len() > limit).then(|| rows[limit - 1].get::<_, Uuid>(0)); + let items = rows + .into_iter() + .take(limit) + .map(|row| ReviewAskFeedEntry { + event_id: row.get(0), + request_id: row.get(1), + ask_id: row.get(2), + changed_at: row.get(3), + }) + .collect(); + Ok(ReviewAskFeedPage { items, next_cursor }) + } + + pub(super) async fn review_ask( + &self, + producer: ®istry_casework_core::ReviewProducerPolicy, + request_id: Uuid, + ask_id: Uuid, + ) -> Result { + let client = self.client().await?; + let record = load_request_client(&client, producer, request_id).await?; + ensure_ask_retained(&record)?; + let row = client + .query_opt( + &format!( + "SELECT {ASK_COLUMNS} FROM casework_review_asks + WHERE ask_id=$1 AND request_id=$2" + ), + &[&ask_id, &request_id], + ) + .await? + .ok_or(ReviewRuntimeError::NotFound)?; + ask_from_row(&row, &record) + } + + pub(super) async fn answer_review_ask( + &self, + producer: ®istry_casework_core::ReviewProducerPolicy, + actor: &ActorContext, + request_id: Uuid, + ask_id: Uuid, + answer: ReviewAskAnswer, + idempotency_key: &str, + ) -> Result { + let now = stored_time(Utc::now()); + let mut audit = self + .begin_audit(crate::audit::request_record( + "review-ask-answered", + Some(actor), + &actor.profile_id, + json!({}), + )) + .await?; + let mut client = self.client().await?; + let transaction = client.transaction().await?; + let record = load_request(&transaction, producer, request_id, true).await?; + let resource = format!("review-ask:{request_id}:{ask_id}"); + let request_hash = review_request_hash(&answer)?; + // The retention window, the subject binding and the ask's own request + // all hold before a stored response can be returned. + ensure_ask_retained(&record)?; + if record.subject != answer.subject { + return Err(ReviewRuntimeError::NotFound); + } + let row = transaction + .query_opt( + &format!( + "SELECT {ASK_COLUMNS} FROM casework_review_asks + WHERE ask_id=$1 AND request_id=$2 FOR UPDATE" + ), + &[&ask_id, &request_id], + ) + .await? + .ok_or(ReviewRuntimeError::NotFound)?; + if let Some(response) = review_idempotent_response( + &transaction, + actor, + "review.ask.answer", + &resource, + idempotency_key, + &request_hash, + ) + .await? + { + audit.record_outcome(crate::audit::AuditOutcome::Replayed); + audit.commit(transaction).await?; + return serde_json::from_value(response).map_err(ReviewRuntimeError::from); + } + let current = ask_from_row(&row, &record)?; + if record.lifecycle != ReviewRequestLifecycle::Reviewing + || !matches!( + current.state, + ReviewAskState::Open | ReviewAskState::Expired + ) + || current.due_at.is_some_and(|due| answer.answered_at > due) + { + return Err(ReviewRuntimeError::ReviewAskNotOpen); + } + if answer.answered_at < current.asked_at || answer.answered_at > now + ASK_ANSWER_CLOCK_SKEW + { + return Err(ReviewRuntimeError::ReviewAskAnswerTimeInvalid); + } + let task_id = row.get::<_, Uuid>(2); + let task_is_active: bool = transaction + .query_one( + "SELECT state IN ('open','claimed') FROM casework_review_tasks WHERE task_id=$1", + &[&task_id], + ) + .await? + .get(0); + if !task_is_active { + return Err(ReviewRuntimeError::ReviewAskNotOpen); + } + let answered_at = transaction + .query_one( + "UPDATE casework_review_asks SET state='answered',answered_at=$2,closed_at=NULL + WHERE ask_id=$1 RETURNING answered_at", + &[&ask_id, &answer.answered_at], + ) + .await? + .get::<_, DateTime>(0); + transaction + .execute( + "UPDATE casework_review_tasks + SET ask_marker=( + SELECT CASE a.state WHEN 'open' THEN 'waiting' + WHEN 'expired' THEN 'expired' ELSE 'answered' END + FROM casework_review_asks a WHERE a.task_id=$1 + ORDER BY a.asked_at DESC,a.ask_id DESC LIMIT 1 + ),revision=revision+1,updated_at=$2 + WHERE task_id=$1 AND state IN ('open','claimed')", + &[&task_id, &now], + ) + .await?; + transaction + .execute( + "UPDATE casework_review_requests SET revision=revision+1,updated_at=$2 + WHERE request_id=$1", + &[&request_id, &now], + ) + .await?; + insert_ask_event(&transaction, &record, ask_id, "answered", now).await?; + super::ask_clocks::resume(&transaction, request_id, ask_id, now).await?; + let history_event_id = Uuid::new_v4(); + transaction + .execute( + "INSERT INTO casework_review_history( + event_id,request_id,task_id,kind,actor_ref,detail,occurred_at) + VALUES($1,$2,$3,'ask-answered',NULL,$4,$5)", + &[ + &history_event_id, + &request_id, + &task_id, + &json!({"askId": ask_id, "arrivedAfterDue": current.due_at.is_some_and(|due| now > due)}), + &now, + ], + ) + .await?; + audit.record( + history_event_id, + json!({ + "event": "casework.review-ask-answered", + "eventId": history_event_id, + "reviewRequestId": request_id, + "reviewTaskId": task_id, + "reviewAskId": ask_id, + "actor": { + "issuer": actor.principal.issuer, + "subject": actor.principal.subject, + }, + "profileId": actor.profile_id, + }), + )?; + let response = ReviewAsk { + state: ReviewAskState::Answered, + answered_at: Some(answered_at), + closed_at: None, + ..current + }; + response.check().map_err(|_| ReviewRuntimeError::Corrupt)?; + insert_review_idempotency( + &transaction, + request_id, + actor, + "review.ask.answer", + &resource, + idempotency_key, + &request_hash, + &serde_json::to_value(&response)?, + ) + .await?; + super::ask_clocks::audit_events(&transaction, request_id, &mut audit).await?; + audit.commit(transaction).await?; + Ok(response) + } + + /// The asks of a request, oldest first, as its reviewers read them. + pub(super) async fn review_context_asks( + &self, + request_id: Uuid, + ) -> Result, ReviewRuntimeError> { + let client = self.client().await?; + client + .query( + "SELECT ask_id,task_id,text,wants,state,asked_at,answered_at,due_at + FROM casework_review_asks WHERE request_id=$1 ORDER BY asked_at,ask_id", + &[&request_id], + ) + .await? + .iter() + .map(|row| { + Ok(ReviewContextAsk { + answer: None, + ask_id: row.get(0), + task_id: row.get(1), + text: row.get(2), + wants: wants_from_json(row.get(3))?, + state: ask_state(&row.get::<_, String>(4))?, + asked_at: row.get(5), + answered_at: row.get(6), + due_at: row.get(7), + }) + }) + .collect() + } +} + +/// Closes open asks when their task is decided or the request +/// ends. `task_id` limits the close to that task's asks. Every close +/// is announced on the producer's feed in the same transaction. +pub(super) async fn close_open_asks( + transaction: &impl GenericClient, + record: &ReviewRequestRecord, + task_id: Option, + now: DateTime, +) -> Result<(), ReviewRuntimeError> { + let now = stored_time(now); + let closed = transaction + .query( + "UPDATE casework_review_asks SET state='closed',closed_at=$2 + WHERE request_id=$1 AND state='open' + AND ($3::uuid IS NULL OR task_id=$3) + RETURNING ask_id", + &[&record.request_id, &now, &task_id], + ) + .await?; + for row in closed { + let ask_id = row.get(0); + insert_ask_event(transaction, record, ask_id, "closed", now).await?; + super::ask_clocks::resume(transaction, record.request_id, ask_id, now).await?; + } + Ok(()) +} + +async fn insert_ask_event( + transaction: &impl GenericClient, + record: &ReviewRequestRecord, + ask_id: Uuid, + change: &str, + now: DateTime, +) -> Result<(), ReviewRuntimeError> { + // The result feed's per-producer lock, held to commit: feed positions are + // assigned in the order the events commit, so a reader never passes an + // event that commits later. + transaction + .query_one( + "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", + &[&record.producer_id], + ) + .await?; + let now = stored_time(now); + transaction + .execute( + "INSERT INTO casework_review_ask_events( + event_id,request_id,ask_id,producer_id,change,changed_at) + VALUES($1,$2,$3,$4,$5,$6)", + &[ + &Uuid::new_v4(), + &record.request_id, + &ask_id, + &record.producer_id, + &change, + &now, + ], + ) + .await?; + Ok(()) +} + +/// The ask and its events leave with the request's retained result. +fn ensure_ask_retained(record: &ReviewRequestRecord) -> Result<(), ReviewRuntimeError> { + if record.result_erased_at.is_some() + || record + .result_available_until + .is_some_and(|available_until| available_until <= Utc::now()) + { + Err(ReviewRuntimeError::NotFound) + } else { + Ok(()) + } +} + +/// One open ask per request is a storage rule; a second insert that reaches it +/// is the refusal the caller sees. +fn map_open_ask_conflict(error: tokio_postgres::Error) -> ReviewRuntimeError { + if error + .as_db_error() + .is_some_and(|error| error.code() == &tokio_postgres::error::SqlState::UNIQUE_VIOLATION) + { + ReviewRuntimeError::ReviewAskAlreadyOpen + } else { + ReviewRuntimeError::from(error) + } +} + +fn ask_state(stored: &str) -> Result { + match stored { + "open" => Ok(ReviewAskState::Open), + "answered" => Ok(ReviewAskState::Answered), + "expired" => Ok(ReviewAskState::Expired), + "closed" => Ok(ReviewAskState::Closed), + _ => Err(ReviewRuntimeError::Corrupt), + } +} + +fn wants_from_json(stored: Value) -> Result, ReviewRuntimeError> { + serde_json::from_value(stored).map_err(|_| ReviewRuntimeError::Corrupt) +} + +fn ask_from_row(row: &Row, record: &ReviewRequestRecord) -> Result { + let state = ask_state(&row.get::<_, String>(5))?; + let ask = ReviewAsk { + ask_id: row.get(0), + request_id: row.get(1), + subject: record.subject.clone(), + text: row.get(3), + wants: wants_from_json(row.get(4))?, + asked_at: row.get(6), + due_at: row.get(9), + state, + answered_at: row.get(7), + closed_at: row.get(8), + }; + ask.check().map_err(|_| ReviewRuntimeError::Corrupt)?; + Ok(ask) +} + +#[cfg(test)] +mod tests { + use super::stored_time; + use chrono::{TimeZone, Timelike, Utc}; + + #[test] + fn a_stored_time_keeps_no_sub_microsecond_part() { + // A Linux clock reads nanoseconds. PostgreSQL would round the stored + // value, so the served value must be the truncated one. + let read = Utc + .with_ymd_and_hms(2026, 11, 27, 10, 0, 0) + .unwrap() + .with_nanosecond(123_456_789) + .unwrap(); + let stored = stored_time(read); + assert_eq!(stored.nanosecond(), 123_456_000); + assert_eq!(stored_time(stored), stored); + } +} diff --git a/crates/registry-casework/src/review/inbox.rs b/crates/registry-casework/src/review/inbox.rs index 9dd3e0c7f5..411eea1b4e 100644 --- a/crates/registry-casework/src/review/inbox.rs +++ b/crates/registry-casework/src/review/inbox.rs @@ -202,6 +202,12 @@ impl InboxObservations { if let Some(status) = status { self.status.insert(id, status); } + // Inbox hydration retains only invocation-local display facts, + // never the applicant answers used by a task-context read. + let observation = observation.map(|mut view| { + view.answers.clear(); + view + }); self.human.insert(id, observation); } } @@ -316,7 +322,7 @@ impl PostgresStore { t.holder_issuer,t.holder_subject,t.revision,r.policy_snapshot, r.lifecycle,r.result_available_until,r.result_erased_at, d.decision,d.outcome,d.decided_at, - r.subject_source,r.subject_type,r.subject_id,r.subject_version,r.subject_digest,r.requester_reference,t.deadline_at,t.created_at,t.staffing_diagnostic + r.subject_source,r.subject_type,r.subject_id,r.subject_version,r.subject_digest,r.requester_reference,t.deadline_at,t.created_at,t.staffing_diagnostic,t.ask_marker FROM casework_review_tasks t JOIN casework_review_requests r ON r.request_id=t.request_id JOIN casework_queue_service q ON q.queue_id=t.queue_id @@ -434,7 +440,7 @@ impl PostgresStore { .query( &format!("SELECT t.task_id,t.request_id,t.stage_index,t.stage_id,t.queue_id,t.state, t.holder_issuer,t.holder_subject,t.revision,r.policy_snapshot, - r.subject_source,r.subject_type,r.subject_id,r.subject_version,r.subject_digest,r.requester_reference,t.deadline_at,t.created_at,t.staffing_diagnostic + r.subject_source,r.subject_type,r.subject_id,r.subject_version,r.subject_digest,r.requester_reference,t.deadline_at,t.created_at,t.staffing_diagnostic,t.ask_marker FROM casework_review_tasks t JOIN casework_review_requests r ON r.request_id=t.request_id WHERE NOT $6 AND r.result_erased_at IS NULL @@ -452,6 +458,7 @@ impl PostgresStore { AND ($11::uuid IS NULL OR t.request_id=$11) AND ($12::text IS NULL OR (r.subject_source=$12 AND r.subject_type=$13 AND r.subject_id=$14 AND r.subject_version=$15 AND r.subject_digest=$16)) + AND ($17::text IS NULL OR t.ask_marker=$17) ORDER BY {order} LIMIT $7"), &[ &actor.principal.issuer, @@ -470,6 +477,7 @@ impl PostgresStore { &subject.map(|s|s.id.as_str()), &subject.map(|s|s.version.as_str()), &subject.map(|s|s.digest.as_str()), + &query.marker.map(ReviewTaskMarker::as_str), ], ) .await?; diff --git a/crates/registry-casework/src/review/maintenance.rs b/crates/registry-casework/src/review/maintenance.rs index c05442b417..7a5ec25d6e 100644 --- a/crates/registry-casework/src/review/maintenance.rs +++ b/crates/registry-casework/src/review/maintenance.rs @@ -8,6 +8,7 @@ impl CaseworkService { if !self.store.audit_ready().await { return Err(StoreError::AuditUnavailable.into()); } + let expired = self.store.expire_due_review_asks(maximum).await?; let candidates = self.store.due_review_clock_tasks(maximum).await?; let mut verified = Vec::new(); for task_id in candidates { @@ -40,9 +41,11 @@ impl CaseworkService { self.store.defer_review_clock_task(task_id).await?; } } - self.store + let applied = self + .store .process_due_review_clocks(maximum, &verified) - .await + .await?; + Ok(expired + applied) } } impl PostgresStore { @@ -163,7 +166,7 @@ impl PostgresStore { .ok_or(ReviewRuntimeError::Corrupt)?; let Some(occurrence) = transaction .query_opt( - "SELECT policy,state,anchor_at,holiday_document,reminders,steps + "SELECT policy,state,anchor_at,holiday_document,reminders,steps,paused_duration_micros FROM casework_review_clock_occurrences WHERE clock_occurrence_id=$1 AND scope='activity' AND ((state='source-facts-missing' @@ -217,9 +220,10 @@ impl PostgresStore { continue; }; let holiday: HolidaySetDocument = serde_json::from_value(holiday_row.get(0))?; - let evaluated = + let mut evaluated = evaluate_stage_clock(&definition.clock, calendar, &holiday, anchor_at) .map_err(|error| clock_evaluation_error(&definition.clock, error))?; + super::ask_clocks::shift_evaluation(&mut evaluated, occurrence.get(6))?; let next_action_at = next_review_clock_action( &evaluated.reminders, &evaluated.steps, @@ -570,6 +574,14 @@ impl PostgresStore { &[&now, &selected], ) .await?; + transaction + .execute( + "DELETE FROM casework_review_prior_stage_reviewers p USING casework_review_requests r + WHERE p.request_id=r.request_id AND r.request_id=ANY($2) + AND r.result_available_until<=$1", + &[&now, &selected], + ) + .await?; transaction .execute( "UPDATE casework_idempotency i SET response=NULL diff --git a/crates/registry-casework/src/review/source_answers.rs b/crates/registry-casework/src/review/source_answers.rs new file mode 100644 index 0000000000..eb51bece36 --- /dev/null +++ b/crates/registry-casework/src/review/source_answers.rs @@ -0,0 +1,177 @@ +//! Live answers are joined only to this request's asks, outside authored fields. +use super::*; +use std::collections::{BTreeMap, BTreeSet}; + +pub(super) fn join( + asks: &mut Vec, + mut answers: BTreeMap, + delegated: bool, +) -> Result { + if delegated { + asks.clear(); + return Ok(0); + } + let mut inconsistent = 0; + for ask in asks { + ask.answer = None; + if let Some(answer) = answers.remove(&ask.ask_id) { + if validate(&answer).is_err() + || answer.answered_at < ask.asked_at + || ask + .wants + .iter() + .any(|want| matches!(want, ReviewAskWant::Answer {})) + && answer.text.is_none() + || ask + .wants + .iter() + .any(|want| matches!(want, ReviewAskWant::Document {})) + && answer.documents.is_empty() + { + inconsistent += 1; + continue; + } + ask.answer = Some(answer); + } + } + Ok(answers.len() + inconsistent) +} + +fn bounded(value: &str, maximum: usize) -> bool { + !value.trim().is_empty() && value.len() <= maximum && !value.chars().any(char::is_control) +} + +fn validate(answer: &ReviewContextAnswer) -> Result<(), ReviewRuntimeError> { + if answer + .text + .as_ref() + .is_some_and(|text| text.trim().is_empty() || text.len() > 2000 || text.contains('\0')) + || answer.documents.len() > 32 + || !answer + .answered_at + .timestamp_subsec_nanos() + .is_multiple_of(1000) + { + return Err(ReviewRuntimeError::SourceInvalid); + } + let mut ids = BTreeSet::new(); + for document in &answer.documents { + if !bounded(&document.id, 128) + || !ids.insert(&document.id) + || document.sha256.len() != 64 + || !document + .sha256 + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + || !bounded(&document.content_type, 255) + || document.byte_size == 0 + || document.byte_size > 9_007_199_254_740_991 + || document + .verification_status + .as_ref() + .is_some_and(|status| !bounded(status, 32)) + { + return Err(ReviewRuntimeError::SourceInvalid); + } + if let Some(link) = &document.download { + if link.method != "GET" + || !bounded(&link.operation, 128) + || !bounded(&link.access_profile, 128) + || !bounded(&link.path, 8192) + || !link.path.starts_with('/') + || link.path.starts_with("//") + { + return Err(ReviewRuntimeError::SourceInvalid); + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ask() -> ReviewContextAsk { + serde_json::from_value(json!({ + "askId":Uuid::new_v4(),"taskId":Uuid::new_v4(),"text":"Why?", + "wants":[{"kind":"answer"}],"askedAt":"2026-11-27T00:00:00Z","state":"open" + })) + .unwrap() + } + fn answer() -> ReviewContextAnswer { + serde_json::from_value(json!({"text":"Private source answer","documents":[],"answeredAt":"2026-11-27T01:00:00Z"})).unwrap() + } + + #[test] + fn an_inconsistent_answer_is_counted_without_hiding_other_answers_or_fields() { + for malformed in [0, 1, 2] { + let mut asks = vec![ask(), ask()]; + let mut invalid = answer(); + match malformed { + 0 => invalid.answered_at = asks[0].asked_at - chrono::Duration::seconds(1), + 1 => invalid.text = None, + _ => invalid.text = Some(" ".into()), + } + let ids = [asks[0].ask_id, asks[1].ask_id]; + let dropped = join( + &mut asks, + BTreeMap::from([(ids[0], invalid), (ids[1], answer())]), + false, + ); + assert!( + dropped.is_ok(), + "one inconsistent source answer must not fail the context" + ); + assert_eq!(dropped.unwrap(), 1); + assert!(asks[0].answer.is_none()); + assert!(asks[1].answer.is_some()); + assert_eq!(asks[0].text, "Why?"); + } + } + + #[test] + fn source_answer_documents_accept_the_breg_media_type_bound() { + let mut answer = answer(); + answer.documents = serde_json::from_value(json!([{ + "id":"00000000-0000-4000-8000-000000000001", "sha256":"a".repeat(64), + "contentType":format!("{}/{}", "a".repeat(127), "a".repeat(127)), "byteSize":1 + }])) + .unwrap(); + assert!(validate(&answer).is_ok()); + answer.documents[0].content_type.push('a'); + assert!(validate(&answer).is_err()); + } + + #[test] + fn unknown_source_answers_are_counted_and_never_joined_to_another_request() { + let mut asks = vec![ask()]; + let count = join( + &mut asks, + BTreeMap::from([(Uuid::new_v4(), answer())]), + false, + ) + .unwrap(); + assert_eq!(count, 1); + assert!(asks[0].answer.is_none()); + } + + #[test] + fn delegated_reads_discard_questions_and_source_answers() { + let mut asks = vec![ask()]; + let answers = BTreeMap::from([(asks[0].ask_id, answer())]); + assert_eq!(join(&mut asks, answers, true).unwrap(), 0); + assert!(asks.is_empty()); + } + + #[test] + fn every_join_uses_only_the_current_source_observation() { + let mut asks = vec![ask()]; + let answers = BTreeMap::from([(asks[0].ask_id, answer())]); + assert_eq!(join(&mut asks, answers, false).unwrap(), 0); + assert!(asks[0].answer.is_some()); + assert!(!format!("{:?}", asks[0].answer).contains("Private source answer")); + join(&mut asks, BTreeMap::new(), false).unwrap(); + assert!(asks[0].answer.is_none()); + } +} diff --git a/crates/registry-casework/src/review/staffing.rs b/crates/registry-casework/src/review/staffing.rs index 8e990a5bdf..4efe8a9735 100644 --- a/crates/registry-casework/src/review/staffing.rs +++ b/crates/registry-casework/src/review/staffing.rs @@ -27,6 +27,7 @@ impl CaseworkService { return Err(ReviewRuntimeError::Invalid); } query.check().map_err(|_| ReviewRuntimeError::Invalid)?; + refuse_delegated_marker_filter(delegated.is_some(), &query)?; require_human_reviewer(actor)?; if source_profile.is_none() { let policies = self @@ -194,6 +195,7 @@ impl CaseworkService { position, batch_limit, expected_subject.as_ref(), + query.marker, ) .await? }; @@ -808,7 +810,7 @@ async fn calculate_review_clocks( record: &ReviewRequestRecord, task_id: Uuid, ) -> Result, ReviewRuntimeError> { - let rows=tx.query("SELECT clock_occurrence_id,policy,anchor_at,updated_at FROM casework_review_clock_occurrences WHERE request_id=$1 AND task_id=$2 AND scope='activity' AND state IN('running','source-facts-missing') ORDER BY clock_occurrence_id FOR SHARE",&[&record.request_id,&task_id]).await?; + let rows=tx.query("SELECT clock_occurrence_id,policy,anchor_at,updated_at,paused_duration_micros FROM casework_review_clock_occurrences WHERE request_id=$1 AND task_id=$2 AND scope='activity' AND state IN('running','source-facts-missing') ORDER BY clock_occurrence_id FOR SHARE",&[&record.request_id,&task_id]).await?; let mut plans = Vec::new(); for row in rows { let definition: ReviewClockDefinition = serde_json::from_value(row.get(1))?; @@ -827,8 +829,9 @@ async fn calculate_review_clocks( } let holiday_row=tx.query_opt("SELECT document FROM casework_holiday_sets WHERE holiday_set=$1 ORDER BY revision DESC LIMIT 1",&[&calendar.holiday_set]).await?.ok_or(ReviewRuntimeError::Invalid)?; let holiday: HolidaySetDocument = serde_json::from_value(holiday_row.get(0))?; - let evaluated = evaluate_stage_clock(&definition.clock, calendar, &holiday, row.get(2)) + let mut evaluated = evaluate_stage_clock(&definition.clock, calendar, &holiday, row.get(2)) .map_err(|error| clock_evaluation_error(&definition.clock, error))?; + super::ask_clocks::shift_evaluation(&mut evaluated, row.get(4))?; let occurrence_id: Uuid = row.get(0); let applied=tx.query("SELECT effect_kind,effect_id FROM casework_review_clock_effects WHERE clock_occurrence_id=$1",&[&occurrence_id]).await?.into_iter().map(|r|(r.get::<_,String>(0),r.get::<_,String>(1))).collect(); let next_action_at = @@ -879,3 +882,35 @@ fn staffing_position(task: &ReviewTask) -> Value { "source": task.subject.source, "type": task.subject.subject_type, "id": task.subject.id, "version": task.subject.version, "digest": task.subject.digest.as_str()}) } + +/// Delegated institutional readers see no ask state, so a filter on it is +/// refused rather than ignored. +fn refuse_delegated_marker_filter( + delegated: bool, + query: &ReviewStaffingQuery, +) -> Result<(), ReviewRuntimeError> { + if delegated && query.marker.is_some() { + Err(ReviewRuntimeError::Invalid) + } else { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_delegated_read_refuses_a_marker_filter_and_an_ordinary_read_accepts_it() { + let with_marker = ReviewStaffingQuery { + marker: Some(registry_casework_core::ReviewTaskMarker::Waiting), + ..Default::default() + }; + assert!(matches!( + refuse_delegated_marker_filter(true, &with_marker), + Err(ReviewRuntimeError::Invalid) + )); + assert!(refuse_delegated_marker_filter(false, &with_marker).is_ok()); + assert!(refuse_delegated_marker_filter(true, &ReviewStaffingQuery::default()).is_ok()); + } +} diff --git a/crates/registry-casework/src/store.rs b/crates/registry-casework/src/store.rs index d4a1b187ff..3f6267d0cd 100644 --- a/crates/registry-casework/src/store.rs +++ b/crates/registry-casework/src/store.rs @@ -16,12 +16,13 @@ use uuid::Uuid; /// Every schema version, in the order it is applied. The baseline is /// version [`BASELINE_SCHEMA_VERSION`], above every version an earlier /// release applied; each later migration takes the next number. -pub(crate) const MIGRATIONS: [(i64, &str); 2] = [ +pub(crate) const MIGRATIONS: [(i64, &str); 3] = [ (200, include_str!("../migrations/0200_reviews.sql")), ( 201, include_str!("../migrations/0201_activation_posture.sql"), ), + (202, include_str!("../migrations/0202_review_asks.sql")), ]; /// The baseline schema version. A ledger holding any version below it was /// left by an earlier pre-1.0 release, which this release refuses by name: @@ -947,12 +948,12 @@ mod schema_version_tests { } } assert!(refuse_unsupported_schema(&[]).is_ok()); - assert!(refuse_unsupported_schema(&[200, 201]).is_ok()); + assert!(refuse_unsupported_schema(&[200, 201, 202]).is_ok()); assert!(matches!( - refuse_unsupported_schema(&[200, 201, 202]), + refuse_unsupported_schema(&[200, 201, 202, 203]), Err(StoreError::SchemaNewer { - found: 202, - supported: 201 + found: 203, + supported: 202 }) )); } diff --git a/crates/registry-casework/src/task_grants/http_tests.rs b/crates/registry-casework/src/task_grants/http_tests.rs index 070574187b..b9b335c93d 100644 --- a/crates/registry-casework/src/task_grants/http_tests.rs +++ b/crates/registry-casework/src/task_grants/http_tests.rs @@ -51,6 +51,7 @@ impl ReviewContextProvider for Source { _ => {} } Ok(HumanDisplayObservation { + answers: Default::default(), identity: request.identity.clone(), reviewable: true, display_reference: None, diff --git a/crates/registry-casework/src/task_grants/native_exchange_tests.rs b/crates/registry-casework/src/task_grants/native_exchange_tests.rs index 9e8b1f95b8..2ea8fd39f8 100644 --- a/crates/registry-casework/src/task_grants/native_exchange_tests.rs +++ b/crates/registry-casework/src/task_grants/native_exchange_tests.rs @@ -64,6 +64,7 @@ impl ReviewContextProvider for Source { request: HumanDisplayRequest<'_>, ) -> Result { Ok(HumanDisplayObservation { + answers: Default::default(), identity: request.identity.clone(), reviewable: true, display_reference: Some("Synthetic request".into()), diff --git a/crates/registry-casework/tests/migration_pins.rs b/crates/registry-casework/tests/migration_pins.rs index b90a3ccb21..9eabb7486e 100644 --- a/crates/registry-casework/tests/migration_pins.rs +++ b/crates/registry-casework/tests/migration_pins.rs @@ -17,6 +17,10 @@ const PINS: &[(&str, &str)] = &[ "0201_activation_posture.sql", "3eacf388a3ebcc488315291f17c466bcc877932fd2a3c83c2333b36d2d02f85f", ), + ( + "0202_review_asks.sql", + "d3c887839f592452ae407865b2b62719b63e58b357f7f9ab9a9603d242654bd4", + ), ]; #[test] diff --git a/crates/registry-casework/tests/problem_code_catalogue.rs b/crates/registry-casework/tests/problem_code_catalogue.rs index 9894087454..61a12402b3 100644 --- a/crates/registry-casework/tests/problem_code_catalogue.rs +++ b/crates/registry-casework/tests/problem_code_catalogue.rs @@ -113,6 +113,30 @@ fn registered_statuses() -> BTreeMap<&'static str, u16> { .collect() } +#[test] +fn the_ask_limit_refusal_is_registered_in_the_ask_operation_only() { + let code = ProblemCode::ALL + .iter() + .find(|code| code.code() == "review.ask-limit-reached"); + assert!( + code.is_some(), + "the runtime catalogue must name the ask limit" + ); + assert_eq!(code.unwrap().status().as_u16(), 409); + let schema: serde_json::Value = serde_json::from_str(include_str!( + "../../../products/casework/generated/registry-casework.openapi.json" + )) + .unwrap(); + assert!( + schema["paths"]["/v1/review-tasks/{task_id}/asks"]["post"]["responses"]["409"] + .to_string() + .contains("ProblemReviewAskLimitReached") + ); + let answer = &schema["paths"]["/v1/review-requests/{request_id}/asks/{ask_id}/answer"]["post"]; + assert!(answer.is_object()); + assert!(!answer.to_string().contains("ProblemReviewAskLimitReached")); +} + /// The members of one TypeScript string-literal union, in declaration order. fn typescript_union(source: &str, name: &str) -> Vec { let declaration = format!("export type {name} ="); diff --git a/crates/registry-casework/tests/review_acceptance_postgres.rs b/crates/registry-casework/tests/review_acceptance_postgres.rs index 9f94729074..a549666493 100644 --- a/crates/registry-casework/tests/review_acceptance_postgres.rs +++ b/crates/registry-casework/tests/review_acceptance_postgres.rs @@ -120,6 +120,7 @@ impl ReviewContextProvider for SubstituteProvider { identity.subject.version = "successor".into(); } Ok(HumanDisplayObservation { + answers: Default::default(), identity, reviewable: true, display_reference: Some( diff --git a/crates/registry-casework/tests/review_http.rs b/crates/registry-casework/tests/review_http.rs index 777208804d..25f1d0395a 100644 --- a/crates/registry-casework/tests/review_http.rs +++ b/crates/registry-casework/tests/review_http.rs @@ -1,5 +1,8 @@ #![cfg(feature = "postgres-test")] +#[path = "support/ask_limit_http.rs"] +mod ask_limit_http; + use std::{ collections::BTreeMap, env, @@ -41,6 +44,7 @@ use uuid::Uuid; #[derive(Default)] struct DelegatedSourceBarrier { + answers: Mutex>, entered: tokio::sync::Notify, release: tokio::sync::Notify, } @@ -122,6 +126,11 @@ impl ReviewContextProvider for ReviewSource { identity.subject.version = "2".into(); } Ok(HumanDisplayObservation { + answers: self + .delegated_barrier + .as_ref() + .map(|barrier| barrier.answers.lock().unwrap().clone()) + .unwrap_or_default(), identity, reviewable: matches!( *self.source_state.lock().unwrap(), @@ -142,6 +151,7 @@ impl ReviewContextProvider for ReviewSource { barrier.entered.notify_one(); barrier.release.notified().await; self.human_display(HumanDisplayRequest { + include_answers: true, identity: request.identity, source_profile_id: request.source_profile_id, credential: request.credential, @@ -168,6 +178,7 @@ impl ReviewContextProvider for ReviewSource { for identity in identities { observations.push( self.human_display(HumanDisplayRequest { + include_answers: true, identity, source_profile_id, credential: EphemeralCredential::new(credential), @@ -241,6 +252,7 @@ fn project(issuer: &str) -> CaseworkProject { teams: vec![serde_json::from_value(json!({"id":"review-team","label":"Review team","serves":["review"],"memberProfiles":["staff"],"supervisorProfiles":["supervisor"]})).unwrap()], review_policies: vec![ ReviewPolicy { + resubmission: ReviewResubmissionPolicy::default(), id: "registry-correction".to_owned(), label: None, version: "1".to_owned(), @@ -258,6 +270,7 @@ fn project(issuer: &str) -> CaseworkProject { required_approvals: 1, outcomes: None, negative_decisions: ReviewNegativeDecisionMode::Settle, + asks: None, exclude_initiator: true, exclude_previous_stage_reviewers: true, }], @@ -283,6 +296,7 @@ fn project(issuer: &str) -> CaseworkProject { }], }, ReviewPolicy { + resubmission: ReviewResubmissionPolicy::default(), id: "registry-answer".to_owned(), label: None, version: "1".to_owned(), @@ -298,6 +312,7 @@ fn project(issuer: &str) -> CaseworkProject { required_approvals: 1, outcomes: None, negative_decisions: ReviewNegativeDecisionMode::Settle, + asks: None, exclude_initiator: true, exclude_previous_stage_reviewers: true, }], @@ -335,6 +350,7 @@ fn project(issuer: &str) -> CaseworkProject { subject: "registry-service".to_owned(), trusted_initiator_issuer: Some(issuer.to_owned()), initiator_profile: Some("initiator".to_owned()), + reads_asks: false, source_namespaces: vec!["registry".to_owned()], review_policies: vec![ "registry-correction".to_owned(), @@ -352,6 +368,7 @@ fn project(issuer: &str) -> CaseworkProject { subject: "registry-service".to_owned(), trusted_initiator_issuer: Some(issuer.to_owned()), initiator_profile: None, + reads_asks: false, source_namespaces: vec!["registry".to_owned()], review_policies: vec![ "registry-correction".to_owned(), @@ -5756,6 +5773,7 @@ impl ReviewContextProvider for SeparateHumanSource { return Err(ReviewContextError::Concealed); } Ok(HumanDisplayObservation { + answers: Default::default(), identity: request.identity.clone(), reviewable: true, display_reference: None, @@ -6752,3 +6770,444 @@ async fn well_formed_source_pair_is_ignored_on_every_admitted_submitted_context_ } idp.stop().await; } + +fn asks_http_project(idp: &MockIdp) -> CaseworkProject { + let mut asking = project(&idp.issuer()); + asking.review_policies[0].context = ReviewContextPolicy::Submitted; + asking.review_policies[0].stages[0].asks = Some(ReviewStageAsksPolicy::default()); + asking.trusted_producers[0].reads_asks = true; + asking.trusted_producers[1].reads_asks = true; + asking.check().expect("asking project"); + asking +} + +async fn http_json( + app: &axum::Router, + method: &str, + uri: String, + headers: &[(&str, String)], + body: Option, +) -> (StatusCode, axum::http::HeaderMap, Vec) { + let mut request = Request::builder().method(method).uri(uri); + for (name, value) in headers { + request = request.header(*name, value); + } + let request = match body { + Some(body) => request + .header(CONTENT_TYPE, "application/json") + .body(Body::from(serde_json::to_vec(&body).unwrap())), + None => request.body(Body::empty()), + } + .expect("request"); + let response = app.clone().oneshot(request).await.expect("response"); + let status = response.status(); + let response_headers = response.headers().clone(); + let bytes = to_bytes(response.into_body(), 64 * 1024) + .await + .expect("bounded body") + .to_vec(); + (status, response_headers, bytes) +} + +#[tokio::test] +async fn c2_due_pause_expiry_and_delivery_lag_follow_the_http_contract() { + let idp = MockIdp::start().await; + let mut project = asks_http_project(&idp); + project.review_policies[0].stages[0].asks = Some(ReviewStageAsksPolicy { + answer_within: Some(ElapsedDuration::Hours(1)), + pause_clocks: true, + ..Default::default() + }); + project.clocks.push(ClockPolicy::Subject { + id: "subject-budget".into(), + anchor: SubjectClockAnchor { + kind: SubjectClockAnchorType::RequestAccepted, + }, + after: ElapsedDuration::Days(5), + }); + project.review_policies[0] + .clocks + .push("subject-budget".into()); + let (app, service, _, _, _, _, database) = app_with_project(&idp, project).await; + let mut input = review_request_for_subject("ask-due-http", "ask-due-http-ref", &idp.issuer()); + input.context = ReviewContext::Submitted { + snapshot: json!({"summary": "Timed ask"}), + }; + let (created, task) = create_task(&app, &database, &idp, &input).await; + let reviewer = reviewer_token(&idp); + claim_task_over_http(&app, task, &reviewer, "claim").await; + let staff = vec![ + ("authorization", format!("Bearer {reviewer}")), + (CASEWORK_PROFILE_HEADER, "staff".into()), + ]; + let mut mutation = staff.clone(); + mutation.extend([ + ("if-match", "\"2\"".into()), + ("idempotency-key", "ask".into()), + ]); + let (status, _, body) = http_json( + &app, + "POST", + format!("/v1/review-tasks/{task}/asks"), + &mutation, + Some(json!({"text":"Why?","wants":[{"kind":"answer"}]})), + ) + .await; + assert_eq!(status, StatusCode::OK); + let asked: ReviewTaskAsked = serde_json::from_slice(&body).unwrap(); + assert_eq!( + asked.ask.due_at, + Some(asked.ask.asked_at + chrono::TimeDelta::hours(1)) + ); + let clock_uri = format!("/v1/review-requests/{}/clocks", created.request_id); + let (status, _, body) = http_json(&app, "GET", clock_uri.clone(), &staff, None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + serde_json::from_slice::(&body).unwrap()[0]["state"], + "paused" + ); + let due = chrono::Utc::now() - chrono::TimeDelta::minutes(1); + let due = chrono::DateTime::parse_from_rfc3339( + &due.to_rfc3339_opts(chrono::SecondsFormat::Micros, true), + ) + .unwrap() + .with_timezone(&chrono::Utc); + database + .execute( + "UPDATE casework_review_asks SET asked_at=$2,due_at=$3 WHERE ask_id=$1", + &[ + &asked.ask.ask_id, + &(due - chrono::TimeDelta::hours(1)), + &due, + ], + ) + .await + .unwrap(); + assert_eq!(service.process_due_review_clocks(100).await.unwrap(), 1); + let (status, _, body) = http_json( + &app, + "GET", + "/v1/review-tasks?marker=expired".into(), + &staff, + None, + ) + .await; + assert_eq!(status, StatusCode::OK); + let page: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(page["items"].as_array().unwrap().len(), 1); + assert_eq!(page["items"][0]["marker"], "expired"); + let producer = vec![ + ("authorization", format!("Bearer {}", token(&idp))), + (REVIEW_PROFILE_HEADER, "producer".into()), + ("idempotency-key", "answer-late".into()), + ]; + let answer_uri = format!( + "/v1/review-requests/{}/asks/{}/answer", + created.request_id, asked.ask.ask_id + ); + let (status, _, body) = http_json( + &app, + "POST", + answer_uri.clone(), + &producer, + Some(json!({"subject":input.subject,"answeredAt":due+chrono::TimeDelta::microseconds(1)})), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!( + serde_json::from_slice::(&body).unwrap()["code"], + "review.ask-not-open" + ); + let mut producer = producer; + producer[2].1 = "answer-on-time".into(); + let (status, _, body) = http_json( + &app, + "POST", + answer_uri, + &producer, + Some(json!({"subject":input.subject,"answeredAt":due})), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + serde_json::from_slice::(&body).unwrap()["state"], + "answered" + ); + let (_, _, body) = http_json(&app, "GET", clock_uri, &staff, None).await; + assert_eq!( + serde_json::from_slice::(&body).unwrap()[0]["state"], + "running" + ); + idp.stop().await; +} + +#[tokio::test] +async fn the_ask_command_and_the_producer_ask_routes_follow_the_contract_over_http() { + let idp = MockIdp::start().await; + let (app, _, _, _, _, _, database) = app_with_project(&idp, asks_http_project(&idp)).await; + let mut created_request = review_request_for_subject("ask-http", "ask-http-ref", &idp.issuer()); + created_request.context = ReviewContext::Submitted { + snapshot: json!({"summary": "Ask over HTTP"}), + }; + let (created, task) = create_task(&app, &database, &idp, &created_request).await; + let request_id = created.request_id; + let reviewer = reviewer_token(&idp); + claim_task_over_http(&app, task, &reviewer, "claim-ask-http").await; + let staff_headers = |key: &str, revision: &str| { + vec![ + ("authorization", format!("Bearer {reviewer}")), + (CASEWORK_PROFILE_HEADER, "staff".to_owned()), + ("if-match", format!("\"{revision}\"")), + ("idempotency-key", key.to_owned()), + ] + }; + let ask_body = json!({"text": "Send the signed form.", "wants": [{"kind": "answer"}]}); + let uri = format!("/v1/review-tasks/{task}/asks"); + + // A stale revision is refused before anything changes. + let (status, _, _) = http_json( + &app, + "POST", + uri.clone(), + &staff_headers("ask-stale", "1"), + Some(ask_body.clone()), + ) + .await; + assert_eq!(status, StatusCode::PRECONDITION_FAILED); + + let (status, _, body) = http_json( + &app, + "POST", + uri.clone(), + &staff_headers("ask-1", "2"), + Some(ask_body.clone()), + ) + .await; + assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body)); + let asked: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(asked["task"]["marker"], "waiting"); + assert_eq!(asked["task"]["revision"], 3); + assert_eq!(asked["ask"]["state"], "open"); + let ask_id = asked["ask"]["askId"].as_str().unwrap().to_owned(); + + // A second open ask is its own problem. + let (status, _, body) = http_json( + &app, + "POST", + uri.clone(), + &staff_headers("ask-2", "3"), + Some(ask_body.clone()), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!( + serde_json::from_slice::(&body).unwrap()["code"], + "review.ask-already-open" + ); + + let producer = vec![ + ("authorization", format!("Bearer {}", token(&idp))), + (REVIEW_PROFILE_HEADER, "producer".to_owned()), + ]; + let other = vec![ + ( + "authorization", + format!("Bearer {}", alternate_producer_token(&idp)), + ), + (REVIEW_PROFILE_HEADER, "producer-alternate".to_owned()), + ]; + let (status, _, body) = http_json( + &app, + "GET", + "/v1/review-asks?limit=10".to_owned(), + &producer, + None, + ) + .await; + assert_eq!(status, StatusCode::OK); + let feed: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(feed["items"].as_array().unwrap().len(), 1); + assert_eq!(feed["items"][0]["askId"], ask_id.as_str()); + let (_, _, body) = http_json(&app, "GET", "/v1/review-asks".to_owned(), &other, None).await; + assert!(serde_json::from_slice::(&body).unwrap()["items"] + .as_array() + .unwrap() + .is_empty()); + + let ask_uri = format!("/v1/review-requests/{request_id}/asks/{ask_id}"); + let (status, _, body) = http_json(&app, "GET", ask_uri.clone(), &producer, None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + serde_json::from_slice::(&body).unwrap()["text"], + "Send the signed form." + ); + // Another producer's read is a bare empty 404 with no content type. + let (status, headers, body) = http_json(&app, "GET", ask_uri.clone(), &other, None).await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert!(body.is_empty()); + assert!(headers.get(CONTENT_TYPE).is_none()); + + let subject = serde_json::to_value(&created_request.subject).unwrap(); + let answered_at = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Micros, true); + let answer_uri = format!("{ask_uri}/answer"); + let answer_headers = |key: &str, mut base: Vec<(&'static str, String)>| { + base.push(("idempotency-key", key.to_owned())); + base + }; + let answer = json!({"subject": subject, "answeredAt": answered_at}); + + // The answer carries no text: an extra member is refused. + let mut with_text = answer.clone(); + with_text["text"] = json!("my answer"); + let (status, _, _) = http_json( + &app, + "POST", + answer_uri.clone(), + &answer_headers("answer-text", producer.clone()), + Some(with_text), + ) + .await; + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY); + // Another producer: concealed. + let (status, headers, body) = http_json( + &app, + "POST", + answer_uri.clone(), + &answer_headers("answer-other", other.clone()), + Some(answer.clone()), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert!(body.is_empty() && headers.get(CONTENT_TYPE).is_none()); + + let (status, _, body) = http_json( + &app, + "POST", + answer_uri.clone(), + &answer_headers("answer-1", producer.clone()), + Some(answer.clone()), + ) + .await; + assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body)); + let answered: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(answered["state"], "answered"); + // Compare instants: the wire form may spell the same time differently. + assert_eq!( + chrono::DateTime::parse_from_rfc3339(answered["answeredAt"].as_str().unwrap()).unwrap(), + chrono::DateTime::parse_from_rfc3339(&answered_at).unwrap(), + ); + // A second answer under another key is the not-open problem. + let (status, _, body) = http_json( + &app, + "POST", + answer_uri, + &answer_headers("answer-2", producer), + Some(answer), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!( + serde_json::from_slice::(&body).unwrap()["code"], + "review.ask-not-open" + ); + + // The reviewer's task read carries the answered marker. + let task_json = read_task_json(&app, task, &reviewer).await; + assert_eq!(task_json["marker"], "answered"); + idp.stop().await; +} + +#[tokio::test] +async fn delegated_institutional_reads_carry_neither_asks_nor_markers() { + let idp = MockIdp::start().await; + let barrier = Arc::new(DelegatedSourceBarrier::default()); + let mut project = asks_http_project(&idp); + project.review_policies[0].context = ReviewContextPolicy::CurrentSource { + provider: "registry".into(), + contract: context_contract(), + }; + let (app, _, _, _, _, _, database) = + app_with_project_options(&idp, project, Some(barrier.clone()), true, None).await; + let (client, server) = native_review_client(app.clone()).await; + let created_request = + review_request_for_subject("ask-delegated", "ask-delegated-ref", &idp.issuer()); + let (_, task_id) = create_task(&app, &database, &idp, &created_request).await; + let reviewer = human_token(&idp, "reviewer", "staff"); + client + .claim_review_task( + CaseworkAuth::new(&reviewer, "staff").with_source_profile("reviewer-source"), + task_id, + 1, + "claim", + ) + .await + .expect("claim"); + let asked = client + .ask_applicant( + CaseworkAuth::new(&reviewer, "staff").with_source_profile("reviewer-source"), + task_id, + 2, + "ask", + ®istry_casework_client::ReviewTaskAskRequest { + text: "Send the signed form.".to_owned(), + wants: vec![registry_casework_client::ReviewAskWant::Answer {}], + }, + ) + .await + .expect("ask") + .value; + assert_eq!( + asked.task.marker, + Some(registry_casework_client::ReviewTaskMarker::Waiting) + ); + barrier.answers.lock().unwrap().insert( + asked.ask.ask_id, + ReviewContextAnswer { + text: Some("source answer excluded from institutional delegation".into()), + documents: vec![], + answered_at: asked.ask.asked_at, + }, + ); + // The reviewer sees the ask, its live answer and the marker. + let own = client + .review_task_context( + CaseworkAuth::new(&reviewer, "staff").with_source_profile("reviewer-source"), + task_id, + ) + .await + .expect("reviewer context") + .value; + assert_eq!(own.asks.len(), 1); + assert!(own.asks[0].answer.is_some()); + barrier.release.notify_one(); + + let delegated = delegated_staff_read_token(&idp, "reviewer"); + let context = client + .delegated_review_task_context( + DelegatedStaffReadAuth::new(&delegated, "assistant-reader") + .with_source_profile("reviewer-source"), + task_id, + ) + .await + .expect("delegated context") + .value; + assert!(context.asks.is_empty()); + assert!(!serde_json::to_string(&context) + .unwrap() + .contains("source answer excluded")); + barrier.release.notify_one(); + let list = client + .delegated_review_tasks( + DelegatedStaffReadAuth::new(&delegated, "assistant-reader") + .with_source_profile("reviewer-source"), + None, + 25, + ) + .await + .expect("delegated list") + .value; + assert_eq!(list.items.len(), 1); + assert_eq!(list.items[0].marker, None); + server.abort(); + idp.stop().await; +} diff --git a/crates/registry-casework/tests/review_payment_fixture_postgres.rs b/crates/registry-casework/tests/review_payment_fixture_postgres.rs index dad6a9dff1..5c4e6cee22 100644 --- a/crates/registry-casework/tests/review_payment_fixture_postgres.rs +++ b/crates/registry-casework/tests/review_payment_fixture_postgres.rs @@ -23,9 +23,9 @@ use registry_casework_core::{ InboxPolicy, IssuerPrincipal, ProjectIdentity, QueuePolicy, ReviewCompletion, ReviewCompletionDestinationPolicy, ReviewCompletionType, ReviewContext, ReviewContextPolicy, ReviewCreateRequest, ReviewNegativeDecisionMode, ReviewPolicy, ReviewProducerPolicy, - ReviewPurpose, ReviewRequestAccepted, ReviewResult, ReviewResultFeedPage, ReviewResultStatus, - ReviewRetentionPolicy, ReviewStagePolicy, ReviewTaskPage, SubjectBinding, - CASEWORK_PROFILE_HEADER, REVIEW_PROFILE_HEADER, + ReviewPurpose, ReviewRequestAccepted, ReviewResubmissionPolicy, ReviewResult, + ReviewResultFeedPage, ReviewResultStatus, ReviewRetentionPolicy, ReviewStagePolicy, + ReviewTaskPage, SubjectBinding, CASEWORK_PROFILE_HEADER, REVIEW_PROFILE_HEADER, }; use registry_platform_config::{SecretProvider, SecretResolver}; use registry_platform_crypto::delivery_signature::{ @@ -389,6 +389,7 @@ fn project(issuer: &str) -> CaseworkProject { teams: Vec::new(), context_providers: Vec::new(), review_policies: vec![ReviewPolicy { + resubmission: ReviewResubmissionPolicy::default(), id: "payment-batch".to_owned(), label: None, version: "1".to_owned(), @@ -404,6 +405,7 @@ fn project(issuer: &str) -> CaseworkProject { required_approvals: 1, outcomes: None, negative_decisions: ReviewNegativeDecisionMode::Settle, + asks: None, exclude_initiator: false, exclude_previous_stage_reviewers: false, }], @@ -436,6 +438,7 @@ fn project(issuer: &str) -> CaseworkProject { subject: "payment-service".to_owned(), trusted_initiator_issuer: None, initiator_profile: None, + reads_asks: false, source_namespaces: vec!["payments".to_owned()], review_policies: vec!["payment-batch".to_owned()], retention: registry_casework_core::ProducerRetention { diff --git a/crates/registry-casework/tests/review_postgres.rs b/crates/registry-casework/tests/review_postgres.rs index bf79c50c75..dc1f695b1c 100644 --- a/crates/registry-casework/tests/review_postgres.rs +++ b/crates/registry-casework/tests/review_postgres.rs @@ -28,6 +28,10 @@ use tokio_postgres::NoTls; use tracing::instrument::WithSubscriber; use tracing_subscriber::fmt::MakeWriter; use uuid::Uuid; +#[path = "support/ask_limit.rs"] +mod ask_limit; +#[path = "support/source_ask_answers.rs"] +mod source_ask_answers; struct Fixture { service_v1: CaseworkService, @@ -85,6 +89,7 @@ impl ReviewContextProvider for ReviewSource { return Err(ReviewContextError::BindingMoved); } Ok(HumanDisplayObservation { + answers: Default::default(), identity: request.identity.clone(), reviewable: *self.state.lock().unwrap(), display_reference: None, @@ -286,6 +291,7 @@ fn project(version: &str) -> CaseworkProject { supervisor_profiles: vec!["supervisor".into()], }], review_policies: vec![ReviewPolicy { + resubmission: ReviewResubmissionPolicy::default(), id: "registry-correction".to_owned(), label: None, version: version.to_owned(), @@ -302,6 +308,7 @@ fn project(version: &str) -> CaseworkProject { required_approvals: 1, outcomes: None, negative_decisions: ReviewNegativeDecisionMode::Settle, + asks: None, exclude_initiator: true, exclude_previous_stage_reviewers: false, }, @@ -314,6 +321,7 @@ fn project(version: &str) -> CaseworkProject { required_approvals: 1, outcomes: None, negative_decisions: ReviewNegativeDecisionMode::Settle, + asks: None, exclude_initiator: true, exclude_previous_stage_reviewers: true, }, @@ -369,6 +377,7 @@ fn project(version: &str) -> CaseworkProject { subject: "registry-service".to_owned(), trusted_initiator_issuer: Some("https://issuer.test".to_owned()), initiator_profile: None, + reads_asks: false, source_namespaces: vec!["registry".to_owned()], review_policies: vec!["registry-correction".to_owned()], retention: registry_casework_core::ProducerRetention { @@ -1822,6 +1831,37 @@ async fn a_completion_past_a_lowered_attempt_limit_is_set_aside_as_exhausted() { ); } +#[tokio::test] +async fn a_completion_is_immediately_claimable_when_the_application_clock_is_ahead() { + let fixture = fixture().await; + let created = fixture + .service_v1 + .create_review_request( + &fixture.producer, + request("completion-clock-skew", "completion-clock-skew"), + "create-completion-clock-skew", + ) + .await + .unwrap(); + let database_now: chrono::DateTime = fixture + .database + .query_one("SELECT transaction_timestamp()", &[]) + .await + .unwrap() + .get(0); + let application_now = database_now + TimeDelta::hours(1); + let result = fixture + .store + .settle_review_at_for_test(created.accepted.request_id, application_now) + .await + .unwrap(); + assert_eq!(result.completed_at, application_now); + let lease = claim_review_completion_for_test(fixture.store.clone(), "registry-completion", 3) + .await.unwrap() + .expect("immediate dispatch uses the database clock despite an application clock one hour ahead"); + assert_eq!(lease.event().request_id, created.accepted.request_id); +} + #[tokio::test] async fn recovery_pins_policy_and_terminal_settlement_emits_atomically() { let fixture = fixture().await; @@ -12311,3 +12351,3309 @@ async fn staffing_diagnostic_is_disclosed_and_clears_when_responsibility_resumes None ); } + +fn asks_project(stage_asks: bool, producer_reads_asks: bool) -> CaseworkProject { + let mut project = project("asks-1"); + if stage_asks { + project.review_policies[0].stages[0].asks = Some(ReviewStageAsksPolicy::default()); + } + project.trusted_producers[0].reads_asks = producer_reads_asks; + project.trusted_producers[0].completion = None; + project + .access_profiles + .push(profile("other-producer", CaseworkActsAs::Requester)); + let mut other = project.trusted_producers[0].clone(); + other.id = "other".to_owned(); + other.profile = "other-producer".to_owned(); + other.subject = "other-service".to_owned(); + other.completion = None; + other.reads_asks = true; + project.trusted_producers.push(other); + project +} + +fn asks_service(fixture: &Fixture, stage_asks: bool, producer_reads_asks: bool) -> CaseworkService { + CaseworkService::new( + fixture.store.clone(), + asks_project(stage_asks, producer_reads_asks), + Vec::>::new(), + ) + .expect("asks service") +} + +fn timed_asks_service(fixture: &Fixture, pause_clocks: bool) -> CaseworkService { + let mut project = asks_project(true, true); + project.review_policies[0].stages[0].asks = Some(ReviewStageAsksPolicy { + answer_within: Some(ElapsedDuration::Hours(1)), + pause_clocks, + ..Default::default() + }); + CaseworkService::new(fixture.store.clone(), project, Vec::new()).unwrap() +} + +#[tokio::test] +async fn c2_ask_due_date_is_absolute_and_delivery_lag_does_not_make_an_answer_late() { + let fixture = fixture().await; + let service = timed_asks_service(&fixture, false); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "ask-due").await; + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .unwrap(); + assert_eq!( + asked.ask.due_at, + Some(asked.ask.asked_at + TimeDelta::hours(1)) + ); + let context = service + .review_task_context(&fixture.reviewer_a, task, None, "") + .await + .unwrap(); + assert_eq!( + serde_json::to_value(&context.asks[0]).unwrap()["dueAt"], + json!(asked.ask.due_at.unwrap()) + ); + assert_eq!( + service + .review_ask(&fixture.producer, request_id, asked.ask.ask_id) + .await + .unwrap(), + asked.ask + ); + let due = now_micros() - TimeDelta::hours(1); + fixture + .database + .execute( + "UPDATE casework_review_asks SET asked_at=$2,due_at=$3 WHERE ask_id=$1", + &[&asked.ask.ask_id, &(due - TimeDelta::hours(1)), &due], + ) + .await + .unwrap(); + assert_eq!(service.process_due_review_clocks(100).await.unwrap(), 1); + let expired = service + .review_ask(&fixture.producer, request_id, asked.ask.ask_id) + .await + .unwrap(); + assert_eq!(expired.state, ReviewAskState::Expired); + assert!(expired.closed_at.unwrap() >= due); + let held = service + .review_task(&fixture.reviewer_a, task, None, "") + .await + .unwrap(); + assert!( + matches!(held.state, ReviewTaskState::Held { ref holder } if holder == &fixture.reviewer_a.principal) + ); + assert_eq!(held.marker, Some(ReviewTaskMarker::Expired)); + let revision = held.revision; + assert!(matches!( + service + .answer_review_ask( + &fixture.producer, + request_id, + asked.ask.ask_id, + ReviewAskAnswer { + subject: create.subject.clone(), + answered_at: due + TimeDelta::microseconds(1) + }, + "late" + ) + .await, + Err(ReviewRuntimeError::ReviewAskNotOpen) + )); + assert_eq!( + service + .review_task(&fixture.reviewer_a, task, None, "") + .await + .unwrap() + .revision, + revision + ); + assert_eq!( + ask_changes(&fixture, request_id).await, + ["opened", "expired"] + ); + let answered = service + .answer_review_ask( + &fixture.producer, + request_id, + asked.ask.ask_id, + ReviewAskAnswer { + subject: create.subject, + answered_at: due, + }, + "on-time", + ) + .await + .unwrap(); + assert_eq!(answered.state, ReviewAskState::Answered); + assert_eq!(answered.closed_at, None); + assert_eq!( + ask_marker(&fixture, task).await.as_deref(), + Some("answered") + ); + assert_eq!( + ask_changes(&fixture, request_id).await, + ["opened", "expired", "answered"] + ); + let detail: serde_json::Value = fixture.database.query_one("SELECT detail FROM casework_review_history WHERE request_id=$1 AND kind='ask-answered'", &[&request_id]).await.unwrap().get(0); + assert_eq!(detail["arrivedAfterDue"], true); + assert_eq!(service.process_due_review_clocks(100).await.unwrap(), 0); +} + +#[tokio::test] +async fn c2_a_late_answer_is_refused_before_the_expiry_runner_runs() { + let fixture = fixture().await; + let service = timed_asks_service(&fixture, false); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "ask-late-open").await; + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .unwrap(); + let due = now_micros() - TimeDelta::minutes(1); + fixture + .database + .execute( + "UPDATE casework_review_asks SET asked_at=$2,due_at=$3 WHERE ask_id=$1", + &[&asked.ask.ask_id, &(due - TimeDelta::hours(1)), &due], + ) + .await + .unwrap(); + assert!(matches!( + service + .answer_review_ask( + &fixture.producer, + request_id, + asked.ask.ask_id, + ReviewAskAnswer { + subject: create.subject, + answered_at: due + TimeDelta::microseconds(1) + }, + "late" + ) + .await, + Err(ReviewRuntimeError::ReviewAskNotOpen) + )); + assert_eq!(ask_states(&fixture, request_id).await, ["open"]); + assert_eq!(ask_marker(&fixture, task).await.as_deref(), Some("waiting")); + assert_eq!(ask_changes(&fixture, request_id).await, ["opened"]); +} + +#[tokio::test] +async fn c2_ask_pause_shifts_the_clock_and_resumes_on_answer() { + let fixture = fixture().await; + let service = timed_asks_service(&fixture, true); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "ask-pause").await; + let before = service + .review_clocks(&fixture.producer, request_id, None, "") + .await + .unwrap(); + assert_eq!(before.len(), 1); + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .unwrap(); + let paused = service + .review_clocks(&fixture.producer, request_id, None, "") + .await + .unwrap(); + assert_eq!(paused[0].state, ReviewClockState::Paused); + assert_eq!( + service + .review_task(&fixture.reviewer_a, task, None, "") + .await + .unwrap() + .deadline_at, + None + ); + assert_eq!(service.process_due_review_clocks(100).await.unwrap(), 0); + fixture.database.execute("UPDATE casework_review_clock_occurrences SET paused_at=paused_at-interval '2 hours' WHERE request_id=$1", &[&request_id]).await.unwrap(); + service + .answer_review_ask( + &fixture.producer, + request_id, + asked.ask.ask_id, + ReviewAskAnswer { + subject: create.subject, + answered_at: asked.ask.asked_at, + }, + "answer", + ) + .await + .unwrap(); + let resumed = service + .review_clocks(&fixture.producer, request_id, None, "") + .await + .unwrap(); + assert_eq!(resumed[0].state, ReviewClockState::Running); + assert!(resumed[0].due_at.unwrap() >= before[0].due_at.unwrap() + TimeDelta::hours(2)); + let history = fixture.database.query("SELECT kind,detail FROM casework_review_history WHERE request_id=$1 AND kind IN ('clock-paused','clock-resumed') ORDER BY occurred_at", &[&request_id]).await.unwrap(); + assert_eq!(history.len(), 2); + assert_eq!(history[0].get::<_, String>(0), "clock-paused"); + assert_eq!(history[1].get::<_, String>(0), "clock-resumed"); + assert!( + history[1].get::<_, serde_json::Value>(1)["pausedSeconds"] + .as_f64() + .unwrap() + >= 7200.0 + ); +} + +#[tokio::test] +async fn c2_expiry_and_an_on_time_answer_can_race_without_losing_the_answer() { + let fixture = fixture().await; + let service = timed_asks_service(&fixture, true); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "ask-race").await; + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .unwrap(); + let due = now_micros() - TimeDelta::minutes(1); + fixture + .database + .execute( + "UPDATE casework_review_asks SET asked_at=$2,due_at=$3 WHERE ask_id=$1", + &[&asked.ask.ask_id, &(due - TimeDelta::hours(1)), &due], + ) + .await + .unwrap(); + let (expiry, answer) = tokio::join!( + service.process_due_review_clocks(100), + service.answer_review_ask( + &fixture.producer, + request_id, + asked.ask.ask_id, + ReviewAskAnswer { + subject: create.subject, + answered_at: due + }, + "answer" + ) + ); + assert!(expiry.unwrap() <= 1); + assert_eq!(answer.unwrap().state, ReviewAskState::Answered); + assert_eq!(ask_states(&fixture, request_id).await, ["answered"]); + assert_eq!( + ask_marker(&fixture, task).await.as_deref(), + Some("answered") + ); + assert_eq!( + service + .review_clocks(&fixture.producer, request_id, None, "") + .await + .unwrap()[0] + .state, + ReviewClockState::Running + ); + assert_eq!(service.process_due_review_clocks(100).await.unwrap(), 0); + let events = ask_changes(&fixture, request_id).await; + assert!(events == ["opened", "answered"] || events == ["opened", "expired", "answered"]); +} + +#[tokio::test] +async fn c2_pause_covers_activity_effects_and_resume_uses_wall_time_for_both_clock_kinds() { + let fixture = fixture().await; + let mut project = activity_clock_project(); + let ClockPolicy::Stage { at_risk, .. } = &mut project.clocks[0] else { + panic!("activity clock fixture"); + }; + *at_risk = Some(WorkingDaysBefore { + before: WorkingDays { working_days: 1 }, + }); + project.review_policies[0].stages[0].asks = Some(ReviewStageAsksPolicy { + pause_clocks: true, + answer_within: Some(ElapsedDuration::Hours(1)), + ..Default::default() + }); + project.trusted_producers[0].reads_asks = true; + project.trusted_producers[0].completion = None; + project.clocks.push(ClockPolicy::Subject { + id: "subject-budget".into(), + anchor: SubjectClockAnchor { + kind: SubjectClockAnchorType::RequestAccepted, + }, + after: ElapsedDuration::Days(5), + }); + project.review_policies[0] + .clocks + .push("subject-budget".into()); + let service = CaseworkService::new(fixture.store.clone(), project, Vec::new()).unwrap(); + service + .create_holiday_revision( + &actor("admin", CaseworkActsAs::Administrator, "administrator"), + &HolidaySetDocument { + holiday_set: "office-holidays".into(), + revision: 1, + dates: Vec::new(), + }, + "holidays", + ) + .await + .unwrap(); + let (request_id, task, create) = + claimed_for_asks(&fixture, &service, "ask-activity-pause").await; + let before = fixture.database.query_one("SELECT due_at,next_action_at,reminders,steps,at_risk_at FROM casework_review_clock_occurrences WHERE task_id=$1", &[&task]).await.unwrap(); + let before_due: chrono::DateTime = before.get(0); + let before_next: chrono::DateTime = before.get(1); + let before_reminders: Vec = serde_json::from_value(before.get(2)).unwrap(); + let before_steps: Vec = serde_json::from_value(before.get(3)).unwrap(); + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .unwrap(); + let clocks = service + .review_clocks(&fixture.producer, request_id, None, "") + .await + .unwrap(); + assert_eq!(clocks.len(), 2); + assert!(clocks + .iter() + .all(|clock| clock.state == ReviewClockState::Paused)); + fixture.database.execute("UPDATE casework_review_clock_occurrences SET next_action_at=now()-interval '1 minute',paused_at=paused_at-interval '2 hours' WHERE request_id=$1", &[&request_id]).await.unwrap(); + assert_eq!(service.process_due_review_clocks(100).await.unwrap(), 0); + let effects: i64 = fixture.database.query_one("SELECT count(*) FROM casework_review_clock_effects e JOIN casework_review_clock_occurrences c USING(clock_occurrence_id) WHERE c.request_id=$1", &[&request_id]).await.unwrap().get(0); + assert_eq!(effects, 0); + // Restore the pending instant after making it due only for the paused-runner check. + fixture + .database + .execute( + "UPDATE casework_review_clock_occurrences SET next_action_at=$2 WHERE task_id=$1", + &[&task, &before_next], + ) + .await + .unwrap(); + service + .answer_review_ask( + &fixture.producer, + request_id, + asked.ask.ask_id, + ReviewAskAnswer { + subject: create.subject, + answered_at: asked.ask.asked_at, + }, + "answer", + ) + .await + .unwrap(); + let after = fixture.database.query_one("SELECT due_at,next_action_at,reminders,steps,at_risk_at FROM casework_review_clock_occurrences WHERE task_id=$1", &[&task]).await.unwrap(); + let shift = after.get::<_, chrono::DateTime>(0) - before_due; + assert!(shift >= TimeDelta::hours(2)); + assert_eq!( + after.get::<_, chrono::DateTime>(1) - before_next, + shift + ); + let reminders: Vec = serde_json::from_value(after.get(2)).unwrap(); + let steps: Vec = serde_json::from_value(after.get(3)).unwrap(); + assert_eq!(reminders[0].at - before_reminders[0].at, shift); + assert_eq!(steps[0].at - before_steps[0].at, shift); + assert_eq!( + after.get::<_, chrono::DateTime>(4) - before.get::<_, chrono::DateTime>(4), + shift + ); +} + +#[tokio::test] +async fn c2_expiry_and_close_resume_clocks_and_a_closed_expired_ask_cannot_be_answered() { + let fixture = fixture().await; + let service = timed_asks_service(&fixture, true); + for expire in [false, true] { + let label = if expire { + "ask-expire-close" + } else { + "ask-close-pause" + }; + let (request_id, task, create) = claimed_for_asks(&fixture, &service, label).await; + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .unwrap(); + let mut answered_at = asked.ask.asked_at; + if expire { + let due = now_micros() - TimeDelta::minutes(1); + answered_at = due; + fixture + .database + .execute( + "UPDATE casework_review_asks SET asked_at=$2,due_at=$3 WHERE ask_id=$1", + &[&asked.ask.ask_id, &(due - TimeDelta::hours(1)), &due], + ) + .await + .unwrap(); + assert_eq!(service.process_due_review_clocks(100).await.unwrap(), 1); + assert_eq!( + service + .review_clocks(&fixture.producer, request_id, None, "") + .await + .unwrap()[0] + .state, + ReviewClockState::Running + ); + } + let current = service + .review_task(&fixture.reviewer_a, task, None, "") + .await + .unwrap(); + let expiry_time = service + .review_ask(&fixture.producer, request_id, asked.ask.ask_id) + .await + .unwrap() + .closed_at; + service + .decide_review_task( + &fixture.reviewer_a, + task, + ReviewTaskDecisionRequest { + decision: DecisionKind::Approve { + outcome: "approved".into(), + public_reason: None, + }, + }, + None, + "", + current.revision, + "decide", + ) + .await + .unwrap(); + assert_eq!( + ask_states(&fixture, request_id).await, + [if expire { "expired" } else { "closed" }] + ); + if expire { + assert_eq!( + service + .review_ask(&fixture.producer, request_id, asked.ask.ask_id) + .await + .unwrap() + .closed_at, + expiry_time + ); + } + assert_eq!( + service + .review_clocks(&fixture.producer, request_id, None, "") + .await + .unwrap()[0] + .state, + ReviewClockState::Running + ); + assert!(matches!( + service + .answer_review_ask( + &fixture.producer, + request_id, + asked.ask.ask_id, + ReviewAskAnswer { + subject: create.subject, + answered_at + }, + "answer-closed" + ) + .await, + Err(ReviewRuntimeError::ReviewAskNotOpen) + )); + } +} + +#[tokio::test] +async fn c2_resubmission_resumes_at_the_returning_stage_with_a_fresh_clock() { + let fixture = fixture().await; + let mut project = asks_project(true, true); + project.review_policies[0].resubmission = ReviewResubmissionPolicy::ResumeAtReturningStage; + let service = CaseworkService::new(fixture.store.clone(), project, Vec::new()).unwrap(); + let first = service + .create_review_request( + &fixture.producer, + bind_request(&service, request("resume", "ref-resume-1")), + "create-1", + ) + .await + .unwrap(); + let primary = task_id(&fixture, first.accepted.request_id, 0).await; + service + .claim_review_task(&fixture.reviewer_a, primary, None, "", 1, "claim-primary") + .await + .unwrap(); + service + .decide_review_task( + &fixture.reviewer_a, + primary, + ReviewTaskDecisionRequest { + decision: DecisionKind::Approve { + outcome: "approved".into(), + public_reason: None, + }, + }, + None, + "", + 2, + "approve-primary", + ) + .await + .unwrap(); + let secondary = task_id(&fixture, first.accepted.request_id, 1).await; + service + .claim_review_task( + &fixture.reviewer_b, + secondary, + None, + "", + 1, + "claim-secondary", + ) + .await + .unwrap(); + service + .decide_review_task( + &fixture.reviewer_b, + secondary, + ReviewTaskDecisionRequest { + decision: DecisionKind::ChangesRequested { + outcome: "needs-correction".into(), + public_reason: Some("Correct the form".into()), + reason: Some("Check the name".into()), + result: Some(json!({"correction": "name"})), + }, + }, + None, + "", + 2, + "return", + ) + .await + .unwrap(); + let old_clocks = service + .review_clocks(&fixture.producer, first.accepted.request_id, None, "") + .await + .unwrap(); + let mut next = bind_request(&service, request("resume", "ref-resume-2")); + next.subject.version = "2".into(); + next.subject.digest = ContentDigest::for_bytes(b"resume-2"); + let second = service + .create_review_request(&fixture.producer, next, "create-2") + .await + .unwrap(); + let rows = fixture + .database + .query( + "SELECT stage_index,stage_id FROM casework_review_tasks WHERE request_id=$1", + &[&second.accepted.request_id], + ) + .await + .unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].get::<_, i32>(0), 1); + assert_eq!(rows[0].get::<_, String>(1), "secondary"); + let detail: serde_json::Value = fixture.database.query_one("SELECT detail FROM casework_review_history WHERE request_id=$1 AND kind='review-resumed-at-stage'", &[&second.accepted.request_id]).await.unwrap().get(0); + assert_eq!(detail, json!({"stageId":"secondary"})); + let clocks = service + .review_clocks(&fixture.producer, second.accepted.request_id, None, "") + .await + .unwrap(); + assert_ne!( + clocks[0].clock_occurrence_id, + old_clocks[0].clock_occurrence_id + ); + assert!(clocks[0].anchor_at > old_clocks[0].anchor_at); + let decisions: i64 = fixture + .database + .query_one( + "SELECT count(*) FROM casework_review_decisions WHERE request_id=$1", + &[&second.accepted.request_id], + ) + .await + .unwrap() + .get(0); + assert_eq!(decisions, 0); + let mut foreign = bind_request(&service, request("resume", "ref-resume-other")); + foreign.subject.version = "3".into(); + foreign.subject.digest = ContentDigest::for_bytes(b"other-producer-round"); + let foreign = service + .create_review_request(&other_producer(), foreign, "create-other") + .await + .unwrap(); + let foreign_index: i32 = fixture + .database + .query_one( + "SELECT active_stage_index FROM casework_review_requests WHERE request_id=$1", + &[&foreign.accepted.request_id], + ) + .await + .unwrap() + .get(0); + assert_eq!( + foreign_index, 0, + "another producer cannot inherit this producer's returning stage" + ); + + let mut revised = asks_project(true, true); + revised.review_policies[0].version = "asks-2".into(); + revised.review_policies[0].resubmission = ReviewResubmissionPolicy::ResumeAtReturningStage; + revised.review_policies[0].stages.truncate(1); + let revised = CaseworkService::new(fixture.store.clone(), revised, Vec::new()).unwrap(); + let mut fallback = bind_request(&revised, request("resume", "ref-resume-fallback")); + fallback.subject.version = "4".into(); + fallback.subject.digest = ContentDigest::for_bytes(b"missing-stage-round"); + let fallback = revised + .create_review_request(&fixture.producer, fallback, "create-fallback") + .await + .unwrap(); + let fallback_index: i32 = fixture + .database + .query_one( + "SELECT active_stage_index FROM casework_review_requests WHERE request_id=$1", + &[&fallback.accepted.request_id], + ) + .await + .unwrap() + .get(0); + assert_eq!( + fallback_index, 0, + "a removed returning stage falls back to the first stage" + ); +} + +async fn c2_returning_stage_round( + fixture: &Fixture, + service: &CaseworkService, + label: &str, +) -> Uuid { + let (request_id, primary, _) = claimed_for_asks(fixture, service, label).await; + service + .decide_review_task( + &fixture.reviewer_a, + primary, + ReviewTaskDecisionRequest { + decision: DecisionKind::Approve { + outcome: "approved".into(), + public_reason: None, + }, + }, + None, + "", + 2, + "approve-primary", + ) + .await + .unwrap(); + let secondary = task_id(fixture, request_id, 1).await; + service + .claim_review_task( + &fixture.reviewer_b, + secondary, + None, + "", + 1, + "claim-secondary", + ) + .await + .unwrap(); + service + .decide_review_task( + &fixture.reviewer_b, + secondary, + ReviewTaskDecisionRequest { + decision: DecisionKind::ChangesRequested { + outcome: "needs-correction".into(), + public_reason: Some("Correct the form".into()), + reason: Some("Check the name".into()), + result: Some(json!({"correction":"name"})), + }, + }, + None, + "", + 2, + "return", + ) + .await + .unwrap(); + request_id +} + +fn c2_resumption_service(fixture: &Fixture) -> CaseworkService { + let mut project = asks_project(true, true); + project.review_policies[0].resubmission = ReviewResubmissionPolicy::ResumeAtReturningStage; + CaseworkService::new(fixture.store.clone(), project, Vec::new()).unwrap() +} + +async fn c2_next_round_stage(fixture: &Fixture, service: &CaseworkService, label: &str) -> i32 { + let mut next = bind_request(service, request(label, &format!("ref-{label}-2"))); + next.subject.version = "2".into(); + next.subject.digest = ContentDigest::for_bytes(format!("{label}-2").as_bytes()); + let accepted = service + .create_review_request(&fixture.producer, next, "create-next") + .await + .unwrap(); + fixture + .database + .query_one( + "SELECT active_stage_index FROM casework_review_requests WHERE request_id=$1", + &[&accepted.accepted.request_id], + ) + .await + .unwrap() + .get(0) +} + +#[tokio::test] +async fn c2_resubmission_starts_at_first_stage_after_result_retention() { + for erase in [false, true] { + let fixture = fixture().await; + let service = c2_resumption_service(&fixture); + let prior = c2_returning_stage_round(&fixture, &service, "return-retained").await; + expire_review_results(&fixture, &[prior]).await; + if erase { + service.erase_expired_reviews().await.unwrap(); + } + let request = fixture + .database + .query_one( + "SELECT result_erased_at FROM casework_review_requests WHERE request_id=$1", + &[&prior], + ) + .await + .unwrap(); + assert_eq!( + request.get::<_, Option>>(0).is_some(), + erase + ); + let history: i64 = fixture + .database + .query_one( + "SELECT count(*) FROM casework_review_history WHERE request_id=$1", + &[&prior], + ) + .await + .unwrap() + .get(0); + assert_eq!(history == 0, erase); + assert_eq!( + c2_next_round_stage(&fixture, &service, "return-retained").await, + 0 + ); + } +} + +#[tokio::test] +async fn c2_sod_resumed_round_keeps_earlier_stage_reviewers_out_of_the_returning_stage() { + for (exclude, erase) in [(true, false), (true, true), (false, false)] { + let fixture = fixture().await; + let mut project = asks_project(true, true); + project.review_policies[0].resubmission = ReviewResubmissionPolicy::ResumeAtReturningStage; + project.review_policies[0].stages[1].exclude_previous_stage_reviewers = exclude; + let service = CaseworkService::new(fixture.store.clone(), project, Vec::new()).unwrap(); + let earlier = c2_returning_stage_round(&fixture, &service, "sod").await; + let mut next = bind_request(&service, request("sod", "ref-sod-2")); + next.subject.version = "2".into(); + next.subject.digest = ContentDigest::for_bytes(b"sod-2"); + let resumed = service + .create_review_request(&fixture.producer, next, "create-sod-2") + .await + .unwrap() + .accepted + .request_id; + if erase { + expire_review_results(&fixture, &[earlier]).await; + service.erase_expired_reviews().await.unwrap(); + let earlier_decisions: i64 = fixture + .database + .query_one( + "SELECT count(*) FROM casework_review_decisions WHERE request_id=$1", + &[&earlier], + ) + .await + .unwrap() + .get(0); + assert_eq!(earlier_decisions, 0, "the earlier round is erased"); + } + let returning = task_id(&fixture, resumed, 1).await; + let claimed = service + .claim_review_task( + &fixture.reviewer_a, + returning, + None, + "", + 1, + "claim-sod-returning", + ) + .await; + if !exclude { + claimed.expect("the policy lets an earlier-stage reviewer claim"); + service + .decide_review_task( + &fixture.reviewer_a, + returning, + ReviewTaskDecisionRequest { + decision: DecisionKind::Approve { + outcome: "approved".into(), + public_reason: None, + }, + }, + None, + "", + 2, + "approve-sod-returning", + ) + .await + .expect("the policy lets an earlier-stage reviewer decide"); + continue; + } + assert!( + matches!( + claimed, + Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties + )) + ), + "erase={erase}: {claimed:?}" + ); + let assigned = service + .assign_review_task( + &fixture.supervisor, + returning, + None, + "", + 1, + AssignmentRequest { + assignee: fixture.reviewer_a.principal.clone(), + reason: Some("nominate the earlier primary reviewer".to_owned()), + }, + "assign-sod-returning", + ) + .await; + assert!( + matches!( + assigned, + Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties + )) + ), + "erase={erase}: {assigned:?}" + ); + // Another reviewer still decides the returning stage. + service + .claim_review_task( + &fixture.reviewer_b, + returning, + None, + "", + 1, + "claim-sod-other", + ) + .await + .expect("a reviewer outside the earlier stages claims"); + service + .decide_review_task( + &fixture.reviewer_b, + returning, + ReviewTaskDecisionRequest { + decision: DecisionKind::ChangesRequested { + outcome: "needs-correction".into(), + public_reason: Some("Correct the form again".into()), + reason: Some("Check the name again".into()), + result: Some(json!({"correction":"name"})), + }, + }, + None, + "", + 2, + "return-again", + ) + .await + .unwrap(); + // A third round inherits the second round's prior-stage reviewers. + let mut third = bind_request(&service, request("sod", "ref-sod-3")); + third.subject.version = "3".into(); + third.subject.digest = ContentDigest::for_bytes(b"sod-3"); + let third = service + .create_review_request(&fixture.producer, third, "create-sod-3") + .await + .unwrap() + .accepted + .request_id; + let third_task = task_id(&fixture, third, 1).await; + assert!( + matches!( + service + .claim_review_task( + &fixture.reviewer_a, + third_task, + None, + "", + 1, + "claim-sod-third", + ) + .await, + Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties + )) + ), + "erase={erase}" + ); + // The set is erased with the resumed request's own decisions, and the + // third round keeps its copy: reviewer_a at stage 0 and reviewer_b at + // the returning stage 1. + expire_review_results(&fixture, &[resumed]).await; + service.erase_expired_reviews().await.unwrap(); + for (request_id, expected) in [(resumed, 0_i64), (third, 2)] { + let retained: i64 = fixture + .database + .query_one( + "SELECT count(*) FROM casework_review_prior_stage_reviewers + WHERE request_id=$1", + &[&request_id], + ) + .await + .unwrap() + .get(0); + assert_eq!(retained, expected, "erase={erase}"); + } + } +} + +/// A resumption service whose policy adds stages after `secondary`, each +/// excluding previous-stage reviewers, with the given negative-decision mode. +fn c2_sod2_service( + fixture: &Fixture, + later_stages: &[(&str, ReviewNegativeDecisionMode)], +) -> CaseworkService { + let mut project = asks_project(true, true); + let policy = &mut project.review_policies[0]; + policy.resubmission = ReviewResubmissionPolicy::ResumeAtReturningStage; + for (id, negative_decisions) in later_stages { + let mut stage = policy.stages[1].clone(); + stage.id = (*id).to_owned(); + stage.negative_decisions = *negative_decisions; + policy.stages.push(stage); + } + CaseworkService::new(fixture.store.clone(), project, Vec::new()).unwrap() +} + +async fn c2_sod2_member(fixture: &Fixture, subject: &str) -> ActorContext { + fixture + .database + .execute( + "INSERT INTO casework_memberships(team_id,issuer,subject,membership_kind) + VALUES('review-team','https://issuer.test',$1,'staff')", + &[&subject], + ) + .await + .unwrap(); + actor(subject, CaseworkActsAs::Staff, "staff") +} + +async fn c2_sod2_round( + fixture: &Fixture, + service: &CaseworkService, + label: &str, + version: u32, +) -> Uuid { + let mut next = bind_request(service, request(label, &format!("ref-{label}-{version}"))); + next.subject.version = version.to_string(); + next.subject.digest = ContentDigest::for_bytes(format!("{label}-{version}").as_bytes()); + service + .create_review_request( + &fixture.producer, + next, + &format!("create-{label}-{version}"), + ) + .await + .unwrap() + .accepted + .request_id +} + +async fn c2_sod2_active_stage(fixture: &Fixture, request_id: Uuid) -> i32 { + fixture + .database + .query_one( + "SELECT active_stage_index FROM casework_review_requests WHERE request_id=$1", + &[&request_id], + ) + .await + .unwrap() + .get(0) +} + +async fn c2_sod2_claim_and_decide( + service: &CaseworkService, + reviewer: &ActorContext, + task: Uuid, + decision: DecisionKind, + key: &str, +) -> ReviewTransition { + service + .claim_review_task(reviewer, task, None, "", 1, &format!("claim-{key}")) + .await + .unwrap_or_else(|error| panic!("{key}: claim: {error:?}")); + service + .decide_review_task( + reviewer, + task, + ReviewTaskDecisionRequest { decision }, + None, + "", + 2, + &format!("decide-{key}"), + ) + .await + .unwrap_or_else(|error| panic!("{key}: decide: {error:?}")) +} + +async fn c2_sod2_claim_is_refused( + service: &CaseworkService, + reviewer: &ActorContext, + task: Uuid, + key: &str, +) { + let claimed = service + .claim_review_task(reviewer, task, None, "", 1, &format!("claim-{key}")) + .await; + assert!( + matches!( + claimed, + Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties + )) + ), + "{key}: {claimed:?}" + ); +} + +fn c2_sod2_approve() -> DecisionKind { + DecisionKind::Approve { + outcome: "approved".into(), + public_reason: None, + } +} + +fn c2_sod2_return() -> DecisionKind { + DecisionKind::ChangesRequested { + outcome: "needs-correction".into(), + public_reason: Some("Correct the form".into()), + reason: Some("Check the name".into()), + result: Some(json!({"correction":"name"})), + } +} + +fn c2_sod2_reject(reason: &str) -> DecisionKind { + DecisionKind::Reject { + outcome: "incorrect".into(), + reason: Some(reason.into()), + public_reason: Some("The record is incorrect".into()), + result: Some(json!({"correction":"record"})), + } +} + +#[tokio::test] +async fn c2_sod2_returning_stage_reviewers_stay_out_of_later_stages_across_rounds() { + let fixture = fixture().await; + let service = c2_sod2_service( + &fixture, + &[("tertiary", ReviewNegativeDecisionMode::Settle)], + ); + let reviewer_c = c2_sod2_member(&fixture, "reviewer-c").await; + let reviewer_d = c2_sod2_member(&fixture, "reviewer-d").await; + // Round 1: reviewer_a approves stage 0, reviewer_b returns at stage 1. + c2_returning_stage_round(&fixture, &service, "strict").await; + + // Round 2 resumes at stage 1. reviewer_c approves it. + let second = c2_sod2_round(&fixture, &service, "strict", 2).await; + assert_eq!(c2_sod2_active_stage(&fixture, second).await, 1); + c2_sod2_claim_and_decide( + &service, + &reviewer_c, + task_id(&fixture, second, 1).await, + c2_sod2_approve(), + "strict-2-secondary", + ) + .await; + // Stage 2 excludes reviewer_b, who decided stage 1 in round 1, exactly as + // within one request. + let tertiary = task_id(&fixture, second, 2).await; + for (reviewer, key) in [ + (&fixture.reviewer_a, "strict-2-a"), + (&fixture.reviewer_b, "strict-2-b"), + (&reviewer_c, "strict-2-c"), + ] { + c2_sod2_claim_is_refused(&service, reviewer, tertiary, key).await; + } + let assigned = service + .assign_review_task( + &fixture.supervisor, + tertiary, + None, + "", + 1, + AssignmentRequest { + assignee: fixture.reviewer_b.principal.clone(), + reason: Some("nominate the earlier returning reviewer".to_owned()), + }, + "assign-strict-2-b", + ) + .await; + assert!( + matches!( + assigned, + Err(ReviewRuntimeError::Forbidden( + FailedCheck::SeparationOfDuties + )) + ), + "{assigned:?}" + ); + c2_sod2_claim_and_decide( + &service, + &reviewer_d, + tertiary, + c2_sod2_return(), + "strict-2-tertiary", + ) + .await; + + // Round 3 resumes at stage 2 and carries every stage index forward. + let third = c2_sod2_round(&fixture, &service, "strict", 3).await; + assert_eq!(c2_sod2_active_stage(&fixture, third).await, 2); + let stored = fixture + .database + .query( + "SELECT actor_subject,stage_index FROM casework_review_prior_stage_reviewers + WHERE request_id=$1 ORDER BY actor_subject", + &[&third], + ) + .await + .unwrap() + .into_iter() + .map(|row| (row.get::<_, String>(0), row.get::<_, i32>(1))) + .collect::>(); + assert_eq!( + stored, + [ + ("reviewer-a".to_owned(), 0), + ("reviewer-b".to_owned(), 1), + ("reviewer-c".to_owned(), 1), + ("reviewer-d".to_owned(), 2), + ] + ); + let returning = task_id(&fixture, third, 2).await; + for (reviewer, key) in [ + (&fixture.reviewer_b, "strict-3-b"), + (&reviewer_c, "strict-3-c"), + ] { + c2_sod2_claim_is_refused(&service, reviewer, returning, key).await; + } + // The reviewer who returned stage 2 may review it again. + c2_sod2_claim_and_decide( + &service, + &reviewer_d, + returning, + c2_sod2_approve(), + "strict-3-tertiary", + ) + .await; +} + +#[tokio::test] +async fn c2_sod2_staffing_shortfall_counts_earlier_round_reviewers_out() { + // (required approvals at the returning stage, stage flag, shortfall) + for (required, exclude, shortfall) in [(2, true, true), (2, false, false), (1, true, false)] { + let fixture = fixture().await; + let mut project = asks_project(true, true); + project.review_policies[0].resubmission = ReviewResubmissionPolicy::ResumeAtReturningStage; + project.review_policies[0].stages[1].required_approvals = required; + project.review_policies[0].stages[1].exclude_previous_stage_reviewers = exclude; + let service = CaseworkService::new(fixture.store.clone(), project, Vec::new()).unwrap(); + c2_returning_stage_round(&fixture, &service, "staffing").await; + let resumed = c2_sod2_round(&fixture, &service, "staffing", 2).await; + assert_eq!(c2_sod2_active_stage(&fixture, resumed).await, 1); + // reviewer_a decided stage 0 of round 1 and counts out where the stage + // asks for it. reviewer_b returned stage 1 and still counts. + let task = service + .review_task( + &fixture.reviewer_b, + task_id(&fixture, resumed, 1).await, + None, + "", + ) + .await + .unwrap(); + assert_eq!( + task.staffing_diagnostic, + shortfall.then_some(StaffingDiagnostic::InsufficientDistinctApprovers), + "required={required} exclude={exclude}" + ); + } +} + +#[tokio::test] +async fn c2_sod2_advisory_reasons_stay_hidden_from_earlier_round_reviewers() { + let fixture = fixture().await; + let service = c2_sod2_service( + &fixture, + &[ + ("advice", ReviewNegativeDecisionMode::Advise), + ("final", ReviewNegativeDecisionMode::Settle), + ], + ); + let reviewer_c = c2_sod2_member(&fixture, "reviewer-c").await; + let reviewer_d = c2_sod2_member(&fixture, "reviewer-d").await; + let reviewer_e = c2_sod2_member(&fixture, "reviewer-e").await; + c2_returning_stage_round(&fixture, &service, "advisory-sod").await; + let resumed = c2_sod2_round(&fixture, &service, "advisory-sod", 2).await; + c2_sod2_claim_and_decide( + &service, + &reviewer_c, + task_id(&fixture, resumed, 1).await, + c2_sod2_approve(), + "advisory-sod-secondary", + ) + .await; + let advisory_task = task_id(&fixture, resumed, 2).await; + assert_eq!( + c2_sod2_claim_and_decide( + &service, + &reviewer_d, + advisory_task, + c2_sod2_reject("sod2 advisory private reason"), + "advisory-sod-advice", + ) + .await, + ReviewTransition::StageAdvanced { + completed_stage: "advice".to_owned(), + next_stage: "final".to_owned(), + } + ); + // reviewer_a and reviewer_b decided earlier stages of round 1 and are + // excluded from the final stage, so they do not read its accountability. + for (reviewer, readable) in [ + (&fixture.reviewer_a, false), + (&fixture.reviewer_b, false), + (&reviewer_e, true), + ] { + let history = service + .review_history(reviewer, resumed, None, "", None, 100) + .await + .unwrap(); + let advisory = history + .items + .iter() + .find(|entry| entry.task_id == Some(advisory_task) && entry.kind == "review-decided") + .expect("the advisory decision is in ordinary history"); + assert_eq!( + advisory.detail.get("privateReason").is_some(), + readable, + "{}", + reviewer.principal.subject + ); + } +} + +#[tokio::test] +async fn c2_sod2_an_erased_later_round_stops_an_older_round_resuming() { + let fixture = fixture().await; + let older = c2_resumption_service(&fixture); + // A later revision of the same policy keeps terminal results for less time. + let mut project = asks_project(true, true); + project.project = ProjectIdentity::new("review-test".parse().unwrap(), "asks-2".to_owned()); + let policy = &mut project.review_policies[0]; + policy.version = "asks-2".to_owned(); + policy.resubmission = ReviewResubmissionPolicy::ResumeAtReturningStage; + policy.retention.terminal_retention_days = 30; + let shorter = CaseworkService::new(fixture.store.clone(), project, Vec::new()).unwrap(); + + // Round 1 (90-day results) returns at stage 1. + let first = c2_returning_stage_round(&fixture, &older, "erased-later").await; + // Round 2 (30-day results) resumes at stage 1 and is rejected. + let second = c2_sod2_round(&fixture, &shorter, "erased-later", 2).await; + assert_eq!(c2_sod2_active_stage(&fixture, second).await, 1); + c2_sod2_claim_and_decide( + &shorter, + &fixture.reviewer_b, + task_id(&fixture, second, 1).await, + c2_sod2_reject("rejected in the later round"), + "erased-later-2", + ) + .await; + // Forty days pass: round 2's results expire, round 1's do not. + for statement in [ + "UPDATE casework_review_requests SET created_at=created_at-interval '40 days', + terminal_at=terminal_at-interval '40 days', + result_available_until=result_available_until-interval '40 days' + WHERE request_id=ANY($1)", + "UPDATE casework_review_results SET completed_at=completed_at-interval '40 days', + available_until=available_until-interval '40 days' + WHERE request_id=ANY($1)", + "UPDATE casework_review_terminal_events SET completed_at=completed_at-interval '40 days', + retained_until=retained_until-interval '40 days' + WHERE request_id=ANY($1)", + ] { + fixture + .database + .execute(statement, &[&vec![first, second]]) + .await + .unwrap(); + } + shorter.erase_expired_reviews().await.unwrap(); + for (request_id, erased) in [(first, false), (second, true)] { + let row = fixture + .database + .query_one( + "SELECT result_erased_at IS NOT NULL FROM casework_review_requests + WHERE request_id=$1", + &[&request_id], + ) + .await + .unwrap(); + assert_eq!(row.get::<_, bool>(0), erased); + } + // The latest round was rejected, so round 3 starts at the first stage even + // though round 1 is still retained. + let third = c2_sod2_round(&fixture, &shorter, "erased-later", 3).await; + assert_eq!(c2_sod2_active_stage(&fixture, third).await, 0); +} + +/// A resumption service for one revision of the policy with the given stage +/// order. `primary` keeps its asks; every other stage excludes previous-stage +/// reviewers. +fn c2_sod3_revision(fixture: &Fixture, version: &str, stage_ids: &[&str]) -> CaseworkService { + let mut project = asks_project(true, true); + project.project = ProjectIdentity::new("review-test".parse().unwrap(), version.to_owned()); + let policy = &mut project.review_policies[0]; + policy.version = version.to_owned(); + policy.resubmission = ReviewResubmissionPolicy::ResumeAtReturningStage; + let (primary, later) = (policy.stages[0].clone(), policy.stages[1].clone()); + policy.stages = stage_ids + .iter() + .map(|id| { + let mut stage = if *id == "primary" { + primary.clone() + } else { + later.clone() + }; + stage.id = (*id).to_owned(); + stage + }) + .collect(); + CaseworkService::new(fixture.store.clone(), project, Vec::new()).unwrap() +} + +#[tokio::test] +async fn c2_sod3_resumption_needs_the_same_stages_up_to_the_returning_stage() { + // Round 1 under [primary, secondary, tertiary] returns at tertiary. A + // revision that moves tertiary first starts the resubmission at the first + // stage, so earlier-round stage positions never under-exclude. + let fixture = fixture().await; + let earlier = c2_sod3_revision(&fixture, "order-1", &["primary", "secondary", "tertiary"]); + let reviewer_c = c2_sod2_member(&fixture, "reviewer-c").await; + let (first, primary, _) = claimed_for_asks(&fixture, &earlier, "reordered").await; + earlier + .decide_review_task( + &fixture.reviewer_a, + primary, + ReviewTaskDecisionRequest { + decision: c2_sod2_approve(), + }, + None, + "", + 2, + "decide-reordered-primary", + ) + .await + .unwrap(); + c2_sod2_claim_and_decide( + &earlier, + &fixture.reviewer_b, + task_id(&fixture, first, 1).await, + c2_sod2_approve(), + "reordered-secondary", + ) + .await; + c2_sod2_claim_and_decide( + &earlier, + &reviewer_c, + task_id(&fixture, first, 2).await, + c2_sod2_return(), + "reordered-tertiary", + ) + .await; + let reordered = c2_sod3_revision(&fixture, "order-2", &["tertiary", "primary", "secondary"]); + let second = c2_sod2_round(&fixture, &reordered, "reordered", 2).await; + assert_eq!(c2_sod2_active_stage(&fixture, second).await, 0); + let history: i64 = fixture + .database + .query_one( + "SELECT count(*) FROM casework_review_history + WHERE request_id=$1 AND kind='review-resumed-at-stage'", + &[&second], + ) + .await + .unwrap() + .get(0); + assert_eq!(history, 0); + let prior: i64 = fixture + .database + .query_one( + "SELECT count(*) FROM casework_review_prior_stage_reviewers WHERE request_id=$1", + &[&second], + ) + .await + .unwrap() + .get(0); + assert_eq!(prior, 0); +} + +#[tokio::test] +async fn c2_sod3_stages_added_or_reordered_above_the_returning_stage_still_resume() { + for (label, later_order) in [ + ( + "added-above", + &["primary", "secondary", "tertiary", "quaternary", "extra"][..], + ), + ( + "reordered-above", + &["primary", "secondary", "quaternary", "tertiary"][..], + ), + ] { + let fixture = fixture().await; + let earlier = c2_sod3_revision( + &fixture, + "above-1", + &["primary", "secondary", "tertiary", "quaternary"], + ); + // reviewer_a approves primary, reviewer_b returns at secondary. + c2_returning_stage_round(&fixture, &earlier, label).await; + let revised = c2_sod3_revision(&fixture, "above-2", later_order); + let resumed = c2_sod2_round(&fixture, &revised, label, 2).await; + assert_eq!(c2_sod2_active_stage(&fixture, resumed).await, 1, "{label}"); + } +} + +/// The protocol carries answer times at microsecond precision. +fn now_micros() -> chrono::DateTime { + let now = Utc::now(); + now - TimeDelta::nanoseconds(i64::from(now.timestamp_subsec_nanos() % 1_000)) +} + +fn other_producer() -> ActorContext { + actor("other-service", CaseworkActsAs::Requester, "other-producer") +} + +#[tokio::test] +async fn c2_fix_old_answer_preserves_a_new_asks_waiting_marker() { + let fixture = fixture().await; + let service = timed_asks_service(&fixture, true); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "marker-round").await; + let old = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("First?"), + None, + "", + 2, + "old", + ) + .await + .unwrap(); + let due = now_micros() - TimeDelta::minutes(1); + fixture + .database + .execute( + "UPDATE casework_review_asks SET asked_at=$2,due_at=$3 WHERE ask_id=$1", + &[&old.ask.ask_id, &(due - TimeDelta::hours(1)), &due], + ) + .await + .unwrap(); + service.process_due_review_clocks(100).await.unwrap(); + let current = service + .review_task(&fixture.reviewer_a, task, None, "") + .await + .unwrap(); + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Second?"), + None, + "", + current.revision, + "new", + ) + .await + .unwrap(); + service + .answer_review_ask( + &fixture.producer, + request_id, + old.ask.ask_id, + ReviewAskAnswer { + subject: create.subject, + answered_at: due, + }, + "old-answer", + ) + .await + .unwrap(); + assert_eq!(ask_marker(&fixture, task).await.as_deref(), Some("waiting")); + assert_eq!( + service + .review_clocks(&fixture.producer, request_id, None, "") + .await + .unwrap()[0] + .state, + ReviewClockState::Paused + ); +} + +#[tokio::test] +async fn c2_fix_recompute_preserves_the_pause() { + let fixture = fixture().await; + let mut project = activity_clock_project(); + project.trusted_producers[0].reads_asks = true; + project.trusted_producers[0].completion = None; + project.review_policies[0].stages[0].asks = Some(ReviewStageAsksPolicy { + answer_within: Some(ElapsedDuration::Hours(1)), + pause_clocks: true, + ..Default::default() + }); + project + .access_profiles + .push(profile("clock-admin", CaseworkActsAs::Administrator)); + let service = CaseworkService::new(fixture.store.clone(), project, Vec::new()).unwrap(); + service + .create_holiday_revision( + &actor("admin", CaseworkActsAs::Administrator, "administrator"), + &HolidaySetDocument { + holiday_set: "office-holidays".into(), + revision: 1, + dates: Vec::new(), + }, + "holidays", + ) + .await + .unwrap(); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "recompute-pause").await; + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .unwrap(); + fixture.database.execute("UPDATE casework_review_clock_occurrences SET paused_at=paused_at-interval '2 hours' WHERE request_id=$1", &[&request_id]).await.unwrap(); + service + .answer_review_ask( + &fixture.producer, + request_id, + asked.ask.ask_id, + ReviewAskAnswer { + subject: create.subject, + answered_at: asked.ask.asked_at, + }, + "answer", + ) + .await + .unwrap(); + let due = service + .review_clocks(&fixture.producer, request_id, None, "") + .await + .unwrap()[0] + .due_at; + let admin = actor("clock-admin", CaseworkActsAs::Administrator, "clock-admin"); + let preview = service + .preview_review_clock_recompute( + &admin, + None, + "", + ReviewClockRecomputeRequest { + task_ids: vec![task], + }, + ) + .await + .unwrap(); + assert_eq!(preview.tasks[0].deadline_at, due); + service + .apply_review_clock_recompute( + &admin, + None, + "", + ReviewClockRecomputeApplyRequest { + preview_id: preview.preview_id, + }, + ) + .await + .unwrap(); + assert_eq!( + service + .review_clocks(&fixture.producer, request_id, None, "") + .await + .unwrap()[0] + .due_at, + due + ); +} + +#[tokio::test] +async fn c2_fix_old_answer_preserves_the_newest_expired_asks_marker() { + let fixture = fixture().await; + let service = timed_asks_service(&fixture, true); + let (request_id, task, create) = + claimed_for_asks(&fixture, &service, "expired-marker-round").await; + let mut asks = Vec::new(); + for (index, text) in ["First?", "Second?"].into_iter().enumerate() { + let current = service + .review_task(&fixture.reviewer_a, task, None, "") + .await + .unwrap(); + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request(text), + None, + "", + current.revision, + &format!("ask-{index}"), + ) + .await + .unwrap(); + let due = now_micros() - TimeDelta::minutes(2 - index as i64); + fixture + .database + .execute( + "UPDATE casework_review_asks SET asked_at=$2,due_at=$3 WHERE ask_id=$1", + &[&asked.ask.ask_id, &(due - TimeDelta::hours(1)), &due], + ) + .await + .unwrap(); + assert_eq!(service.process_due_review_clocks(100).await.unwrap(), 1); + asks.push((asked.ask.ask_id, due)); + } + service + .answer_review_ask( + &fixture.producer, + request_id, + asks[0].0, + ReviewAskAnswer { + subject: create.subject.clone(), + answered_at: asks[0].1, + }, + "answer-old", + ) + .await + .unwrap(); + assert_eq!(ask_marker(&fixture, task).await.as_deref(), Some("expired")); + assert_eq!( + service + .review_task(&fixture.reviewer_a, task, None, "") + .await + .unwrap() + .marker, + Some(ReviewTaskMarker::Expired) + ); + service + .answer_review_ask( + &fixture.producer, + request_id, + asks[1].0, + ReviewAskAnswer { + subject: create.subject, + answered_at: asks[1].1, + }, + "answer-newest", + ) + .await + .unwrap(); + assert_eq!( + ask_marker(&fixture, task).await.as_deref(), + Some("answered") + ); +} + +async fn c2_later_round_fallback(lifecycle: &str) { + let fixture = fixture().await; + let service = c2_resumption_service(&fixture); + c2_returning_stage_round(&fixture, &service, "latest-round").await; + let mut next = bind_request(&service, request("latest-round", "ref-latest-round-2")); + next.subject.version = "2".into(); + next.subject.digest = ContentDigest::for_bytes(b"latest-round-2"); + let second = service + .create_review_request(&fixture.producer, next.clone(), "create-second") + .await + .unwrap(); + if lifecycle == "cancelled" { + service + .cancel_review_request( + &fixture.producer, + second.accepted.request_id, + ReviewCancelRequest { + subject: next.subject, + reason: "No longer needed".into(), + }, + "cancel", + ) + .await + .unwrap(); + } else if lifecycle != "open" { + let task = task_id(&fixture, second.accepted.request_id, 1).await; + service + .claim_review_task(&fixture.reviewer_b, task, None, "", 1, "claim") + .await + .unwrap(); + let decision = if lifecycle == "approved" { + DecisionKind::Approve { + outcome: "approved".into(), + public_reason: None, + } + } else { + DecisionKind::Reject { + outcome: "incorrect".into(), + public_reason: Some("Refused".into()), + reason: Some("Refused".into()), + result: Some(json!({"correction":"name"})), + } + }; + service + .decide_review_task( + &fixture.reviewer_b, + task, + ReviewTaskDecisionRequest { decision }, + None, + "", + 2, + "decide", + ) + .await + .unwrap(); + } + let mut third = bind_request(&service, request("latest-round", "ref-latest-round-3")); + third.subject.version = "3".into(); + third.subject.digest = ContentDigest::for_bytes(b"latest-round-3"); + let third = service + .create_review_request(&fixture.producer, third, "create-third") + .await + .unwrap(); + let stage: i32 = fixture + .database + .query_one( + "SELECT active_stage_index FROM casework_review_requests WHERE request_id=$1", + &[&third.accepted.request_id], + ) + .await + .unwrap() + .get(0); + assert_eq!( + stage, 0, + "latest {lifecycle} round must prevent reuse of an older return" + ); +} + +#[tokio::test] +async fn c2_fix_latest_approved_round_starts_at_first_stage() { + c2_later_round_fallback("approved").await; +} +#[tokio::test] +async fn c2_fix_latest_cancelled_round_starts_at_first_stage() { + c2_later_round_fallback("cancelled").await; +} +#[tokio::test] +async fn c2_fix_latest_rejected_round_starts_at_first_stage() { + c2_later_round_fallback("rejected").await; +} +#[tokio::test] +async fn c2_fix_latest_open_round_starts_at_first_stage() { + c2_later_round_fallback("open").await; +} + +#[tokio::test] +async fn c2_fix_resumption_isolates_subject_and_policy() { + let fixture = fixture().await; + let service = c2_resumption_service(&fixture); + c2_returning_stage_round(&fixture, &service, "isolated-return").await; + assert_eq!( + c2_next_round_stage(&fixture, &service, "other-subject").await, + 0 + ); + let mut project = asks_project(true, true); + project.review_policies[0].id = "other-policy".into(); + for producer in &mut project.trusted_producers { + producer.review_policies = vec!["other-policy".into()]; + } + project.review_policies[0].resubmission = ReviewResubmissionPolicy::ResumeAtReturningStage; + let other = CaseworkService::new(fixture.store.clone(), project, Vec::new()).unwrap(); + let mut next = request("isolated-return", "ref-other-policy"); + next.policy.id = "other-policy".into(); + let next = bind_request(&other, next); + let next = other + .create_review_request(&fixture.producer, next, "other-policy") + .await + .unwrap(); + let stage: i32 = fixture + .database + .query_one( + "SELECT active_stage_index FROM casework_review_requests WHERE request_id=$1", + &[&next.accepted.request_id], + ) + .await + .unwrap() + .get(0); + assert_eq!(stage, 0); +} + +#[tokio::test] +async fn c2_fix_pause_expiry_and_resume_are_audited_in_both_orders() { + for expiry_first in [true, false] { + let fixture = fixture().await; + let mut project = asks_project(true, true); + project.review_policies[0].stages[0].asks = Some(ReviewStageAsksPolicy { + answer_within: Some(ElapsedDuration::Hours(1)), + pause_clocks: true, + ..Default::default() + }); + let (service, audit) = service_with_audit(&fixture, project); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "ordered-race").await; + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .unwrap(); + assert_eq!(audit.responses("review-clock-paused").len(), 1); + let due = now_micros() - TimeDelta::minutes(1); + fixture + .database + .execute( + "UPDATE casework_review_asks SET asked_at=$2,due_at=$3 WHERE ask_id=$1", + &[&asked.ask.ask_id, &(due - TimeDelta::hours(1)), &due], + ) + .await + .unwrap(); + fixture.database.batch_execute("BEGIN").await.unwrap(); + if expiry_first { + fixture.database.query("SELECT clock_occurrence_id FROM casework_review_clock_occurrences WHERE request_id=$1 FOR UPDATE", &[&request_id]).await.unwrap(); + } else { + fixture + .database + .query( + "SELECT ask_id FROM casework_review_asks WHERE ask_id=$1 FOR UPDATE", + &[&asked.ask.ask_id], + ) + .await + .unwrap(); + } + let answer = service.answer_review_ask( + &fixture.producer, + request_id, + asked.ask.ask_id, + ReviewAskAnswer { + subject: create.subject, + answered_at: due, + }, + "answer", + ); + let expiry = service.process_due_review_clocks(100); + tokio::pin!(answer, expiry); + if expiry_first { + tokio::select! { + result = &mut expiry => panic!("expiry must wait on the clock lock: {result:?}"), + () = c2_wait_for_blocked_sessions(&fixture, 1) => {} + } + tokio::select! { + result = &mut answer => panic!("answer must wait behind expiry: {result:?}"), + () = c2_wait_for_blocked_sessions(&fixture, 2) => {} + } + release_lock(&fixture).await; + let (expiry, answer) = tokio::join!(&mut expiry, &mut answer); + assert_eq!(expiry.unwrap(), 1); + assert_eq!(answer.unwrap().state, ReviewAskState::Answered); + } else { + tokio::select! { + result = &mut answer => panic!("answer must wait on the ask lock: {result:?}"), + () = c2_wait_for_blocked_sessions(&fixture, 1) => {} + } + assert_eq!( + expiry.await.unwrap(), + 0, + "expiry skips the request locked by the answer" + ); + release_lock(&fixture).await; + assert_eq!(answer.await.unwrap().state, ReviewAskState::Answered); + } + assert_eq!(service.process_due_review_clocks(100).await.unwrap(), 0); + assert_eq!( + audit.responses("review-ask-expired").len(), + usize::from(expiry_first) + ); + assert_eq!(audit.responses("review-clock-resumed").len(), 1); + assert_eq!( + ask_changes(&fixture, request_id).await, + if expiry_first { + vec!["opened", "expired", "answered"] + } else { + vec!["opened", "answered"] + } + ); + } +} + +async fn c2_wait_for_blocked_sessions(fixture: &Fixture, minimum: i64) { + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + fixture.database.batch_execute("SELECT pg_stat_clear_snapshot()").await.unwrap(); + let waiting:i64 = fixture.database.query_one("SELECT count(*) FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock' AND pid<>pg_backend_pid()", &[&fixture.application_name]).await.unwrap().get(0); + if waiting >= minimum { return; } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }).await.expect("the intended transaction order must be observed, without timing guesses"); +} + +#[tokio::test] +async fn c2_fix_cancellation_and_supersession_resume_paused_clocks() { + for supersede in [false, true] { + let fixture = fixture().await; + let mut project = asks_project(true, true); + project.review_policies[0].stages[0].asks = Some(ReviewStageAsksPolicy { + answer_within: Some(ElapsedDuration::Hours(1)), + pause_clocks: true, + ..Default::default() + }); + let (service, audit) = service_with_audit(&fixture, project); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "close-paused").await; + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .unwrap(); + if supersede { + let mut next = create; + next.requester_reference = "superseding-ref".into(); + next.subject.version = "2".into(); + next.subject.digest = ContentDigest::for_bytes(b"superseding"); + service + .create_review_request(&fixture.producer, next, "supersede") + .await + .unwrap(); + } else { + service + .cancel_review_request( + &fixture.producer, + request_id, + ReviewCancelRequest { + subject: create.subject, + reason: "Withdrawn".into(), + }, + "cancel", + ) + .await + .unwrap(); + } + assert_eq!(ask_states(&fixture, request_id).await, ["closed"]); + let paused:i64 = fixture.database.query_one("SELECT count(*) FROM casework_review_clock_occurrences WHERE request_id=$1 AND (state='paused' OR paused_at IS NOT NULL OR paused_ask_id IS NOT NULL)", &[&request_id]).await.unwrap().get(0); + assert_eq!(paused, 0); + assert_eq!( + audit + .responses(if supersede { + "clock-resumed" + } else { + "review-clock-resumed" + }) + .len(), + 1 + ); + } +} + +fn ask_request(text: &str) -> ReviewTaskAskRequest { + ReviewTaskAskRequest { + text: text.to_owned(), + wants: vec![ + registry_casework_core::ReviewAskWant::Answer {}, + registry_casework_core::ReviewAskWant::Document {}, + ], + } +} + +/// A review at its first stage, claimed by reviewer A. The task is at revision 2. +async fn claimed_for_asks( + fixture: &Fixture, + service: &CaseworkService, + label: &str, +) -> (Uuid, Uuid, ReviewCreateRequest) { + let create = bind_request(service, request(label, &format!("ref-{label}"))); + let created = service + .create_review_request( + &fixture.producer, + create.clone(), + &format!("create-{label}"), + ) + .await + .expect("create review"); + let request_id = created.accepted.request_id; + let task = task_id(fixture, request_id, 0).await; + service + .claim_review_task( + &fixture.reviewer_a, + task, + None, + "", + 1, + &format!("claim-{label}"), + ) + .await + .expect("claim review task"); + (request_id, task, create) +} + +async fn ask_states(fixture: &Fixture, request_id: Uuid) -> Vec { + fixture + .database + .query( + "SELECT state FROM casework_review_asks WHERE request_id=$1 ORDER BY asked_at", + &[&request_id], + ) + .await + .expect("ask states") + .iter() + .map(|row| row.get(0)) + .collect() +} + +async fn ask_marker(fixture: &Fixture, task: Uuid) -> Option { + fixture + .database + .query_one( + "SELECT ask_marker FROM casework_review_tasks WHERE task_id=$1", + &[&task], + ) + .await + .expect("ask marker") + .get(0) +} + +async fn ask_changes(fixture: &Fixture, request_id: Uuid) -> Vec { + fixture + .database + .query( + "SELECT change FROM casework_review_ask_events WHERE request_id=$1 ORDER BY feed_position", + &[&request_id], + ) + .await + .expect("ask events") + .iter() + .map(|row| row.get(0)) + .collect() +} + +#[tokio::test] +async fn the_holder_asks_the_applicant_and_the_producer_reads_the_ask() { + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + let (request_id, task, _) = claimed_for_asks(&fixture, &service, "ask-open").await; + + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Send the signed form."), + None, + "", + 2, + "ask-1", + ) + .await + .expect("holder asks"); + assert_eq!(asked.task.revision, 3); + assert_eq!( + asked.task.marker, + Some(registry_casework_core::ReviewTaskMarker::Waiting) + ); + assert!( + matches!(asked.task.state, ReviewTaskState::Held { ref holder } + if holder == &fixture.reviewer_a.principal) + ); + assert_eq!( + asked.ask.state, + registry_casework_core::ReviewAskState::Open + ); + assert_eq!(ask_states(&fixture, request_id).await, ["open"]); + assert_eq!(ask_changes(&fixture, request_id).await, ["opened"]); + assert_eq!(ask_marker(&fixture, task).await.as_deref(), Some("waiting")); + + // The history row names the ask and holds no text. + let history = fixture + .database + .query_one( + "SELECT detail::text FROM casework_review_history + WHERE request_id=$1 AND kind='ask-opened'", + &[&request_id], + ) + .await + .expect("ask-opened history") + .get::<_, String>(0); + assert!(history.contains(&asked.ask.ask_id.to_string())); + assert!(!history.contains("signed form")); + + // The producer sees it in its feed and reads it; another producer does not. + let feed = service + .review_ask_feed(&fixture.producer, None, 10) + .await + .expect("feed"); + assert_eq!(feed.items.len(), 1); + assert_eq!(feed.items[0].ask_id, asked.ask.ask_id); + assert!(service + .review_ask_feed(&other_producer(), None, 10) + .await + .expect("other feed") + .items + .is_empty()); + let read = service + .review_ask(&fixture.producer, request_id, asked.ask.ask_id) + .await + .expect("read ask"); + assert_eq!(read, asked.ask); + assert!(matches!( + service + .review_ask(&other_producer(), request_id, asked.ask.ask_id) + .await, + Err(ReviewRuntimeError::NotFound) + )); + assert!(matches!( + service + .review_ask(&fixture.producer, request_id, Uuid::new_v4()) + .await, + Err(ReviewRuntimeError::NotFound) + )); + + // The context lists the ask for the reviewer, and the task carries its marker. + let context = service + .review_task_context(&fixture.reviewer_a, task, None, "") + .await + .expect("context"); + assert_eq!(context.asks.len(), 1); + assert_eq!(context.asks[0].task_id, task); + assert_eq!(context.asks[0].text, "Send the signed form."); + let read_task = service + .review_task(&fixture.reviewer_a, task, None, "") + .await + .expect("task"); + assert_eq!( + read_task.marker, + Some(registry_casework_core::ReviewTaskMarker::Waiting) + ); + + // An exact replay under the same key returns the stored response. + let replay = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Send the signed form."), + None, + "", + 2, + "ask-1", + ) + .await + .expect("replay"); + assert_eq!(replay, asked); + assert_eq!(ask_states(&fixture, request_id).await.len(), 1); +} + +#[tokio::test] +async fn an_ask_is_refused_unless_every_condition_holds() { + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + + // Unclaimed task. + let created = service + .create_review_request( + &fixture.producer, + bind_request(&service, request("ask-unclaimed", "ref-unclaimed")), + "create-unclaimed", + ) + .await + .expect("create"); + let unclaimed = task_id(&fixture, created.accepted.request_id, 0).await; + assert!(matches!( + service + .ask_applicant( + &fixture.reviewer_a, + unclaimed, + ask_request("Why?"), + None, + "", + 1, + "k" + ) + .await, + Err(ReviewRuntimeError::TaskNotHeld) + )); + + // Not the holder, stale revision, then a second open ask. + let (request_id, task, _) = claimed_for_asks(&fixture, &service, "ask-refusals").await; + assert!(matches!( + service + .ask_applicant( + &fixture.reviewer_b, + task, + ask_request("Why?"), + None, + "", + 2, + "k-b" + ) + .await, + Err(ReviewRuntimeError::TaskNotHeld) + )); + assert!(matches!( + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 1, + "k-stale" + ) + .await, + Err(ReviewRuntimeError::RevisionConflict) + )); + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "k-first", + ) + .await + .expect("first ask"); + assert!(matches!( + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Again?"), + None, + "", + 3, + "k-second" + ) + .await, + Err(ReviewRuntimeError::ReviewAskAlreadyOpen) + )); + assert_eq!(ask_states(&fixture, request_id).await, ["open"]); + + // Invalid text and wants. + assert!(matches!( + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request(" "), + None, + "", + 3, + "k-empty" + ) + .await, + Err(ReviewRuntimeError::Invalid) + )); +} + +#[tokio::test] +async fn an_ask_needs_a_stage_that_offers_it_and_a_producer_that_reads_it() { + let fixture = fixture().await; + // A policy without asks behaves as before: the stage offers none. + let plain = asks_service(&fixture, false, true); + let (_, task, _) = claimed_for_asks(&fixture, &plain, "ask-plain").await; + assert!(matches!( + plain + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "k" + ) + .await, + Err(ReviewRuntimeError::ReviewAskNotOffered) + )); + assert_eq!(ask_marker(&fixture, task).await, None); + + // The stage offers asks and the producer does not read them. + // A project that checks refuses this combination, so the runtime check + // answers for a request accepted under an earlier project. + let reading = asks_service(&fixture, true, true); + let (_, task, _) = claimed_for_asks(&fixture, &reading, "ask-deaf").await; + let deaf = asks_service(&fixture, true, false); + assert!(matches!( + deaf.ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "k" + ) + .await, + Err(ReviewRuntimeError::ReviewAskProducerUnsupported) + )); +} + +#[tokio::test] +async fn an_ask_from_a_task_that_left_the_active_stage_is_refused_and_a_later_stage_offers_none() { + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + let (request_id, first, _) = claimed_for_asks(&fixture, &service, "ask-stage").await; + service + .decide_review_task( + &fixture.reviewer_a, + first, + ReviewTaskDecisionRequest { + decision: DecisionKind::Approve { + outcome: "approved".into(), + public_reason: None, + }, + }, + None, + "", + 2, + "decide-first", + ) + .await + .expect("advance the stage"); + assert!(matches!( + service + .ask_applicant( + &fixture.reviewer_a, + first, + ask_request("Why?"), + None, + "", + 3, + "k-old" + ) + .await, + Err(ReviewRuntimeError::ReviewAskTaskInactive) + )); + // The second stage declares no asks. + let second = task_id(&fixture, request_id, 1).await; + service + .claim_review_task(&fixture.reviewer_b, second, None, "", 1, "claim-second") + .await + .expect("claim second stage"); + assert!(matches!( + service + .ask_applicant( + &fixture.reviewer_b, + second, + ask_request("Why?"), + None, + "", + 2, + "k-new" + ) + .await, + Err(ReviewRuntimeError::ReviewAskNotOffered) + )); +} + +#[tokio::test] +async fn the_producer_answer_marks_the_task_answered_and_obeys_its_rules() { + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "ask-answer").await; + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Send the form."), + None, + "", + 2, + "ask", + ) + .await + .expect("ask"); + let ask_id = asked.ask.ask_id; + let answer = |at: chrono::DateTime| registry_casework_core::ReviewAskAnswer { + subject: create.subject.clone(), + answered_at: at, + }; + + // Another producer cannot answer it: concealed. + assert!(matches!( + service + .answer_review_ask( + &other_producer(), + request_id, + ask_id, + answer(now_micros()), + "o-1" + ) + .await, + Err(ReviewRuntimeError::NotFound) + )); + // The subject must equal the request's binding. + let mut moved = answer(now_micros()); + moved.subject.id = "another-subject".to_owned(); + assert!(matches!( + service + .answer_review_ask(&fixture.producer, request_id, ask_id, moved, "m-1") + .await, + Err(ReviewRuntimeError::NotFound) + )); + // The ask must belong to the request. + assert!(matches!( + service + .answer_review_ask( + &fixture.producer, + request_id, + Uuid::new_v4(), + answer(now_micros()), + "u-1" + ) + .await, + Err(ReviewRuntimeError::NotFound) + )); + // The answer time lies between the ask and a small skew ahead of now. + assert!(matches!( + service + .answer_review_ask( + &fixture.producer, + request_id, + ask_id, + answer(asked.ask.asked_at - TimeDelta::seconds(1)), + "t-1" + ) + .await, + Err(ReviewRuntimeError::ReviewAskAnswerTimeInvalid) + )); + assert!(matches!( + service + .answer_review_ask( + &fixture.producer, + request_id, + ask_id, + answer(now_micros() + TimeDelta::minutes(30)), + "t-2" + ) + .await, + Err(ReviewRuntimeError::ReviewAskAnswerTimeInvalid) + )); + assert_eq!(ask_states(&fixture, request_id).await, ["open"]); + assert_eq!(ask_marker(&fixture, task).await.as_deref(), Some("waiting")); + + let answered_at = now_micros(); + let answered = service + .answer_review_ask( + &fixture.producer, + request_id, + ask_id, + answer(answered_at), + "a-1", + ) + .await + .expect("answer"); + assert_eq!( + answered.state, + registry_casework_core::ReviewAskState::Answered + ); + // The response serves the stored microsecond time, as the read does. + let stored = service + .review_ask(&fixture.producer, request_id, ask_id) + .await + .expect("read answered ask"); + assert_eq!(stored, answered); + assert_eq!(answered.answered_at, Some(answered_at)); + assert_eq!( + ask_marker(&fixture, task).await.as_deref(), + Some("answered") + ); + assert_eq!( + ask_changes(&fixture, request_id).await, + ["opened", "answered"] + ); + // The task returns to its holder at the next revision. + let task_now = service + .review_task(&fixture.reviewer_a, task, None, "") + .await + .expect("task"); + assert_eq!(task_now.revision, 4); + assert_eq!( + task_now.marker, + Some(registry_casework_core::ReviewTaskMarker::Answered) + ); + assert!(matches!(task_now.state, ReviewTaskState::Held { .. })); + let history: i64 = fixture + .database + .query_one( + "SELECT count(*) FROM casework_review_history + WHERE request_id=$1 AND kind='ask-answered'", + &[&request_id], + ) + .await + .expect("history") + .get(0); + assert_eq!(history, 1); + + // An exact replay returns the stored response and changes nothing. + let replay = service + .answer_review_ask( + &fixture.producer, + request_id, + ask_id, + answer(answered_at), + "a-1", + ) + .await + .expect("replay"); + assert_eq!(replay, answered); + // A second answer under another key cannot reopen or redo it. + assert!(matches!( + service + .answer_review_ask( + &fixture.producer, + request_id, + ask_id, + answer(now_micros()), + "a-2" + ) + .await, + Err(ReviewRuntimeError::ReviewAskNotOpen) + )); + assert_eq!( + ask_changes(&fixture, request_id).await, + ["opened", "answered"] + ); + assert_eq!( + service + .review_task(&fixture.reviewer_a, task, None, "") + .await + .expect("task") + .revision, + 4 + ); +} + +#[tokio::test] +async fn deciding_the_task_closes_its_ask_and_clears_the_marker() { + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + let (request_id, task, _) = claimed_for_asks(&fixture, &service, "ask-decide").await; + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .expect("ask"); + service + .decide_review_task( + &fixture.reviewer_a, + task, + ReviewTaskDecisionRequest { + decision: DecisionKind::Approve { + outcome: "approved".into(), + public_reason: None, + }, + }, + None, + "", + 3, + "decide", + ) + .await + .expect("decide"); + assert_eq!(ask_states(&fixture, request_id).await, ["closed"]); + assert_eq!(ask_marker(&fixture, task).await, None); + assert_eq!( + ask_changes(&fixture, request_id).await, + ["opened", "closed"] + ); + // A closed ask cannot be answered. + let read = service + .review_ask(&fixture.producer, request_id, asked.ask.ask_id) + .await + .expect("read closed ask"); + assert_eq!(read.state, registry_casework_core::ReviewAskState::Closed); + assert!(read.closed_at.is_some()); + assert!(matches!( + service + .answer_review_ask( + &fixture.producer, + request_id, + asked.ask.ask_id, + registry_casework_core::ReviewAskAnswer { + subject: read.subject.clone(), + answered_at: now_micros(), + }, + "late" + ) + .await, + Err(ReviewRuntimeError::ReviewAskNotOpen) + )); +} + +#[tokio::test] +async fn settling_or_cancelling_the_request_closes_its_open_ask() { + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "ask-cancel").await; + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .expect("ask"); + service + .cancel_review_request( + &fixture.producer, + request_id, + ReviewCancelRequest { + subject: create.subject.clone(), + reason: "withdrawn".to_owned(), + }, + "cancel", + ) + .await + .expect("cancel"); + assert_eq!(ask_states(&fixture, request_id).await, ["closed"]); + assert_eq!(ask_marker(&fixture, task).await, None); + assert_eq!( + ask_changes(&fixture, request_id).await, + ["opened", "closed"] + ); + + // A rejection settles the request and closes the ask the same way. + let (request_id, task, _) = claimed_for_asks(&fixture, &service, "ask-reject").await; + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask-2", + ) + .await + .expect("ask"); + service + .decide_review_task( + &fixture.reviewer_a, + task, + ReviewTaskDecisionRequest { + decision: DecisionKind::Reject { + outcome: "incorrect".to_owned(), + public_reason: Some("The record could not be matched.".to_owned()), + reason: Some("private reason".to_owned()), + result: Some(json!({"correction": "bounded correction"})), + }, + }, + None, + "", + 3, + "reject", + ) + .await + .expect("reject settles"); + assert_eq!(ask_states(&fixture, request_id).await, ["closed"]); + assert_eq!(ask_marker(&fixture, task).await, None); +} + +#[tokio::test] +async fn a_released_task_keeps_its_ask_and_marker_for_the_next_holder() { + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + let (request_id, task, _) = claimed_for_asks(&fixture, &service, "ask-release").await; + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .expect("ask"); + let released = service + .release_review_task(&fixture.reviewer_a, task, 3, "release") + .await + .expect("release"); + assert_eq!( + released.marker, + Some(registry_casework_core::ReviewTaskMarker::Waiting) + ); + assert_eq!(ask_states(&fixture, request_id).await, ["open"]); + let claimed = service + .claim_review_task(&fixture.reviewer_b, task, None, "", 4, "claim-b") + .await + .expect("next holder claims"); + assert_eq!( + claimed.marker, + Some(registry_casework_core::ReviewTaskMarker::Waiting) + ); + let context = service + .review_task_context(&fixture.reviewer_b, task, None, "") + .await + .expect("context"); + assert_eq!(context.asks.len(), 1); +} + +#[tokio::test] +async fn staff_list_tasks_that_wait_for_an_applicant_or_were_answered() { + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "ask-list").await; + let (_, plain_task, _) = claimed_for_asks(&fixture, &service, "ask-list-plain").await; + let list = |marker: Option| { + let service = &service; + let reviewer = &fixture.reviewer_a; + async move { + service + .review_staffing_tasks( + reviewer, + None, + "", + ReviewStaffingQuery { + marker, + ..Default::default() + }, + ) + .await + .expect("list tasks") + .items + } + }; + use registry_casework_core::ReviewTaskMarker::{Answered, Waiting}; + assert!(list(Some(Waiting)).await.is_empty()); + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .expect("ask"); + let waiting = list(Some(Waiting)).await; + assert_eq!(waiting.len(), 1); + assert_eq!(waiting[0].task_id, task); + assert_eq!(waiting[0].marker, Some(Waiting)); + assert!(list(Some(Answered)).await.is_empty()); + assert_eq!(list(None).await.len(), 2); + let ask_id = fixture + .database + .query_one( + "SELECT ask_id FROM casework_review_asks WHERE request_id=$1", + &[&request_id], + ) + .await + .expect("ask") + .get::<_, Uuid>(0); + service + .answer_review_ask( + &fixture.producer, + request_id, + ask_id, + registry_casework_core::ReviewAskAnswer { + subject: create.subject.clone(), + answered_at: now_micros(), + }, + "answer", + ) + .await + .expect("answer"); + assert!(list(Some(Waiting)).await.is_empty()); + let answered = list(Some(Answered)).await; + assert_eq!(answered.len(), 1); + assert_eq!(answered[0].task_id, task); + assert_ne!(answered[0].task_id, plain_task); + assert_eq!( + list(None) + .await + .iter() + .filter(|item| item.marker.is_none()) + .count(), + 1 + ); +} + +#[tokio::test] +async fn ask_rows_and_events_leave_with_the_expired_review() { + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "ask-erase").await; + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .expect("ask"); + service + .cancel_review_request( + &fixture.producer, + request_id, + ReviewCancelRequest { + subject: create.subject, + reason: "withdrawn".to_owned(), + }, + "cancel", + ) + .await + .expect("cancel"); + fixture + .database + .execute( + "UPDATE casework_review_requests + SET terminal_at=now()-interval '2 days', + result_available_until=now()-interval '1 day' WHERE request_id=$1", + &[&request_id], + ) + .await + .expect("expire the result"); + assert!( + service + .review_ask_feed(&fixture.producer, None, 10) + .await + .expect("feed") + .items + .is_empty(), + "an expired review leaves the feed before erasure runs" + ); + service.erase_expired_reviews().await.expect("erase"); + for table in ["casework_review_asks", "casework_review_ask_events"] { + assert_eq!(count_for_request(&fixture, table, request_id).await, 0); + } +} + +#[tokio::test] +async fn an_ask_event_waits_for_the_producers_feed_lock() { + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + let (request_id, task, _) = claimed_for_asks(&fixture, &service, "ask-lock").await; + let producer_id = asks_project(true, true).trusted_producers[0].id.clone(); + // The result feed's per-producer lock, held by another session, as a + // settling review holds it until it commits. + fixture + .database + .query_one( + "SELECT pg_advisory_lock(hashtextextended($1,0))", + &[&producer_id], + ) + .await + .expect("take the feed lock"); + let asking = { + let service = service.clone(); + let reviewer = fixture.reviewer_a.clone(); + tokio::spawn(async move { + service + .ask_applicant(&reviewer, task, ask_request("Why?"), None, "", 2, "ask") + .await + }) + }; + tokio::pin!(asking); + assert!( + tokio::time::timeout(std::time::Duration::from_millis(700), &mut asking) + .await + .is_err(), + "an ask event must not take a feed position while another transaction holds the lock" + ); + assert_eq!(ask_changes(&fixture, request_id).await.len(), 0); + fixture + .database + .query_one( + "SELECT pg_advisory_unlock(hashtextextended($1,0))", + &[&producer_id], + ) + .await + .expect("release the feed lock"); + asking + .await + .expect("ask task") + .expect("the ask completes once the lock is free"); + assert_eq!(ask_changes(&fixture, request_id).await, ["opened"]); +} + +#[tokio::test] +async fn the_marker_filter_applies_on_the_reference_and_subject_paths() { + use registry_casework_core::ReviewTaskMarker::{Answered, Waiting}; + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + let (_, task, create) = claimed_for_asks(&fixture, &service, "ask-reference").await; + let (_, plain_task, _) = claimed_for_asks(&fixture, &service, "ask-reference-plain").await; + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .expect("ask"); + let list = |query: ReviewStaffingQuery| { + let service = &service; + let reviewer = &fixture.reviewer_a; + async move { + service + .review_staffing_tasks(reviewer, None, "", query) + .await + .expect("list tasks") + .items + .into_iter() + .map(|item| item.task_id) + .collect::>() + } + }; + let by_reference = |marker| ReviewStaffingQuery { + marker, + sort: ReviewTaskSort::Reference, + ..Default::default() + }; + assert_eq!(list(by_reference(Some(Waiting))).await, [task]); + assert!(list(by_reference(Some(Answered))).await.is_empty()); + assert_eq!(list(by_reference(None)).await.len(), 2); + assert!(list(by_reference(None)).await.contains(&plain_task)); + let by_subject = |marker| ReviewStaffingQuery { + marker, + subject_source: Some(create.subject.source.clone()), + subject_type: Some(create.subject.subject_type.clone()), + subject_id: Some(create.subject.id.clone()), + subject_version: Some(create.subject.version.clone()), + subject_digest: Some(create.subject.digest.clone()), + ..Default::default() + }; + assert_eq!(list(by_subject(Some(Waiting))).await, [task]); + assert!(list(by_subject(Some(Answered))).await.is_empty()); +} + +#[tokio::test] +async fn an_ask_is_read_and_answered_only_through_its_own_request() { + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + let (request_a, task_a, create_a) = claimed_for_asks(&fixture, &service, "ask-bind-a").await; + let (request_b, _, create_b) = claimed_for_asks(&fixture, &service, "ask-bind-b").await; + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task_a, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .expect("ask on request A"); + let ask_id = asked.ask.ask_id; + // Request B belongs to the same producer, and its own subject is the one + // the producer would bind. + assert!(matches!( + service + .review_ask(&fixture.producer, request_b, ask_id) + .await, + Err(ReviewRuntimeError::NotFound) + )); + let answer = |subject: &SubjectBinding| registry_casework_core::ReviewAskAnswer { + subject: subject.clone(), + answered_at: now_micros(), + }; + assert!(matches!( + service + .answer_review_ask( + &fixture.producer, + request_b, + ask_id, + answer(&create_b.subject), + "answer-through-b" + ) + .await, + Err(ReviewRuntimeError::NotFound) + )); + assert_eq!(ask_states(&fixture, request_a).await, ["open"]); + assert_eq!( + ask_marker(&fixture, task_a).await.as_deref(), + Some("waiting") + ); + + // A replay under the key that answered it does not outlive the binding. + service + .answer_review_ask( + &fixture.producer, + request_a, + ask_id, + answer(&create_a.subject), + "answer-key", + ) + .await + .expect("answer through its own request"); + assert!(matches!( + service + .answer_review_ask( + &fixture.producer, + request_b, + ask_id, + answer(&create_b.subject), + "answer-key" + ) + .await, + Err(ReviewRuntimeError::NotFound) + )); + let replay = service + .answer_review_ask( + &fixture.producer, + request_a, + ask_id, + answer(&create_a.subject), + "answer-key", + ) + .await; + // The same key and a fresh time is a different body: refused, not replayed. + assert!(matches!( + replay, + Err(ReviewRuntimeError::IdempotencyConflict) + )); +} + +#[tokio::test] +async fn the_answer_time_window_ends_five_minutes_after_the_clock() { + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "ask-window").await; + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .expect("ask"); + let answer = |answered_at| registry_casework_core::ReviewAskAnswer { + subject: create.subject.clone(), + answered_at, + }; + let try_answer = |answered_at, key: &'static str| { + let service = &service; + let producer = &fixture.producer; + let ask_id = asked.ask.ask_id; + let answer = answer(answered_at); + async move { + service + .answer_review_ask(producer, request_id, ask_id, answer, key) + .await + } + }; + assert!(matches!( + try_answer(asked.ask.asked_at - TimeDelta::microseconds(1), "before").await, + Err(ReviewRuntimeError::ReviewAskAnswerTimeInvalid) + )); + assert!(matches!( + try_answer( + now_micros() + TimeDelta::minutes(5) + TimeDelta::seconds(1), + "late" + ) + .await, + Err(ReviewRuntimeError::ReviewAskAnswerTimeInvalid) + )); + try_answer(now_micros() + TimeDelta::minutes(5), "edge") + .await + .expect("five minutes ahead of the clock is still accepted"); +} + +#[tokio::test] +async fn a_decision_that_only_records_closes_the_deciding_tasks_ask() { + let fixture = fixture().await; + let mut project = asks_project(true, true); + project.review_policies[0].stages[0].required_approvals = 2; + let service = CaseworkService::new( + fixture.store.clone(), + project, + Vec::>::new(), + ) + .expect("two-approval asks service"); + let (request_id, task, _) = claimed_for_asks(&fixture, &service, "ask-records").await; + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .expect("ask"); + service + .decide_review_task( + &fixture.reviewer_a, + task, + ReviewTaskDecisionRequest { + decision: DecisionKind::Approve { + outcome: "approved".into(), + public_reason: None, + }, + }, + None, + "", + 3, + "approve", + ) + .await + .expect("the first approval is recorded"); + let lifecycle: String = fixture + .database + .query_one( + "SELECT lifecycle FROM casework_review_requests WHERE request_id=$1", + &[&request_id], + ) + .await + .expect("lifecycle") + .get(0); + let stage: i32 = fixture + .database + .query_one( + "SELECT active_stage_index FROM casework_review_requests WHERE request_id=$1", + &[&request_id], + ) + .await + .expect("stage") + .get(0); + assert_eq!((lifecycle.as_str(), stage), ("reviewing", 0)); + assert_eq!(ask_states(&fixture, request_id).await, ["closed"]); + assert_eq!(ask_marker(&fixture, task).await, None); +} + +#[tokio::test] +async fn superseding_a_request_closes_its_open_ask() { + let fixture = fixture().await; + let service = asks_service(&fixture, true, true); + let (request_id, task, create) = claimed_for_asks(&fixture, &service, "ask-supersede").await; + service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + 2, + "ask", + ) + .await + .expect("ask"); + // The same subject and policy at a newer version supersedes the review. + let _ = create; + let mut newer = request("ask-supersede", "ref-ask-supersede"); + newer.subject.version = "2".to_owned(); + newer.subject.digest = ContentDigest::for_bytes(b"ask-supersede-v2"); + let newer = bind_request(&service, newer); + service + .create_review_request(&fixture.producer, newer, "create-newer") + .await + .expect("the newer submission supersedes the first"); + assert_eq!(ask_states(&fixture, request_id).await, ["closed"]); + assert_eq!(ask_marker(&fixture, task).await, None); + assert_eq!( + ask_changes(&fixture, request_id).await, + ["opened", "closed"] + ); +} diff --git a/crates/registry-casework/tests/support/ask_limit.rs b/crates/registry-casework/tests/support/ask_limit.rs new file mode 100644 index 0000000000..ef2342db38 --- /dev/null +++ b/crates/registry-casework/tests/support/ask_limit.rs @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; + +async fn mutation_state(fixture: &Fixture, request: Uuid) -> serde_json::Value { + fixture.database.query_one( + "SELECT jsonb_build_object( + 'request',to_jsonb(r), + 'tasks',(SELECT jsonb_agg(to_jsonb(t) ORDER BY task_id) FROM casework_review_tasks t WHERE request_id=$1), + 'clocks',(SELECT jsonb_agg(to_jsonb(c) ORDER BY clock_occurrence_id) FROM casework_review_clock_occurrences c WHERE request_id=$1), + 'asks',(SELECT count(*) FROM casework_review_asks WHERE request_id=$1), + 'events',(SELECT count(*) FROM casework_review_ask_events WHERE request_id=$1), + 'history',(SELECT count(*) FROM casework_review_history WHERE request_id=$1), + 'idempotency',(SELECT count(*) FROM casework_idempotency WHERE resource LIKE '%' || $1::text || '%' OR resource IN (SELECT 'review-task:' || task_id::text FROM casework_review_tasks WHERE request_id=$1)) + ) FROM casework_review_requests r WHERE request_id=$1", + &[&request]).await.unwrap().get(0) +} + +#[tokio::test] +async fn the_fifty_first_ask_is_refused_before_state_or_clocks_change() { + let fixture = fixture().await; + let service = timed_asks_service(&fixture, true); + let (request, task, create) = claimed_for_asks(&fixture, &service, "ask-limit").await; + let mut revision = 2; + let mut last = None; + for index in 0..50 { + let expected = revision; + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + expected, + &format!("ask-{index}"), + ) + .await + .unwrap(); + revision = asked.task.revision; + service + .answer_review_ask( + &fixture.producer, + request, + asked.ask.ask_id, + ReviewAskAnswer { + subject: create.subject.clone(), + answered_at: asked.ask.asked_at, + }, + &format!("answer-{index}"), + ) + .await + .unwrap(); + revision += 1; + last = Some((expected, asked)); + } + assert_eq!(ask_states(&fixture, request).await.len(), 50); + let before = mutation_state(&fixture, request).await; + assert_eq!(before["clocks"].as_array().unwrap().len(), 1); + assert_eq!(before["clocks"][0]["state"], "running"); + let refused = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("One too many"), + None, + "", + revision, + "ask-51", + ) + .await; + assert!(refused.is_err(), "the fifty-first ask must be refused"); + assert_eq!( + format!("{:?}", refused.unwrap_err()), + "ReviewAskLimitReached" + ); + assert_eq!( + mutation_state(&fixture, request).await, + before, + "a refused ask changes no request, task, clock, feed, history or idempotency state" + ); + let (expected, last) = last.unwrap(); + let replay = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + None, + "", + expected, + "ask-49", + ) + .await + .unwrap(); + assert_eq!( + replay, last, + "the limit does not spend or block an earlier successful key" + ); + assert_eq!(mutation_state(&fixture, request).await, before); + let (_, other, _) = claimed_for_asks(&fixture, &service, "another-ask-limit").await; + assert!( + service + .ask_applicant( + &fixture.reviewer_a, + other, + ask_request("First ask"), + None, + "", + 2, + "another-first" + ) + .await + .is_ok(), + "the cap belongs to the request" + ); +} diff --git a/crates/registry-casework/tests/support/ask_limit_http.rs b/crates/registry-casework/tests/support/ask_limit_http.rs new file mode 100644 index 0000000000..15eb609cbf --- /dev/null +++ b/crates/registry-casework/tests/support/ask_limit_http.rs @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; + +#[tokio::test] +async fn the_ask_limit_is_a_conflict_problem_without_changing_the_task() { + let idp = MockIdp::start().await; + let project = asks_http_project(&idp); + let (app, _, _, _, _, _, database) = app_with_project(&idp, project).await; + let mut input = + review_request_for_subject("ask-limit-http", "ask-limit-http-ref", &idp.issuer()); + input.context = ReviewContext::Submitted { + snapshot: json!({"summary":"Ask limit"}), + }; + let (created, task) = create_task(&app, &database, &idp, &input).await; + let reviewer = reviewer_token(&idp); + claim_task_over_http(&app, task, &reviewer, "claim").await; + let ids = (0..50).map(|_| Uuid::new_v4()).collect::>(); + database.execute("INSERT INTO casework_review_asks(ask_id,request_id,task_id,stage_index,text,wants,state,asked_at,asked_by_ref,closed_at) SELECT x,$1,$2,0,'Earlier ask','[]','closed',transaction_timestamp()-interval '1 hour','synthetic-reviewer',transaction_timestamp() FROM unnest($3::uuid[]) x",&[&created.request_id,&task,&ids]).await.unwrap(); + database.execute("UPDATE casework_review_asks SET state='expired',due_at=transaction_timestamp()-interval '1 minute' WHERE ask_id=$1",&[&ids[0]]).await.unwrap(); + let staff = vec![ + ("authorization", format!("Bearer {reviewer}")), + (CASEWORK_PROFILE_HEADER, "staff".into()), + ]; + let uri = format!("/v1/review-tasks/{task}"); + let before = http_json(&app, "GET", uri.clone(), &staff, None).await; + assert_eq!(before.0, StatusCode::OK); + let mut headers = staff.clone(); + headers.extend([ + ("if-match", "\"2\"".into()), + ("idempotency-key", "ask-51".into()), + ]); + let response = http_json( + &app, + "POST", + format!("{uri}/asks"), + &headers, + Some(json!({"text":"Why?","wants":[]})), + ) + .await; + assert_eq!(response.0, StatusCode::CONFLICT); + let problem: Value = serde_json::from_slice(&response.2).unwrap(); + assert_eq!(problem["code"], "review.ask-limit-reached"); + assert_eq!( + problem["type"], + "https://id.registrystack.org/problems/registry-casework/review/ask-limit-reached" + ); + assert_eq!(problem["title"], "Review ask limit reached"); + assert_eq!(problem["detail"],"This review request has reached its limit of 50 asks. Continue the review without opening another ask."); + assert_eq!(http_json(&app, "GET", uri, &staff, None).await.2, before.2); + assert_eq!( + database + .query_one( + "SELECT count(*) FROM casework_review_asks WHERE request_id=$1", + &[&created.request_id] + ) + .await + .unwrap() + .get::<_, i64>(0), + 50 + ); +} diff --git a/crates/registry-casework/tests/support/source_ask_answers.rs b/crates/registry-casework/tests/support/source_ask_answers.rs new file mode 100644 index 0000000000..a51b9bfe5b --- /dev/null +++ b/crates/registry-casework/tests/support/source_ask_answers.rs @@ -0,0 +1,255 @@ +use super::*; + +struct AnswerSource { + inner: ReviewSource, + answers: Arc>, + reads: Arc, + requests_answers: Arc>>, +} + +#[async_trait] +impl ReviewContextProvider for AnswerSource { + fn provider_id(&self) -> &str { + self.inner.provider_id() + } + fn capabilities(&self) -> &[ReviewContextCapability] { + self.inner.capabilities() + } + async fn human_display( + &self, + request: HumanDisplayRequest<'_>, + ) -> Result { + self.reads.fetch_add(1, Ordering::SeqCst); + self.requests_answers + .lock() + .unwrap() + .push(request.include_answers); + let include_answers = request.include_answers; + let mut value = serde_json::to_value(self.inner.human_display(request).await?) + .map_err(|_| ReviewContextError::Invalid)?; + let answers = self.answers.lock().unwrap().clone(); + if include_answers && !answers.as_object().unwrap().is_empty() { + value["answers"] = answers; + } + serde_json::from_value(value).map_err(|_| ReviewContextError::Invalid) + } + async fn service_status( + &self, + identity: &ReviewContextIdentity, + ) -> Result { + self.inner.service_status(identity).await + } + async fn routing_context( + &self, + request: &ServiceContextRequest, + ) -> Result { + self.inner.routing_context(request).await + } + async fn task_grant_context( + &self, + request: &ServiceContextRequest, + ) -> Result { + self.inner.task_grant_context(request).await + } +} + +#[tokio::test] +async fn source_answers_join_known_asks_live_without_entering_the_display_schema_or_store() { + let fixture = fixture().await; + let mut project = asks_project(true, true); + current_source(&mut project); + let answers = Arc::new(Mutex::new(json!({}))); + let reads = Arc::new(AtomicUsize::new(0)); + let requests_answers = Arc::new(Mutex::new(Vec::new())); + let provider = AnswerSource { + inner: ReviewSource { + revoked: fixture.source_revoked.clone(), + state: fixture.source_state.clone(), + read_blocked: fixture.source_read_blocked.clone(), + read_started: fixture.source_read_started.clone(), + read_continue: fixture.source_read_continue.clone(), + advanced: fixture.source_advanced.clone(), + }, + answers: answers.clone(), + reads: reads.clone(), + requests_answers: requests_answers.clone(), + }; + let service = CaseworkService::new( + fixture.store.clone(), + project, + [Arc::new(provider) as Arc], + ) + .unwrap(); + let mut create = request("source-answers", "reference-source-answers"); + create.context = ReviewContext::CurrentSource { + binding: SourceContextBinding { + reference: "source:answers".into(), + }, + }; + let created = service + .create_review_request( + &fixture.producer, + bind_request(&service, create), + "source-answers-create", + ) + .await + .unwrap(); + let request_id = created.accepted.request_id; + let task = task_id(&fixture, request_id, 0).await; + let held = service + .claim_review_task( + &fixture.reviewer_a, + task, + Some("staff"), + "human-token", + 1, + "source-answers-claim", + ) + .await + .unwrap(); + assert_eq!( + *requests_answers.lock().unwrap(), + vec![false], + "claim preflight must not request applicant answers" + ); + let asked = service + .ask_applicant( + &fixture.reviewer_a, + task, + ask_request("Why?"), + Some("staff"), + "human-token", + held.revision, + "source-answers-ask", + ) + .await + .unwrap(); + assert_eq!( + *requests_answers.lock().unwrap(), + vec![false, false], + "ask preflight must not request applicant answers" + ); + let answer = json!({"text":"synthetic-answer-live-only","documents":[{ + "id":"cited-file","sha256":"a".repeat(64),"contentType":"text/plain","byteSize":7, + "download":{"method":"GET","operation":"get-review-context","accessProfile":"staff","path":"/files/cited"} + }],"answeredAt":asked.ask.asked_at}); + *answers.lock().unwrap() = json!({(asked.ask.ask_id.to_string()):answer, + (Uuid::new_v4().to_string()):{"text":"unknown-answer-must-not-appear","documents":[],"answeredAt":asked.ask.asked_at}}); + let captured = CapturedLogs::default(); + let subscriber = tracing_subscriber::fmt() + .json() + .with_writer(captured.clone()) + .finish(); + let context = service + .review_task_context(&fixture.reviewer_a, task, Some("staff"), "human-token") + .with_subscriber(subscriber) + .await; + assert!( + context.is_ok(), + "intrinsic answers bypass the authored display schema: {:?}", + context.err() + ); + let value = serde_json::to_value(context.unwrap()).unwrap(); + assert_eq!( + *requests_answers.lock().unwrap(), + vec![false, false, true], + "only the displayed context requests applicant answers" + ); + assert_eq!(value["asks"][0]["answer"], answer); + assert!(!value.to_string().contains("unknown-answer-must-not-appear")); + let logs = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap(); + assert!( + logs.contains("\"dropped_answers\":1"), + "unknown answers are counted without their content: {logs}" + ); + assert!(!logs.contains("unknown-answer-must-not-appear")); + let mut inconsistent = answer.clone(); + inconsistent["answeredAt"] = json!(asked.ask.asked_at - chrono::Duration::seconds(1)); + *answers.lock().unwrap() = json!({(asked.ask.ask_id.to_string()):inconsistent}); + let captured = CapturedLogs::default(); + let subscriber = tracing_subscriber::fmt() + .json() + .with_writer(captured.clone()) + .finish(); + let partial = service + .review_task_context(&fixture.reviewer_a, task, Some("staff"), "human-token") + .with_subscriber(subscriber) + .await + .unwrap(); + let partial = serde_json::to_value(partial).unwrap(); + assert_eq!( + partial["context"], value["context"], + "one bad answer must not hide the authored fields" + ); + assert!(partial["asks"][0].get("answer").is_none()); + let logs = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap(); + assert!(logs.contains("\"dropped_answers\":1"), "{logs}"); + assert!(!logs.contains("synthetic-answer-live-only")); + for table in [ + "casework_review_requests", + "casework_review_tasks", + "casework_review_history", + ] { + let query = format!("SELECT COALESCE(bool_or(to_jsonb(r)::text LIKE '%synthetic-answer-live-only%'),false) FROM {table} r WHERE request_id=$1"); + let retained: bool = fixture + .database + .query_one(&query, &[&request_id]) + .await + .unwrap() + .get(0); + assert!(!retained, "source answer text must not enter {table}"); + } + let before = reads.load(Ordering::SeqCst); + *answers.lock().unwrap() = json!({}); + let refreshed = service + .review_task_context(&fixture.reviewer_a, task, Some("staff"), "human-token") + .await + .unwrap(); + assert!(serde_json::to_value(refreshed).unwrap()["asks"][0] + .get("answer") + .is_none()); + assert_eq!(reads.load(Ordering::SeqCst), before + 1); + *answers.lock().unwrap() = json!({(asked.ask.ask_id.to_string()):answer}); + let inbox = service + .review_tasks( + &fixture.reviewer_a, + Some("staff"), + "human-token", + None, + None, + 25, + ) + .await + .unwrap(); + assert_eq!(inbox.items.len(), 1); + let inbox = serde_json::to_value(inbox).unwrap(); + assert!(inbox["items"][0].get("asks").is_none()); + assert!(!inbox.to_string().contains("synthetic-answer-live-only")); + assert_eq!( + requests_answers.lock().unwrap().last(), + Some(&false), + "inbox hydration must not request answers" + ); + service + .decide_review_task( + &fixture.reviewer_a, + task, + ReviewTaskDecisionRequest { + decision: DecisionKind::Approve { + outcome: "approved".into(), + public_reason: None, + }, + }, + Some("staff"), + "human-token", + asked.task.revision, + "source-answers-decide", + ) + .await + .unwrap(); + assert_eq!( + requests_answers.lock().unwrap().last(), + Some(&false), + "decide preflight must not request answers" + ); +} diff --git a/crates/registry-caseworkctl/src/report.rs b/crates/registry-caseworkctl/src/report.rs index 121a67c7fa..cab261c989 100644 --- a/crates/registry-caseworkctl/src/report.rs +++ b/crates/registry-caseworkctl/src/report.rs @@ -280,6 +280,8 @@ payload!(ExplainStage { #[serde(default, skip_serializing_if = "Vec::is_empty")] outcomes: Vec, negative_decisions: registry_casework_core::ReviewNegativeDecisionMode, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + asks: bool, exclude_initiator: bool, exclude_previous_stage_reviewers: bool }); @@ -301,6 +303,7 @@ impl ExplainStage { .map(|outcome| outcome.id.clone()) .collect(), negative_decisions: stage.negative_decisions, + asks: stage.asks.is_some(), exclude_initiator: stage.exclude_initiator, exclude_previous_stage_reviewers: stage.exclude_previous_stage_reviewers, } diff --git a/crates/registry-review-client/README.md b/crates/registry-review-client/README.md index 113fcb0138..cdba62c66b 100644 --- a/crates/registry-review-client/README.md +++ b/crates/registry-review-client/README.md @@ -3,7 +3,8 @@ `registry-review-client` is the bounded, runtime-free HTTP client for the producer-facing review handoff contract. It creates or recovers review requests, reads their bindings, retrieves terminal results, pages the -requester result feed, and cancels unfinished requests. +requester result feed, cancels unfinished requests, and pages, reads and +answers reviewer asks. The producer selects an explicitly granted provider profile with `Registry-Review-Profile`. Failures accept bounded, well-formed opaque provider problem URIs and @@ -38,3 +39,17 @@ failure grants permission to retry with a fresh idempotency key. Authentication is supplied for each call. The client does not retain credentials, retry mutations, follow redirects, use ambient proxies, evaluate review policy, operate reviewer tasks, or apply a source-system result. + +`ask_feed`, `ask` and `answer_ask` follow the result feed and result read where +they can. The feed refuses nil identifiers and a cursor that is not its final +entry, and a cursor past retention surfaces as a 410 `Problem`. `ask` and +`answer_ask` take the accepted request binding, as the result read and cancel +do, and refuse a response whose request, ask or subject differs from it. +`answer_ask` posts only the subject binding and answer time with an +idempotency key, and refuses an answer for another subject before any request. +Its typed outcomes are `Answered`, `ConcealedOrUnknown` for an empty 404, and +`NotOpen` for a 409 whose problem code is `review.ask-not-open`. Any other 404 +or 409, including a problem document, is a `Problem` error. A success must be +the same ask, answered, with the `answeredAt` that was sent. None of them +retries. See the protocol README for the rules a producer follows when it +consumes the feed. diff --git a/crates/registry-review-client/src/client.rs b/crates/registry-review-client/src/client.rs index 45d3ffa523..f73a0e6632 100644 --- a/crates/registry-review-client/src/client.rs +++ b/crates/registry-review-client/src/client.rs @@ -9,12 +9,14 @@ use registry_platform_httputil::{ read_bounded, url::append_path_segments, validate_response_headers_without_peer_policy, }; use registry_review_protocol::{ - review_cancel_path, review_request_path, review_result_path, ReviewCancelRequest, - ReviewCancelResponse, ReviewCreateRequest, ReviewProgressCode, ReviewRequestAccepted, - ReviewRequestLifecycle, ReviewRequestView, ReviewResult, ReviewResultFeedPage, - ReviewResultStatus, SubmissionDigest, REVIEW_PRODUCER_HEADER, REVIEW_PROFILE_HEADER, - REVIEW_REQUESTS_PATH, REVIEW_RESULTS_FEED_PATH, REVIEW_VALIDATION_PATH_HEADER, - REVIEW_VALIDATION_REASON_HEADER, + review_ask_answer_path, review_ask_path, review_cancel_path, review_request_path, + review_result_path, ReviewAsk, ReviewAskAnswer, ReviewAskFeedPage, ReviewAskState, + ReviewCancelRequest, ReviewCancelResponse, ReviewCreateRequest, ReviewProgressCode, + ReviewRequestAccepted, ReviewRequestLifecycle, ReviewRequestView, ReviewResult, + ReviewResultFeedPage, ReviewResultStatus, SubjectBinding, SubmissionDigest, + REVIEW_ASKS_FEED_PATH, REVIEW_ASK_NOT_OPEN_PROBLEM, REVIEW_PRODUCER_HEADER, + REVIEW_PROFILE_HEADER, REVIEW_REQUESTS_PATH, REVIEW_RESULTS_FEED_PATH, + REVIEW_VALIDATION_PATH_HEADER, REVIEW_VALIDATION_REASON_HEADER, }; use reqwest::header::{HeaderName, HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_TYPE}; use reqwest::{RequestBuilder, Response, StatusCode, Url}; @@ -22,11 +24,11 @@ use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::Value; use uuid::Uuid; -use crate::model::check_result_page; +use crate::model::{check_ask_page, check_result_page}; use crate::{ - ReviewAuth, ReviewClientConfig, ReviewClientError, ReviewComplete, ReviewProblem, - ReviewProblemCode, ReviewProtocolFailure, ReviewResultResponse, ReviewResultsQuery, - ReviewValidationError, ReviewValidationReason, + ReviewAskAnswerResponse, ReviewAskResponse, ReviewAuth, ReviewClientConfig, ReviewClientError, + ReviewComplete, ReviewProblem, ReviewProblemCode, ReviewProtocolFailure, ReviewResultResponse, + ReviewResultsQuery, ReviewValidationError, ReviewValidationReason, }; const JSON_MEDIA_TYPE: &str = "application/json"; @@ -194,6 +196,64 @@ impl ClientResponse for ReviewResultFeedPage { } } +#[derive(Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "kebab-case")] +enum ReviewAskWantWire { + Answer {}, + Document {}, +} + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct ReviewAskWire { + ask_id: Uuid, + request_id: Uuid, + subject: SubjectBindingWire, + text: String, + wants: Vec, + asked_at: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + due_at: Option, + state: ReviewAskState, + #[serde(default, skip_serializing_if = "Option::is_none")] + answered_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + closed_at: Option, +} + +impl ClientResponse for ReviewAsk { + type Wire = ReviewAskWire; + + fn from_wire(wire: Self::Wire) -> Result { + validate_wire(wire) + } +} + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct ReviewAskFeedEntryWire { + event_id: Uuid, + request_id: Uuid, + ask_id: Uuid, + changed_at: String, +} + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct ReviewAskFeedPageWire { + items: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + next_cursor: Option, +} + +impl ClientResponse for ReviewAskFeedPage { + type Wire = ReviewAskFeedPageWire; + + fn from_wire(wire: Self::Wire) -> Result { + validate_wire(wire) + } +} + #[derive(Deserialize, Serialize)] #[serde( tag = "outcome", @@ -602,6 +662,201 @@ impl ReviewClient { Ok(complete) } + /// Pages the provider's ask feed. An entry only announces that an ask + /// changed; the caller reads the ask next. A cursor past retention is + /// refused by the provider and surfaces as a `Problem` with status 410, + /// exactly as it does for the result feed. + pub async fn ask_feed( + &self, + auth: ReviewAuth<'_>, + cursor: Option, + limit: Option, + ) -> Result, ReviewClientError> { + let query = ReviewResultsQuery { cursor, limit }; + query.check().map_err(ReviewClientError::invalid_request)?; + let url = self.url_from_constant(REVIEW_ASKS_FEED_PATH)?; + let request = self.authorized(self.http.get(url).query(&query), &auth)?; + let complete = self.send_json(request, StatusCode::OK).await?; + check_ask_page(&complete.value).map_err(|_| { + protocol( + StatusCode::OK, + ReviewProtocolFailure::Body, + Some(complete.trace_id.clone()), + ) + })?; + Ok(complete) + } + + /// Reads one ask of the accepted request. The response must be the + /// requested ask for the accepted subject. + pub async fn ask( + &self, + auth: ReviewAuth<'_>, + expected: &ReviewRequestAccepted, + ask_id: Uuid, + ) -> Result { + let request_id = expected.request_id; + let expected_subject = &expected.subject; + check_ask_input(request_id, ask_id, expected_subject)?; + let url = self.url_from_constant(&review_ask_path(request_id, ask_id))?; + let response = self + .send(self.authorized(self.http.get(url), &auth)?) + .await?; + let status = response.status(); + let trace_id = response_trace(status, response.headers())?; + match status { + StatusCode::OK => { + let ask = self + .read_ask( + response, + status, + &trace_id, + request_id, + ask_id, + expected_subject, + ) + .await?; + Ok(ReviewAskResponse::Available(Box::new(ReviewComplete { + value: ask, + trace_id, + }))) + } + StatusCode::NOT_FOUND => { + self.require_bare_not_found(response, status, &trace_id) + .await?; + Ok(ReviewAskResponse::ConcealedOrUnknown { trace_id }) + } + _ => Err(self.problem_or_status(response, Some(trace_id)).await), + } + } + + /// Reports that the subject's owner answered an ask. The body carries + /// only the subject binding and the answer time. The client performs one + /// exchange: 404 is a concealed or unknown ask, 409 an ask that is not + /// open, and a success must return the same ask, answered. + pub async fn answer_ask( + &self, + auth: ReviewAuth<'_>, + idempotency_key: &str, + expected: &ReviewRequestAccepted, + ask_id: Uuid, + answer: &ReviewAskAnswer, + ) -> Result { + let request_id = expected.request_id; + check_ask_input(request_id, ask_id, &expected.subject)?; + if answer.subject != expected.subject { + return Err(ReviewClientError::invalid_request( + "the ask answer subject differs from the accepted request", + )); + } + answer + .check() + .map_err(|_| ReviewClientError::invalid_request("the ask answer is invalid"))?; + validate_idempotency_key(idempotency_key)?; + let key = HeaderValue::from_str(idempotency_key) + .map_err(|_| ReviewClientError::invalid_request("the idempotency key is invalid"))?; + let url = self.url_from_constant(&review_ask_answer_path(request_id, ask_id))?; + let request = self + .authorized(self.http.post(url).json(answer), &auth)? + .header(HeaderName::from_static(IDEMPOTENCY_KEY_HEADER), key); + let response = self.send(request).await?; + let status = response.status(); + let trace_id = response_trace(status, response.headers())?; + match status { + StatusCode::OK => { + let ask = self + .read_ask( + response, + status, + &trace_id, + request_id, + ask_id, + &answer.subject, + ) + .await?; + if ask.state != ReviewAskState::Answered + || ask.answered_at != Some(answer.answered_at) + { + return Err(protocol( + status, + ReviewProtocolFailure::Body, + Some(trace_id), + )); + } + Ok(ReviewAskAnswerResponse::Answered(Box::new( + ReviewComplete { + value: ask, + trace_id, + }, + ))) + } + StatusCode::NOT_FOUND => { + self.require_bare_not_found(response, status, &trace_id) + .await?; + Ok(ReviewAskAnswerResponse::ConcealedOrUnknown { trace_id }) + } + StatusCode::CONFLICT => match self + .problem_or_status(response, Some(trace_id.clone())) + .await + { + ReviewClientError::Problem { problem, .. } + if problem.code.as_str() == REVIEW_ASK_NOT_OPEN_PROBLEM => + { + Ok(ReviewAskAnswerResponse::NotOpen { trace_id }) + } + error => Err(error), + }, + _ => Err(self.problem_or_status(response, Some(trace_id)).await), + } + } + + async fn read_ask( + &self, + response: Response, + status: StatusCode, + trace_id: &str, + request_id: Uuid, + ask_id: Uuid, + expected_subject: &SubjectBinding, + ) -> Result { + if !exact_media_type(response.headers(), JSON_MEDIA_TYPE) { + return Err(protocol( + status, + ReviewProtocolFailure::MediaType, + Some(trace_id.to_owned()), + )); + } + let ask: ReviewAsk = self.read_json(response, status, trace_id).await?; + let bound = ask.check().is_ok() + && ask.request_id == request_id + && ask.ask_id == ask_id + && ask.subject == *expected_subject; + if !bound { + return Err(protocol( + status, + ReviewProtocolFailure::Body, + Some(trace_id.to_owned()), + )); + } + Ok(ask) + } + + /// Accepts a 404 only as a bare, empty response, as the result read does. + /// A 404 problem document, such as a route miss, stays a `Problem`. + async fn require_bare_not_found( + &self, + response: Response, + status: StatusCode, + trace_id: &str, + ) -> Result<(), ReviewClientError> { + if response.headers().contains_key(CONTENT_TYPE) { + return Err(self + .problem_or_status(response, Some(trace_id.to_owned())) + .await); + } + self.require_empty(response, status, trace_id).await + } + fn authorized( &self, request: RequestBuilder, @@ -943,6 +1198,21 @@ fn check_expected_request(expected: &ReviewRequestAccepted) -> Result<(), Review }) } +fn check_ask_input( + request_id: Uuid, + ask_id: Uuid, + subject: &SubjectBinding, +) -> Result<(), ReviewClientError> { + if request_id.is_nil() || ask_id.is_nil() { + return Err(ReviewClientError::invalid_request( + "the ask identifiers are invalid", + )); + } + subject + .check() + .map_err(|_| ReviewClientError::invalid_request("the ask subject binding is invalid")) +} + fn validate_idempotency_key(value: &str) -> Result<(), ReviewClientError> { if value.is_empty() || value.len() > MAXIMUM_IDEMPOTENCY_KEY_BYTES diff --git a/crates/registry-review-client/src/error.rs b/crates/registry-review-client/src/error.rs index 18eb9bc044..ce72bfce00 100644 --- a/crates/registry-review-client/src/error.rs +++ b/crates/registry-review-client/src/error.rs @@ -169,7 +169,7 @@ impl ReviewClientError { Self::InvalidRequest { reason } } - /// Classify a create or cancellation failure without guessing whether the + /// Classify a create, cancellation or ask answer failure without guessing whether the /// service committed a mutation before the failure became observable. #[must_use] pub fn mutation_class(&self) -> ReviewMutationErrorClass { diff --git a/crates/registry-review-client/src/lib.rs b/crates/registry-review-client/src/lib.rs index 7c07cf3ec0..a5da742653 100644 --- a/crates/registry-review-client/src/lib.rs +++ b/crates/registry-review-client/src/lib.rs @@ -15,16 +15,19 @@ pub use error::{ ReviewProtocolFailure, ReviewValidationError, ReviewValidationReason, }; pub use model::{ - ReviewAuth, ReviewComplete, ReviewResultObservation, ReviewResultResponse, ReviewResultsQuery, + ReviewAskAnswerResponse, ReviewAskResponse, ReviewAuth, ReviewComplete, + ReviewResultObservation, ReviewResultResponse, ReviewResultsQuery, }; pub use registry_platform_httputil::client::BearerToken; pub use registry_review_protocol::{ submission_digest, ContentDigest, HumanIdentity, PolicyBinding, PolicySelection, ProtocolError, - ReviewCancelRequest, ReviewCancelResponse, ReviewCompletion, ReviewCompletionType, - ReviewContext, ReviewCreateRequest, ReviewProgressCode, ReviewRequestAccepted, - ReviewRequestLifecycle, ReviewRequestView, ReviewResult, ReviewResultFeedEntry, - ReviewResultFeedPage, ReviewResultLookup, ReviewResultStatus, SourceContextBinding, - SubjectBinding, SubmissionDigest, REVIEW_PRODUCER_HEADER, REVIEW_PROFILE_HEADER, - REVIEW_VALIDATION_PATH_HEADER, REVIEW_VALIDATION_REASON_HEADER, + ReviewAsk, ReviewAskAnswer, ReviewAskFeedEntry, ReviewAskFeedPage, ReviewAskState, + ReviewAskWant, ReviewCancelRequest, ReviewCancelResponse, ReviewCompletion, + ReviewCompletionType, ReviewContext, ReviewCreateRequest, ReviewProgressCode, + ReviewRequestAccepted, ReviewRequestLifecycle, ReviewRequestView, ReviewResult, + ReviewResultFeedEntry, ReviewResultFeedPage, ReviewResultLookup, ReviewResultStatus, + SourceContextBinding, SubjectBinding, SubmissionDigest, REVIEW_ASK_NOT_OPEN_PROBLEM, + REVIEW_PRODUCER_HEADER, REVIEW_PROFILE_HEADER, REVIEW_VALIDATION_PATH_HEADER, + REVIEW_VALIDATION_REASON_HEADER, }; pub use uuid::Uuid; diff --git a/crates/registry-review-client/src/model.rs b/crates/registry-review-client/src/model.rs index 31d325199a..1a1adf7fbd 100644 --- a/crates/registry-review-client/src/model.rs +++ b/crates/registry-review-client/src/model.rs @@ -1,5 +1,7 @@ use registry_platform_httputil::client::BearerToken; -use registry_review_protocol::{ReviewResult, ReviewResultFeedPage, ReviewResultLookup}; +use registry_review_protocol::{ + ReviewAsk, ReviewAskFeedPage, ReviewResult, ReviewResultFeedPage, ReviewResultLookup, +}; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -93,6 +95,28 @@ impl ReviewResultResponse { } } +/// The outcomes of reading one ask. A request or ask the caller may not see +/// is indistinguishable from one that does not exist. +#[derive(Clone, Debug, PartialEq)] +pub enum ReviewAskResponse { + Available(Box>), + ConcealedOrUnknown { trace_id: String }, +} + +/// The outcomes of reporting an ask as answered. +#[derive(Clone, Debug, PartialEq)] +pub enum ReviewAskAnswerResponse { + Answered(Box>), + /// The request or ask is concealed from this producer or unknown. + ConcealedOrUnknown { + trace_id: String, + }, + /// The ask is not open: already answered, expired or closed. + NotOpen { + trace_id: String, + }, +} + #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct ReviewResultsQuery { @@ -143,6 +167,30 @@ pub(crate) fn check_result_page(page: &ReviewResultFeedPage) -> Result<(), &'sta Ok(()) } +pub(crate) fn check_ask_page(page: &ReviewAskFeedPage) -> Result<(), &'static str> { + if page.items.len() > MAXIMUM_PAGE_SIZE { + return Err("the ask page contains too many entries"); + } + if page + .items + .iter() + .any(|entry| entry.event_id.is_nil() || entry.request_id.is_nil() || entry.ask_id.is_nil()) + { + return Err("the ask page contains a nil correlation identifier"); + } + // As for the result feed, a continuation names the final returned entry. + if let Some(cursor) = page.next_cursor { + if page + .items + .last() + .is_none_or(|entry| entry.event_id != cursor) + { + return Err("the ask page cursor does not match its final entry"); + } + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/registry-review-client/tests/http_boundary.rs b/crates/registry-review-client/tests/http_boundary.rs index 65f248d618..bf5f8b47fc 100644 --- a/crates/registry-review-client/tests/http_boundary.rs +++ b/crates/registry-review-client/tests/http_boundary.rs @@ -9,11 +9,12 @@ use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, Request, Response, use axum::routing::{get, post}; use axum::Router; use registry_review_client::{ - BearerToken, ContentDigest, ReviewAuth, ReviewCancelRequest, ReviewClient, ReviewClientConfig, + BearerToken, ContentDigest, ReviewAskAnswer, ReviewAskAnswerResponse, ReviewAskResponse, + ReviewAskState, ReviewAuth, ReviewCancelRequest, ReviewClient, ReviewClientConfig, ReviewClientError, ReviewContext, ReviewCreateRequest, ReviewMutationErrorClass, ReviewProgressCode, ReviewProtocolFailure, ReviewRequestAccepted, ReviewResultLookup, ReviewResultResponse, ReviewResultsQuery, ReviewValidationReason, SourceContextBinding, - SubjectBinding, Uuid, + SubjectBinding, Uuid, REVIEW_ASK_NOT_OPEN_PROBLEM, }; use serde_json::json; use url::Url; @@ -1677,3 +1678,866 @@ async fn same_producer_metadata_still_requires_the_exact_original_digest() { server.abort(); } } + +fn ask_json(request_id: Uuid, ask_id: Uuid) -> serde_json::Value { + json!({ + "askId": ask_id, + "requestId": request_id, + "subject": serde_json::to_value(subject()).expect("subject fixture"), + "text": "Please send the signed form.", + "wants": [{"kind": "answer"}, {"kind": "document"}], + "askedAt": "2026-11-27T01:00:00Z", + "dueAt": "2026-12-01T00:00:00Z", + "state": "open" + }) +} + +fn answered_ask_json(request_id: Uuid, ask_id: Uuid) -> serde_json::Value { + let mut ask = ask_json(request_id, ask_id); + ask["state"] = json!("answered"); + ask["answeredAt"] = json!("2026-11-27T02:00:00Z"); + ask +} + +fn ask_answer() -> ReviewAskAnswer { + serde_json::from_value(json!({ + "subject": serde_json::to_value(subject()).expect("subject fixture"), + "answeredAt": "2026-11-27T02:00:00Z" + })) + .expect("answer fixture") +} + +fn problem_with(status: StatusCode, code: &str) -> Response { + let value = json!({ + "type": format!("https://id.registrystack.org/problems/registry-casework/{code}"), + "title": "Refused", + "status": status.as_u16(), + "detail": "The ask call was refused.", + "code": code, + "traceId": "0123456789abcdef0123456789abcdef" + }); + Response::builder() + .status(status) + .header("content-type", "application/problem+json") + .header("traceparent", TRACEPARENT) + .body(Body::from(value.to_string())) + .expect("fixture response") +} + +fn raw_response(status: StatusCode, content_type: Option<&str>, body: &str) -> Response { + let mut builder = Response::builder() + .status(status) + .header("traceparent", TRACEPARENT); + if let Some(content_type) = content_type { + builder = builder.header("content-type", content_type); + } + builder + .body(Body::from(body.to_owned())) + .expect("fixture response") +} + +/// A problem document with a chosen `status` member and trace id. +fn problem_document(status: StatusCode, code: &str, member: u16, trace_id: &str) -> Response { + let value = json!({ + "type": format!("https://id.registrystack.org/problems/registry-casework/{code}"), + "title": "Refused", + "status": member, + "detail": "The ask call was refused.", + "code": code, + "traceId": trace_id + }); + raw_response(status, Some("application/problem+json"), &value.to_string()) +} + +async fn capture_ask_feed( + State(observations): State, + request: Request, +) -> Response { + capture(&observations, &request); + let mut page = json!({ + "items": [{ + "eventId": Uuid::from_u128(8), + "requestId": Uuid::from_u128(7), + "askId": Uuid::from_u128(5), + "changedAt": "2026-11-27T01:00:00Z", + "futureEntryMember": true + }], + "nextCursor": Uuid::from_u128(8), + "futurePageMember": {"safeToIgnore": true} + }); + page["items"][0]["futureEntryMember"] = json!(true); + json_response(StatusCode::OK, page) +} + +async fn capture_ask( + State(observations): State, + Path((request_id, ask_id)): Path<(Uuid, Uuid)>, + request: Request, +) -> Response { + capture(&observations, &request); + let mut ask = ask_json(request_id, ask_id); + ask["futureAskMember"] = json!({"safeToIgnore": true}); + ask["subject"]["futureSubjectMember"] = json!(true); + json_response(StatusCode::OK, ask) +} + +async fn capture_answer( + State(observations): State, + Path((request_id, ask_id)): Path<(Uuid, Uuid)>, + request: Request, +) -> Response { + capture(&observations, &request); + json_response(StatusCode::OK, answered_ask_json(request_id, ask_id)) +} + +#[tokio::test] +async fn ask_calls_use_the_review_routes_with_the_producer_credential() { + let observations = Arc::new(Mutex::new(Vec::new())); + let app = Router::new() + .route("/v1/review-asks", get(capture_ask_feed)) + .route("/v1/review-requests/{id}/asks/{ask}", get(capture_ask)) + .route( + "/v1/review-requests/{id}/asks/{ask}/answer", + post(capture_answer), + ) + .with_state(observations.clone()); + let (client, server) = serve(app).await; + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let (request_id, ask_id) = (Uuid::from_u128(7), Uuid::from_u128(5)); + + let page = client + .ask_feed( + ReviewAuth::new(&token, "producer"), + Some(Uuid::from_u128(4)), + Some(25), + ) + .await + .expect("ask feed"); + assert_eq!(page.value.items[0].ask_id, ask_id); + assert_eq!(page.value.next_cursor, Some(Uuid::from_u128(8))); + + let ReviewAskResponse::Available(ask) = client + .ask( + ReviewAuth::new(&token, "producer"), + &expected_binding(request_id), + ask_id, + ) + .await + .expect("ask read") + else { + panic!("the ask is available"); + }; + assert_eq!(ask.value.state, ReviewAskState::Open); + + let ReviewAskAnswerResponse::Answered(answered) = client + .answer_ask( + ReviewAuth::new(&token, "producer"), + "answer-5", + &expected_binding(request_id), + ask_id, + &ask_answer(), + ) + .await + .expect("answer") + else { + panic!("the ask is answered"); + }; + assert_eq!(answered.value.state, ReviewAskState::Answered); + + let observations = observations.lock().expect("observations"); + assert_eq!(observations.len(), 3); + for (_, _, headers) in observations.iter() { + assert_eq!(headers["registry-review-profile"], "producer"); + assert_eq!(headers["authorization"], "Bearer one-call-secret"); + } + assert_eq!(observations[0].0, Method::GET); + assert_eq!( + observations[0].1, + "/v1/review-asks?cursor=00000000-0000-0000-0000-000000000004&limit=25" + ); + assert_eq!(observations[1].0, Method::GET); + assert_eq!( + observations[1].1, + format!("/v1/review-requests/{request_id}/asks/{ask_id}") + ); + assert_eq!(observations[2].0, Method::POST); + assert_eq!( + observations[2].1, + format!("/v1/review-requests/{request_id}/asks/{ask_id}/answer") + ); + assert_eq!(observations[2].2["idempotency-key"], "answer-5"); + server.abort(); +} + +#[tokio::test] +async fn answer_posts_exactly_the_subject_and_answer_time() { + let bodies = Arc::new(Mutex::new(Vec::::new())); + let app = Router::new() + .route( + "/v1/review-requests/{id}/asks/{ask}/answer", + post( + |State(bodies): State>>>, + Path((request_id, ask_id)): Path<(Uuid, Uuid)>, + body: String| async move { + bodies.lock().expect("bodies").push(body); + json_response(StatusCode::OK, answered_ask_json(request_id, ask_id)) + }, + ), + ) + .with_state(bodies.clone()); + let (client, server) = serve(app).await; + let token = BearerToken::new("one-call-secret").expect("fixture token"); + client + .answer_ask( + ReviewAuth::new(&token, "producer"), + "answer-5", + &expected_binding(Uuid::from_u128(7)), + Uuid::from_u128(5), + &ask_answer(), + ) + .await + .expect("answer"); + let bodies = bodies.lock().expect("bodies"); + let body: serde_json::Value = serde_json::from_str(&bodies[0]).expect("JSON body"); + let mut members: Vec<_> = body.as_object().expect("object").keys().cloned().collect(); + members.sort(); + assert_eq!(members, ["answeredAt", "subject"]); + server.abort(); +} + +#[tokio::test] +async fn ask_calls_refuse_invalid_input_before_http() { + let observations = Arc::new(Mutex::new(Vec::new())); + let app = Router::new() + .fallback( + |State(observations): State, request: Request| async move { + capture(&observations, &request); + empty_response(StatusCode::NO_CONTENT) + }, + ) + .with_state(observations.clone()); + let (client, server) = serve(app).await; + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let auth = || ReviewAuth::new(&token, "producer"); + let (request_id, ask_id) = (Uuid::from_u128(7), Uuid::from_u128(5)); + + for limit in [0, 101] { + assert!(matches!( + client.ask_feed(auth(), None, Some(limit)).await, + Err(ReviewClientError::InvalidRequest { .. }) + )); + } + let mut nil_request = expected_binding(request_id); + nil_request.request_id = Uuid::nil(); + for (expected, ask) in [ + (expected_binding(request_id), Uuid::nil()), + (nil_request, ask_id), + ] { + assert!(matches!( + client.ask(auth(), &expected, ask).await, + Err(ReviewClientError::InvalidRequest { .. }) + )); + assert!(matches!( + client + .answer_ask(auth(), "key", &expected, ask, &ask_answer()) + .await, + Err(ReviewClientError::InvalidRequest { .. }) + )); + } + for key in ["", "has space"] { + assert!(matches!( + client + .answer_ask( + auth(), + key, + &expected_binding(request_id), + ask_id, + &ask_answer() + ) + .await, + Err(ReviewClientError::InvalidRequest { .. }) + )); + } + let mut bad_binding = expected_binding(request_id); + bad_binding.subject.id = String::new(); + assert!(matches!( + client.ask(auth(), &bad_binding, ask_id).await, + Err(ReviewClientError::InvalidRequest { .. }) + )); + let mut bad_answer = ask_answer(); + bad_answer.subject.id = String::new(); + assert!(matches!( + client + .answer_ask( + auth(), + "key", + &expected_binding(request_id), + ask_id, + &bad_answer + ) + .await, + Err(ReviewClientError::InvalidRequest { .. }) + )); + // An answer for another subject than the accepted request's never leaves. + let mut other_answer = ask_answer(); + other_answer.subject.digest = ContentDigest::parse(OTHER_DIGEST).expect("digest fixture"); + assert!(matches!( + client + .answer_ask( + auth(), + "key", + &expected_binding(request_id), + ask_id, + &other_answer + ) + .await, + Err(ReviewClientError::InvalidRequest { .. }) + )); + assert!(observations.lock().expect("observations").is_empty()); + server.abort(); +} + +#[tokio::test] +async fn ask_feed_refuses_nil_identifiers_a_misplaced_cursor_and_too_many_entries() { + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let entry = |event: u128, request: u128, ask: u128| { + json!({ + "eventId": Uuid::from_u128(event), + "requestId": Uuid::from_u128(request), + "askId": Uuid::from_u128(ask), + "changedAt": "2026-11-27T01:00:00Z" + }) + }; + let pages = [ + json!({"items": [entry(0, 7, 5)]}), + json!({"items": [entry(8, 0, 5)]}), + json!({"items": [entry(8, 7, 0)]}), + json!({"items": [entry(8, 7, 5)], "nextCursor": Uuid::from_u128(9)}), + json!({"items": [], "nextCursor": Uuid::from_u128(9)}), + json!({"items": (1..=101).map(|n| entry(n, 7, 5)).collect::>()}), + ]; + for page in pages { + let app = Router::new().route( + "/v1/review-asks", + get(move || { + let page = page.clone(); + async move { json_response(StatusCode::OK, page) } + }), + ); + let (client, server) = serve(app).await; + assert!(matches!( + client + .ask_feed(ReviewAuth::new(&token, "producer"), None, None) + .await, + Err(ReviewClientError::Protocol { + failure: ReviewProtocolFailure::Body, + .. + }) + )); + server.abort(); + } +} + +#[tokio::test] +async fn ask_feed_past_retention_is_a_gone_problem_the_caller_restarts_from() { + let app = Router::new().route( + "/v1/review-asks", + get(|| async { problem_with(StatusCode::GONE, "cursor.expired") }), + ); + let (client, server) = serve(app).await; + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let error = client + .ask_feed( + ReviewAuth::new(&token, "producer"), + Some(Uuid::from_u128(4)), + None, + ) + .await + .expect_err("410 is not a page"); + assert!(matches!( + error, + ReviewClientError::Problem { status: 410, .. } + )); + server.abort(); +} + +#[tokio::test] +async fn ask_read_refuses_every_mismatched_binding_and_invalid_ask() { + let (request_id, ask_id) = (Uuid::from_u128(7), Uuid::from_u128(5)); + let mut other_binding = expected_binding(request_id); + other_binding.subject.digest = ContentDigest::parse(OTHER_DIGEST).expect("digest fixture"); + let mut cases = Vec::new(); + let mut wrong_request = ask_json(request_id, ask_id); + wrong_request["requestId"] = json!(Uuid::from_u128(8)); + cases.push(wrong_request); + let mut wrong_ask = ask_json(request_id, ask_id); + wrong_ask["askId"] = json!(Uuid::from_u128(6)); + cases.push(wrong_ask); + let mut wrong_digest = ask_json(request_id, ask_id); + wrong_digest["subject"]["digest"] = json!(OTHER_DIGEST); + cases.push(wrong_digest); + let mut wrong_version = ask_json(request_id, ask_id); + wrong_version["subject"]["version"] = json!("4"); + cases.push(wrong_version); + // An answered ask with no answer time breaks the ask's own rules. + let mut invalid = ask_json(request_id, ask_id); + invalid["state"] = json!("answered"); + cases.push(invalid); + let mut unknown_state = ask_json(request_id, ask_id); + unknown_state["state"] = json!("reopened"); + cases.push(unknown_state); + + let token = BearerToken::new("one-call-secret").expect("fixture token"); + for body in cases { + let app = Router::new().route( + "/v1/review-requests/{id}/asks/{ask}", + get(move || { + let body = body.clone(); + async move { json_response(StatusCode::OK, body) } + }), + ); + let (client, server) = serve(app).await; + let outcome = client + .ask( + ReviewAuth::new(&token, "producer"), + &expected_binding(request_id), + ask_id, + ) + .await; + assert!( + matches!( + outcome, + Err(ReviewClientError::Protocol { + failure: ReviewProtocolFailure::Body, + .. + }) + ), + "{outcome:?}" + ); + server.abort(); + } + // The subject the caller expects is what is compared, not the request's. + let app = Router::new().route( + "/v1/review-requests/{id}/asks/{ask}", + get(|| async { + json_response( + StatusCode::OK, + ask_json(Uuid::from_u128(7), Uuid::from_u128(5)), + ) + }), + ); + let (client, server) = serve(app).await; + assert!(matches!( + client + .ask(ReviewAuth::new(&token, "producer"), &other_binding, ask_id) + .await, + Err(ReviewClientError::Protocol { + failure: ReviewProtocolFailure::Body, + .. + }) + )); + server.abort(); +} + +/// Every response the ask read and the answer call must refuse for a defined +/// refusal status instead of mapping it to a typed outcome. +fn refusals_that_are_not_typed_outcomes(status: StatusCode) -> Vec<(&'static str, Response)> { + const TRACE: &str = "0123456789abcdef0123456789abcdef"; + vec![ + ( + "a body without a content type", + raw_response(status, None, "not empty"), + ), + ( + "an empty body with a content type", + raw_response(status, Some("application/json"), ""), + ), + ( + "a proxy page", + raw_response(status, Some("text/html"), "bad gateway"), + ), + ( + "a problem whose status member differs", + problem_document(status, "request.not-found", 500, TRACE), + ), + ( + "a problem whose trace id differs from traceparent", + problem_document( + status, + "request.not-found", + status.as_u16(), + "ffffffffffffffffffffffffffffffff", + ), + ), + ( + "a route miss problem", + problem_document(status, "request.not-found", status.as_u16(), TRACE), + ), + ( + "another named problem", + problem_document(status, "idempotency.key-reused", status.as_u16(), TRACE), + ), + ] +} + +#[tokio::test] +async fn ask_read_maps_only_an_empty_404_to_concealed_or_unknown() { + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let (request_id, ask_id) = (Uuid::from_u128(7), Uuid::from_u128(5)); + let route = "/v1/review-requests/{id}/asks/{ask}"; + let app = Router::new().route( + route, + get(|| async { empty_response(StatusCode::NOT_FOUND) }), + ); + let (client, server) = serve(app).await; + let outcome = client + .ask( + ReviewAuth::new(&token, "producer"), + &expected_binding(request_id), + ask_id, + ) + .await + .expect("an empty 404 is a defined outcome"); + assert!(matches!( + outcome, + ReviewAskResponse::ConcealedOrUnknown { .. } + )); + server.abort(); + + for (name, response) in refusals_that_are_not_typed_outcomes(StatusCode::NOT_FOUND) { + let response = Arc::new(Mutex::new(Some(response))); + let app = Router::new().route( + route, + get( + move || async move { response.lock().expect("response").take().expect("one call") }, + ), + ); + let (client, server) = serve(app).await; + let outcome = client + .ask( + ReviewAuth::new(&token, "producer"), + &expected_binding(request_id), + ask_id, + ) + .await; + assert!( + outcome.is_err(), + "{name} must not be an outcome: {outcome:?}" + ); + server.abort(); + } + // A named problem 404 is the provider's refusal, surfaced as such. + let app = Router::new().route( + route, + get(|| async { problem_with(StatusCode::NOT_FOUND, "request.not-found") }), + ); + let (client, server) = serve(app).await; + assert!(matches!( + client + .ask( + ReviewAuth::new(&token, "producer"), + &expected_binding(request_id), + ask_id + ) + .await, + Err(ReviewClientError::Problem { status: 404, .. }) + )); + server.abort(); + + let app = Router::new().route( + route, + get(|| async { problem_with(StatusCode::SERVICE_UNAVAILABLE, "runtime.failure") }), + ); + let (client, server) = serve(app).await; + assert!(matches!( + client + .ask( + ReviewAuth::new(&token, "producer"), + &expected_binding(request_id), + ask_id + ) + .await, + Err(ReviewClientError::Problem { status: 503, .. }) + )); + server.abort(); +} + +#[tokio::test] +async fn answer_maps_an_empty_404_and_only_the_not_open_409_to_typed_outcomes() { + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let (request_id, ask_id) = (Uuid::from_u128(7), Uuid::from_u128(5)); + let route = "/v1/review-requests/{id}/asks/{ask}/answer"; + let answer = |client: ReviewClient| { + let token = &token; + async move { + client + .answer_ask( + ReviewAuth::new(token, "producer"), + "answer-5", + &expected_binding(request_id), + ask_id, + &ask_answer(), + ) + .await + } + }; + + let app = Router::new().route( + route, + post(|| async { empty_response(StatusCode::NOT_FOUND) }), + ); + let (client, server) = serve(app).await; + assert!(matches!( + answer(client).await.expect("an empty 404 is an outcome"), + ReviewAskAnswerResponse::ConcealedOrUnknown { trace_id } + if trace_id == "0123456789abcdef0123456789abcdef" + )); + server.abort(); + + let app = Router::new().route( + route, + post(|| async { problem_with(StatusCode::CONFLICT, REVIEW_ASK_NOT_OPEN_PROBLEM) }), + ); + let (client, server) = serve(app).await; + assert!(matches!( + answer(client).await.expect("the not-open 409 is an outcome"), + ReviewAskAnswerResponse::NotOpen { trace_id } + if trace_id == "0123456789abcdef0123456789abcdef" + )); + server.abort(); + + for status in [StatusCode::NOT_FOUND, StatusCode::CONFLICT] { + for (name, response) in refusals_that_are_not_typed_outcomes(status) { + let response = Arc::new(Mutex::new(Some(response))); + let app = Router::new().route( + route, + post(move || async move { + response.lock().expect("response").take().expect("one call") + }), + ); + let (client, server) = serve(app).await; + let outcome = answer(client).await; + assert!( + outcome.is_err(), + "{status} with {name} must not be an outcome: {outcome:?}" + ); + server.abort(); + } + } + // An empty 409 is not what a provider sends for a closed ask. + let app = Router::new().route( + route, + post(|| async { empty_response(StatusCode::CONFLICT) }), + ); + let (client, server) = serve(app).await; + assert!(answer(client).await.is_err()); + server.abort(); + + // A reused idempotency key stays a visible, deterministic problem. + let app = Router::new().route( + route, + post(|| async { problem_with(StatusCode::CONFLICT, "idempotency.key-reused") }), + ); + let (client, server) = serve(app).await; + let error = answer(client) + .await + .expect_err("a different 409 is an error"); + assert!(matches!( + &error, + ReviewClientError::Problem { status: 409, problem } + if problem.code.as_str() == "idempotency.key-reused" + )); + assert_eq!( + error.mutation_class(), + ReviewMutationErrorClass::Deterministic + ); + server.abort(); +} + +#[tokio::test] +async fn answer_refuses_a_returned_ask_that_is_not_the_answered_one() { + let (request_id, ask_id) = (Uuid::from_u128(7), Uuid::from_u128(5)); + let mut still_open = ask_json(request_id, ask_id); + still_open["state"] = json!("open"); + let mut closed = ask_json(request_id, ask_id); + closed["state"] = json!("closed"); + closed["closedAt"] = json!("2026-11-27T03:00:00Z"); + let mut wrong_request = answered_ask_json(request_id, ask_id); + wrong_request["requestId"] = json!(Uuid::from_u128(8)); + let mut wrong_ask = answered_ask_json(request_id, ask_id); + wrong_ask["askId"] = json!(Uuid::from_u128(6)); + let mut wrong_subject = answered_ask_json(request_id, ask_id); + wrong_subject["subject"]["digest"] = json!(OTHER_DIGEST); + + let token = BearerToken::new("one-call-secret").expect("fixture token"); + for body in [still_open, closed, wrong_request, wrong_ask, wrong_subject] { + let app = Router::new().route( + "/v1/review-requests/{id}/asks/{ask}/answer", + post(move || { + let body = body.clone(); + async move { json_response(StatusCode::OK, body) } + }), + ); + let (client, server) = serve(app).await; + let outcome = client + .answer_ask( + ReviewAuth::new(&token, "producer"), + "answer-5", + &expected_binding(request_id), + ask_id, + &ask_answer(), + ) + .await; + assert!( + matches!( + outcome, + Err(ReviewClientError::Protocol { + failure: ReviewProtocolFailure::Body, + .. + }) + ), + "{outcome:?}" + ); + server.abort(); + } +} + +#[tokio::test] +async fn answer_refuses_a_success_recorded_at_another_answer_time() { + let (request_id, ask_id) = (Uuid::from_u128(7), Uuid::from_u128(5)); + let mut other_time = answered_ask_json(request_id, ask_id); + other_time["answeredAt"] = json!("2026-11-27T02:00:00.000001Z"); + let app = Router::new().route( + "/v1/review-requests/{id}/asks/{ask}/answer", + post(move || { + let body = other_time.clone(); + async move { json_response(StatusCode::OK, body) } + }), + ); + let (client, server) = serve(app).await; + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let outcome = client + .answer_ask( + ReviewAuth::new(&token, "producer"), + "answer-5", + &expected_binding(request_id), + ask_id, + &ask_answer(), + ) + .await; + assert!( + matches!( + outcome, + Err(ReviewClientError::Protocol { + failure: ReviewProtocolFailure::Body, + .. + }) + ), + "{outcome:?}" + ); + server.abort(); +} + +#[tokio::test] +async fn answer_refuses_a_sub_microsecond_answer_time_before_http() { + let app = Router::new().fallback(|| async { empty_response(StatusCode::NO_CONTENT) }); + let (client, server) = serve(app).await; + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let mut answer = ask_answer(); + answer.answered_at += chrono::Duration::nanoseconds(1); + assert!(matches!( + client + .answer_ask( + ReviewAuth::new(&token, "producer"), + "answer-5", + &expected_binding(Uuid::from_u128(7)), + Uuid::from_u128(5), + &answer + ) + .await, + Err(ReviewClientError::InvalidRequest { .. }) + )); + server.abort(); +} + +#[tokio::test] +async fn ask_calls_do_not_retry_and_classify_failures_for_the_caller() { + let attempts = Arc::new(Mutex::new(0usize)); + let app = Router::new() + .route( + "/v1/review-requests/{id}/asks/{ask}/answer", + post(|State(attempts): State>>| async move { + *attempts.lock().expect("attempts") += 1; + problem_with(StatusCode::SERVICE_UNAVAILABLE, "runtime.failure") + }), + ) + .with_state(attempts.clone()); + let (client, server) = serve(app).await; + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let error = client + .answer_ask( + ReviewAuth::new(&token, "producer"), + "answer-5", + &expected_binding(Uuid::from_u128(7)), + Uuid::from_u128(5), + &ask_answer(), + ) + .await + .expect_err("503 is a failure"); + assert_eq!(error.mutation_class(), ReviewMutationErrorClass::Ambiguous); + assert_eq!(*attempts.lock().expect("attempts"), 1); + server.abort(); +} + +#[tokio::test] +async fn ask_calls_refuse_wrong_media_types_and_oversize_bodies() { + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let (request_id, ask_id) = (Uuid::from_u128(7), Uuid::from_u128(5)); + let app = Router::new() + .route( + "/v1/review-requests/{id}/asks/{ask}", + get(|| async { + let mut response = json_response( + StatusCode::OK, + ask_json(Uuid::from_u128(7), Uuid::from_u128(5)), + ); + response + .headers_mut() + .insert("content-type", HeaderValue::from_static("text/plain")); + response + }), + ) + .route( + "/v1/review-requests/{id}/asks/{ask}/answer", + post(|| async { + json_response(StatusCode::OK, json!({"padding": "x".repeat(300_000)})) + }), + ); + let (client, server) = serve(app).await; + assert!(matches!( + client + .ask( + ReviewAuth::new(&token, "producer"), + &expected_binding(request_id), + ask_id + ) + .await, + Err(ReviewClientError::Protocol { + failure: ReviewProtocolFailure::MediaType, + .. + }) + )); + assert!(matches!( + client + .answer_ask( + ReviewAuth::new(&token, "producer"), + "answer-5", + &expected_binding(request_id), + ask_id, + &ask_answer() + ) + .await, + Err(ReviewClientError::Transport { .. }) + )); + server.abort(); +} diff --git a/crates/registry-review-protocol/README.md b/crates/registry-review-protocol/README.md index ce8d11e1c5..25894715c9 100644 --- a/crates/registry-review-protocol/README.md +++ b/crates/registry-review-protocol/README.md @@ -45,3 +45,49 @@ The crate contains no HTTP client, credentials, persistence, source adapter, policy evaluator, reviewer task, or source execution code. In particular, a completion envelope is only a synchronization hint. It cannot carry approval evidence or authorize a source operation. + +An ask is a reviewer's request for more from the subject's owner. The provider +owns it. The producer finds it through the ask feed (`GET /v1/review-asks`, +announcements of ids and times only), reads it at +`/v1/review-requests/{requestId}/asks/{askId}`, and reports it answered with +`POST .../answer`. `ReviewAsk` carries reviewer text bounded like a public +reason, up to eight distinct `wants` (`answer`, `document`), an optional +absolute `dueAt` and a state (`open`, `answered`, `expired`, `closed`). +`askedAt` comes first: `dueAt`, `answeredAt` and `closedAt` are never before it. +`answeredAt` is present exactly when the ask is answered, and `closedAt` exactly +when it is expired or closed. An expired ask has a `dueAt`, and its `closedAt` +is not before it. `ReviewAskAnswer` holds only the subject binding and the +answer time, so it cannot carry the answer itself. The answer time has at most +microsecond precision, so the producer stores and replays exactly the value the +provider keeps. + +Rules for the provider: + +- A provider judges an answer by its `answeredAt`, not by when it arrives. An + answer whose `answeredAt` is at or before `dueAt` is accepted even if the ask + already reads `expired`, and the ask then reads `answered`. A delivery delay + never makes an on-time answer late. +- Only a not-open ask refuses an answer with 409 and the problem code + `review.ask-not-open` (`REVIEW_ASK_NOT_OPEN_PROBLEM`). Every other 409, such + as a reused idempotency key, carries its own code. +- A concealed or unknown ask is an empty 404, as for the result read. +- A provider sends only want kinds the producer's protocol version knows. An + unknown kind is refused when the ask is decoded, so a producer on an older + version cannot read the ask at all. The limit of eight wants stays for kinds + that may repeat. +- A provider validates an ask with `ReviewAsk::check` before it stores it. + +Keep producer and provider clocks synchronized within five minutes: Casework permanently refuses an `answeredAt` beyond that future tolerance with `review.ask-answer-time-invalid`. + +Rules for the producer: + +- Never stall the feed on one bad ask. For a deterministic refusal (a + protocol failure on the ask, or a not-found), record it and move on. For a + transient failure (transport, 5xx), stop the page and retry from the same + cursor. +- A stored copy of an ask only moves forward: `open` becomes exactly one of + `answered`, `expired` or `closed`, never back. Two readers of the same ask + must not store an older copy over a newer one. +- After a `NotOpen` outcome, read the ask to learn which state it is in. +- Use one idempotency key per ask, and store it with the `answeredAt` that was + sent, so a retry after an ambiguous failure replays the same body. diff --git a/crates/registry-review-protocol/src/lib.rs b/crates/registry-review-protocol/src/lib.rs index 38540b10cb..32aeceac20 100644 --- a/crates/registry-review-protocol/src/lib.rs +++ b/crates/registry-review-protocol/src/lib.rs @@ -26,6 +26,12 @@ pub const MAXIMUM_PORTABLE_JSON_INTEGER: u64 = 9_007_199_254_740_991; pub const REVIEW_REQUESTS_PATH: &str = "/v1/review-requests"; pub const REVIEW_RESULTS_FEED_PATH: &str = "/v1/review-results"; pub const REVIEW_COMPLETIONS_PATH: &str = "/v1/review-completions"; +pub const REVIEW_ASKS_FEED_PATH: &str = "/v1/review-asks"; +/// Upper bound on the kinds of reply one ask can request. +pub const MAXIMUM_ASK_WANTS: usize = 8; +/// The problem code of the 409 a provider returns when an ask is no longer +/// open. Any other 409 on the answer call is a different refusal. +pub const REVIEW_ASK_NOT_OPEN_PROBLEM: &str = "review.ask-not-open"; /// Authenticated producer identity on successful create/recovery responses. /// One ASCII identifier of at most 128 bytes; never an identity inferred from a digest. pub const REVIEW_PRODUCER_HEADER: &str = "registry-review-producer"; @@ -48,6 +54,16 @@ pub fn review_cancel_path(request_id: Uuid) -> String { format!("{}/{request_id}/cancel", REVIEW_REQUESTS_PATH) } +#[must_use] +pub fn review_ask_path(request_id: Uuid, ask_id: Uuid) -> String { + format!("{}/{request_id}/asks/{ask_id}", REVIEW_REQUESTS_PATH) +} + +#[must_use] +pub fn review_ask_answer_path(request_id: Uuid, ask_id: Uuid) -> String { + format!("{}/answer", review_ask_path(request_id, ask_id)) +} + #[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct ContentDigest(String); @@ -639,6 +655,142 @@ impl ReviewCancelRequest { } } +/// What a reviewer's ask requests from the subject's owner. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)] +pub enum ReviewAskWant { + // Struct variants, because serde does not enforce `deny_unknown_fields` + // on the unit variants of an internally tagged enum. + Answer {}, + Document {}, +} + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum ReviewAskState { + Open, + Answered, + Expired, + Closed, +} + +/// A reviewer's request for more from the subject's owner. The provider owns +/// the ask; the producer reads it and reports only that it was answered. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReviewAsk { + pub ask_id: Uuid, + pub request_id: Uuid, + pub subject: SubjectBinding, + #[cfg_attr(feature="schema",schemars(length(min=1,max=MAXIMUM_PUBLIC_REASON_BYTES),extend("x-maximum-utf8-bytes"=MAXIMUM_PUBLIC_REASON_BYTES)))] + pub text: String, + #[cfg_attr( + feature = "schema", + schemars(length(max = MAXIMUM_ASK_WANTS), extend("uniqueItems" = true)) + )] + pub wants: Vec, + pub asked_at: DateTime, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub due_at: Option>, + pub state: ReviewAskState, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub answered_at: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub closed_at: Option>, +} + +impl ReviewAsk { + pub fn check(&self) -> Result<(), ProtocolError> { + if self.ask_id.is_nil() || self.request_id.is_nil() { + return Err(ProtocolError::Identifier); + } + self.subject.check()?; + check_public_reason(&self.text)?; + let distinct = self + .wants + .iter() + .enumerate() + .all(|(index, want)| !self.wants[..index].contains(want)); + if self.wants.len() > MAXIMUM_ASK_WANTS || !distinct { + return Err(ProtocolError::AskWants); + } + if self.due_at.is_some_and(|due_at| due_at <= self.asked_at) { + return Err(ProtocolError::AskTimes); + } + let closes = matches!(self.state, ReviewAskState::Expired | ReviewAskState::Closed); + if self.answered_at.is_some() != (self.state == ReviewAskState::Answered) + || self.closed_at.is_some() != closes + { + return Err(ProtocolError::AskTimes); + } + if self + .answered_at + .into_iter() + .chain(self.closed_at) + .any(|at| at < self.asked_at) + { + return Err(ProtocolError::AskTimes); + } + // An ask expires only once its due time has passed. + if self.state == ReviewAskState::Expired + && !matches!((self.due_at, self.closed_at), (Some(due), Some(closed)) if closed >= due) + { + return Err(ProtocolError::AskTimes); + } + Ok(()) + } +} + +/// Announces that an ask was opened, answered, expired or closed. The +/// producer reads the ask next. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReviewAskFeedEntry { + pub event_id: Uuid, + pub request_id: Uuid, + pub ask_id: Uuid, + pub changed_at: DateTime, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReviewAskFeedPage { + pub items: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, +} + +/// The producer's report that the subject's owner answered an ask. It carries +/// the subject binding and the time the answer was committed, so it cannot +/// carry the answer itself. The provider judges the answer by that time, at +/// microsecond precision. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReviewAskAnswer { + pub subject: SubjectBinding, + pub answered_at: DateTime, +} + +impl ReviewAskAnswer { + pub fn check(&self) -> Result<(), ProtocolError> { + self.subject.check()?; + if !self + .answered_at + .timestamp_subsec_nanos() + .is_multiple_of(1_000) + { + return Err(ProtocolError::AskTimes); + } + Ok(()) + } +} + #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde( @@ -755,7 +907,7 @@ pub enum ProtocolError { #[error("the terminal status does not permit the supplied outcome or result")] TerminalPayload, #[error( - "publicReason must be non-blank text of at most 2000 UTF-8 bytes without control characters" + "reviewer-facing text must be non-blank text of at most 2000 UTF-8 bytes without control characters" )] PublicReason, #[error("result availability must end after completion")] @@ -764,6 +916,12 @@ pub enum ProtocolError { Identifier, #[error("the result endpoint returned a status outside the review lookup contract")] UnexpectedResultStatus, + #[error("an ask lists at most eight distinct wants")] + AskWants, + #[error( + "ask times must be ordered, match the ask state and have at most microsecond precision" + )] + AskTimes, } #[cfg(test)] @@ -1384,3 +1542,310 @@ mod policy_binding_tests { ); } } + +#[cfg(test)] +mod ask_tests { + use chrono::TimeZone; + use serde_json::json; + + use super::*; + + fn at(hour: u32) -> DateTime { + Utc.with_ymd_and_hms(2026, 11, 27, hour, 0, 0).unwrap() + } + + fn subject() -> SubjectBinding { + SubjectBinding { + source: "registry".to_owned(), + subject_type: "change-request".to_owned(), + id: "proposal-7".to_owned(), + version: "3".to_owned(), + digest: ContentDigest::for_bytes(b"proposal"), + } + } + + fn open_ask() -> ReviewAsk { + ReviewAsk { + ask_id: Uuid::from_u128(2), + request_id: Uuid::from_u128(1), + subject: subject(), + text: "Please send the signed form.".to_owned(), + wants: vec![ReviewAskWant::Answer {}, ReviewAskWant::Document {}], + asked_at: at(1), + due_at: Some(at(2)), + state: ReviewAskState::Open, + answered_at: None, + closed_at: None, + } + } + + #[test] + fn an_open_ask_is_accepted() { + assert_eq!(open_ask().check(), Ok(())); + let mut bare = open_ask(); + bare.wants.clear(); + bare.due_at = None; + assert_eq!(bare.check(), Ok(())); + } + + #[test] + fn nil_identifiers_are_refused() { + let mut ask = open_ask(); + ask.ask_id = Uuid::nil(); + assert_eq!(ask.check(), Err(ProtocolError::Identifier)); + let mut ask = open_ask(); + ask.request_id = Uuid::nil(); + assert_eq!(ask.check(), Err(ProtocolError::Identifier)); + } + + #[test] + fn the_subject_binding_is_checked() { + let mut ask = open_ask(); + ask.subject.id = " ".to_owned(); + assert_eq!(ask.check(), Err(ProtocolError::Text)); + } + + #[test] + fn text_is_bounded_like_a_public_reason() { + for bad in [ + String::new(), + " ".to_owned(), + "a\nb".to_owned(), + "x".repeat(MAXIMUM_PUBLIC_REASON_BYTES + 1), + ] { + let mut ask = open_ask(); + ask.text = bad; + assert_eq!(ask.check(), Err(ProtocolError::PublicReason)); + } + let mut ask = open_ask(); + ask.text = "x".repeat(MAXIMUM_PUBLIC_REASON_BYTES); + assert_eq!(ask.check(), Ok(())); + } + + #[test] + fn wants_are_at_most_eight_and_distinct() { + let mut ask = open_ask(); + ask.wants = vec![ReviewAskWant::Answer {}, ReviewAskWant::Answer {}]; + assert_eq!(ask.check(), Err(ProtocolError::AskWants)); + // Eight entries pass the count, so only the duplicate rule refuses them. + ask.wants = vec![ReviewAskWant::Answer {}; MAXIMUM_ASK_WANTS]; + assert_eq!(ask.check(), Err(ProtocolError::AskWants)); + ask.wants = vec![ReviewAskWant::Answer {}; MAXIMUM_ASK_WANTS + 1]; + assert_eq!(ask.check(), Err(ProtocolError::AskWants)); + ask.wants = vec![ReviewAskWant::Document {}]; + assert_eq!(ask.check(), Ok(())); + } + + #[test] + fn the_due_time_follows_the_ask_time() { + let mut ask = open_ask(); + ask.due_at = Some(ask.asked_at); + assert_eq!(ask.check(), Err(ProtocolError::AskTimes)); + ask.due_at = Some(at(0)); + assert_eq!(ask.check(), Err(ProtocolError::AskTimes)); + } + + #[test] + fn answered_at_is_present_exactly_when_answered() { + let mut ask = open_ask(); + ask.state = ReviewAskState::Answered; + assert_eq!(ask.check(), Err(ProtocolError::AskTimes)); + ask.answered_at = Some(at(2)); + assert_eq!(ask.check(), Ok(())); + for state in [ + ReviewAskState::Open, + ReviewAskState::Expired, + ReviewAskState::Closed, + ] { + let mut other = open_ask(); + other.state = state; + other.answered_at = Some(at(2)); + other.closed_at = + matches!(state, ReviewAskState::Expired | ReviewAskState::Closed).then(|| at(3)); + assert_eq!(other.check(), Err(ProtocolError::AskTimes), "{state:?}"); + } + } + + #[test] + fn closed_at_is_present_exactly_when_expired_or_closed() { + for state in [ReviewAskState::Expired, ReviewAskState::Closed] { + let mut ask = open_ask(); + ask.state = state; + assert_eq!(ask.check(), Err(ProtocolError::AskTimes), "{state:?}"); + ask.closed_at = Some(at(3)); + assert_eq!(ask.check(), Ok(()), "{state:?}"); + } + for state in [ReviewAskState::Open, ReviewAskState::Answered] { + let mut ask = open_ask(); + ask.state = state; + ask.answered_at = (state == ReviewAskState::Answered).then(|| at(2)); + ask.closed_at = Some(at(3)); + assert_eq!(ask.check(), Err(ProtocolError::AskTimes), "{state:?}"); + } + } + + #[test] + fn ask_times_are_ordered() { + // Answered before it was asked. + let mut ask = open_ask(); + ask.state = ReviewAskState::Answered; + ask.answered_at = Some(at(0)); + assert_eq!(ask.check(), Err(ProtocolError::AskTimes)); + ask.answered_at = Some(ask.asked_at); + assert_eq!(ask.check(), Ok(())); + // Closed or expired before it was asked. + for state in [ReviewAskState::Expired, ReviewAskState::Closed] { + let mut ask = open_ask(); + ask.state = state; + ask.closed_at = Some(at(0)); + assert_eq!(ask.check(), Err(ProtocolError::AskTimes), "{state:?}"); + } + } + + #[test] + fn an_expired_ask_has_a_due_time_that_has_passed() { + let mut ask = open_ask(); + ask.state = ReviewAskState::Expired; + ask.due_at = None; + ask.closed_at = Some(at(3)); + assert_eq!(ask.check(), Err(ProtocolError::AskTimes)); + ask.due_at = Some(at(4)); + assert_eq!(ask.check(), Err(ProtocolError::AskTimes)); + ask.due_at = Some(at(3)); + assert_eq!(ask.check(), Ok(())); + // A closed ask may close before its due time. + ask.state = ReviewAskState::Closed; + ask.due_at = Some(at(4)); + assert_eq!(ask.check(), Ok(())); + } + + #[test] + fn the_answer_time_has_at_most_microsecond_precision() { + let mut answer = ReviewAskAnswer { + subject: subject(), + answered_at: at(2) + chrono::Duration::microseconds(123_456), + }; + assert_eq!(answer.check(), Ok(())); + answer.answered_at += chrono::Duration::nanoseconds(1); + assert_eq!(answer.check(), Err(ProtocolError::AskTimes)); + } + + #[test] + fn the_not_open_problem_code_is_fixed() { + assert_eq!(REVIEW_ASK_NOT_OPEN_PROBLEM, "review.ask-not-open"); + } + + #[test] + fn wire_names_are_fixed() { + let mut ask = open_ask(); + ask.state = ReviewAskState::Answered; + ask.answered_at = Some(at(2)); + let value = serde_json::to_value(&ask).unwrap(); + assert_eq!(value["state"], json!("answered")); + assert_eq!( + value["wants"], + json!([{"kind": "answer"}, {"kind": "document"}]) + ); + for member in [ + "askId", + "requestId", + "subject", + "text", + "askedAt", + "dueAt", + "answeredAt", + ] { + assert!(value.get(member).is_some(), "{member}"); + } + assert!(value.get("closedAt").is_none()); + assert_eq!( + serde_json::from_value::(value.clone()).unwrap(), + ask + ); + + for (state, word) in [ + (ReviewAskState::Open, "open"), + (ReviewAskState::Answered, "answered"), + (ReviewAskState::Expired, "expired"), + (ReviewAskState::Closed, "closed"), + ] { + assert_eq!(serde_json::to_value(state).unwrap(), json!(word)); + } + let mut unknown = value; + unknown["extra"] = json!(true); + assert!(serde_json::from_value::(unknown).is_err()); + assert!(serde_json::from_value::(json!({"kind": "photo"})).is_err()); + assert!( + serde_json::from_value::(json!({"kind": "answer", "x": 1})).is_err() + ); + } + + #[test] + fn the_answer_body_cannot_carry_text_or_anything_else() { + let ok = json!({"subject": serde_json::to_value(subject()).unwrap(), "answeredAt": "2026-11-27T02:00:00Z"}); + let answer: ReviewAskAnswer = serde_json::from_value(ok.clone()).unwrap(); + assert_eq!(answer.answered_at, at(2)); + assert_eq!(answer.check(), Ok(())); + for member in ["text", "files", "anything"] { + let mut body = ok.clone(); + body[member] = json!("x"); + assert!( + serde_json::from_value::(body).is_err(), + "{member}" + ); + } + let mut bad = answer; + bad.subject.version = String::new(); + assert_eq!(bad.check(), Err(ProtocolError::Text)); + } + + #[test] + fn the_feed_is_shaped_like_the_result_feed() { + let page = json!({ + "items": [{ + "eventId": Uuid::from_u128(9), + "requestId": Uuid::from_u128(1), + "askId": Uuid::from_u128(2), + "changedAt": "2026-11-27T01:00:00Z" + }], + "nextCursor": Uuid::from_u128(9) + }); + let parsed: ReviewAskFeedPage = serde_json::from_value(page.clone()).unwrap(); + assert_eq!(parsed.items[0].changed_at, at(1)); + assert_eq!(serde_json::to_value(&parsed).unwrap(), page); + let mut extra = page; + extra["items"][0]["text"] = json!("leak"); + assert!(serde_json::from_value::(extra).is_err()); + } + + #[test] + fn paths_follow_the_review_routes() { + let request = Uuid::from_u128(1); + let ask = Uuid::from_u128(2); + assert_eq!(REVIEW_ASKS_FEED_PATH, "/v1/review-asks"); + assert_eq!( + review_ask_path(request, ask), + format!("/v1/review-requests/{request}/asks/{ask}") + ); + assert_eq!( + review_ask_answer_path(request, ask), + format!("/v1/review-requests/{request}/asks/{ask}/answer") + ); + } + + #[cfg(feature = "schema")] + #[test] + fn schemas_follow_the_wire_shape() { + let ask = serde_json::to_value(schemars::schema_for!(ReviewAsk)).unwrap(); + assert_eq!(ask["additionalProperties"], false); + assert_eq!( + ask["$defs"]["ReviewAskState"]["enum"], + json!(["open", "answered", "expired", "closed"]) + ); + assert_eq!(ask["properties"]["wants"]["maxItems"], 8); + assert_eq!(ask["properties"]["wants"]["uniqueItems"], true); + let answer = serde_json::to_value(schemars::schema_for!(ReviewAskAnswer)).unwrap(); + assert_eq!(answer["additionalProperties"], false); + assert_eq!(answer["properties"].as_object().unwrap().len(), 2); + } +} diff --git a/crates/registry-stack-client-node/breg/client.d.ts b/crates/registry-stack-client-node/breg/client.d.ts index 0c321103b2..7b704e610e 100644 --- a/crates/registry-stack-client-node/breg/client.d.ts +++ b/crates/registry-stack-client-node/breg/client.d.ts @@ -1003,6 +1003,9 @@ export declare class BaseRegistryClient { executeRecoveredAction(binding: BRegActionBinding, recovered: BRegRecoveredAction): Promise> executeRecoveredProposalStart(binding: BRegActionBinding, recovered: BRegRecoveredAction): Promise downloadProposalAttachment(proposal: BRegProposal, slot: string): Promise + answerProposalAsk(proposal: BRegProposal, askId: string, body: BRegProposalAnswerRequest, key: string): Promise + downloadProposalAddition(proposal: BRegProposal, addition: string): Promise + addProposalAddition(proposal: BRegProposal, slot: string, contentType: string, bytes: Buffer, key: string): Promise readProposalReviewStatus(proposal: BRegProposal, request?: ReadRequestOptions): Promise> readProposalReviewStatusWithProgress(proposal: BRegProposal, request?: ReadRequestOptions): Promise> readProposalReviewContext(proposal: BRegProposal, request?: ReadRequestOptions): Promise> @@ -1049,7 +1052,7 @@ export declare class BaseRegistryClient { } export type BRegProposalTransition = 'edit' | 'submit' | 'revise' | 'rebase' | 'retry' | 'cancel' | 'apply' -export type BRegAvailabilityReason = 'pending-review' | 'review-rejected' | 'review-changes-requested' | 'review-ended' | 'stale-revision' | 'package-changed' | 'dependency-outage' | 'invalid-input' | 'already-applied' +export type BRegAvailabilityReason = 'pending-review' | 'review-rejected' | 'review-changes-requested' | 'review-ended' | 'stale-revision' | 'package-changed' | 'dependency-outage' | 'invalid-input' | 'already-applied' | 'limit-reached' | 'application-pending' | 'attachment-required' | 'attachment-pending' | 'ask-answered' | 'ask-closed' | 'ask-due-passed' export type BRegRecoveryHint = 'refresh' | 'revise' | 'retry' | 'rebase' | 'correct-input' | 'receipt-only' export type BRegAvailability = | { readonly available: true; readonly observedRevision: number } @@ -1061,6 +1064,16 @@ export interface BRegProposalAttachment { readonly links: Readonly & {readonly method: 'GET' | 'PATCH' | 'DELETE'}>>> readonly value?: {readonly submissionVersion: number; readonly sha256: string; readonly contentType: string; readonly byteSize: number; readonly uploadedAt?: string; readonly verificationStatus: 'notRequired' | 'pending' | 'approved' | 'rejected'} } +export interface BRegProposalAddition { + readonly id: string; readonly submissionVersion: number; readonly sha256: string; readonly byteSize: number + readonly contentType: string; readonly addedAt: string; readonly verificationStatus: 'notRequired' | 'pending' | 'approved' | 'rejected' + readonly links: Readonly>> +} +export interface BRegProposalAdditionSlot { + readonly id: string; readonly maximumBytes: number; readonly maximumCount: number + readonly contentTypes: ReadonlyArray; readonly classification: 'public' | 'internal' | 'restricted' + readonly items: ReadonlyArray; readonly links: Readonly>> +} export interface BRegProposalApplication { readonly applicationId: string; readonly submissionVersion: number; readonly effectDigest: string readonly appliedBy?: string; readonly appliedAt?: string @@ -1070,14 +1083,14 @@ export interface BRegProposalApplicationStatus { readonly state: 'awaiting-review' | 'pending' | 'applying' | 'blocked' | 'applied' | 'cancelled' | 'rejected' readonly mode: 'automatic' | 'manual' readonly reason?: 'package-changed' | 'dependency-outage' | 'lease-expired' | 'application-refused' | 'attempts-exhausted' - readonly recovery?: 'retry' | 'rebase' | 'correct-input' + readonly recovery?: 'retry' | 'rebase' | 'revise' | 'correct-input' readonly automaticRetry?: {readonly scheduled: boolean; readonly attempts: number; readonly maximumAttempts: number} } export interface BRegProposalReviewDocument { readonly id: string; readonly actionId: string; readonly actionRevision: string readonly submissionVersion: number; readonly revision: number; readonly effectDigest: string; readonly reviewable: boolean readonly subject: {readonly source: string; readonly subjectType: 'proposal'; readonly id: string; readonly version: string; readonly digest: string} - readonly context: {readonly reference: string; readonly contract?: {readonly id: string; readonly revision: string; readonly schemaDigest: string}; readonly fields?: Readonly>} + readonly context: {readonly reference: string; readonly contract?: {readonly id: string; readonly revision: string; readonly schemaDigest: string}; readonly fields?: Readonly>; readonly asks?: ReadonlyArray} readonly requestId?: string /** Present only on an explicit progress status read while the accepted request remains pending. */ readonly progressCode?: string @@ -1088,6 +1101,7 @@ export interface BRegProposalReviewDocument { } /** Who is expected to act next, derived by BReg. */ export type BRegProposalTurn = 'party' | 'official' | 'nobody' +export type BRegProposalStatus = 'draft' | 'awaiting-party' | 'in-review' | 'approved' | 'processing' | 'applied' | 'rejected' | 'cancelled' /** The review decision on one submission. The public reason is the only reviewer text BReg serves. */ export interface BRegProposalDecision { readonly status: 'approved' | 'rejected' | 'changes-requested' | 'answered'; readonly decidedAt: string; readonly publicReason?: string } /** Why the review authority refused to take a submission. BReg names only these codes and never the authority's own text. */ @@ -1099,7 +1113,7 @@ export interface BRegProposalSubmission { readonly decision?: BRegProposalDecision readonly handoffRefusal?: BRegProposalHandoffRefusal } -export interface BRegProposalDocument { readonly id: string; readonly actionId: string; readonly actionRevision: string; readonly submissionVersion: number; readonly revision: number; readonly state: 'draft' | 'submitted' | 'cancelled' | 'applied' | 'rejected'; readonly createdAt?: string; readonly turn?: BRegProposalTurn; readonly decision?: BRegProposalDecision; readonly handoffRefusal?: BRegProposalHandoffRefusal; readonly title?: string; readonly input?: JsonObject; readonly blockedReason?: 'package-changed'; readonly effectDigest?: string; readonly application?: BRegProposalApplication; readonly applicationStatus?: BRegProposalApplicationStatus; readonly links: Readonly>>; readonly attachments?: Readonly> } +export interface BRegProposalDocument { readonly id: string; readonly actionId: string; readonly actionRevision: string; readonly submissionVersion: number; readonly revision: number; readonly state: 'draft' | 'submitted' | 'cancelled' | 'applied' | 'rejected'; readonly createdAt?: string; readonly turn?: BRegProposalTurn; readonly status?: BRegProposalStatus; readonly decision?: BRegProposalDecision; readonly handoffRefusal?: BRegProposalHandoffRefusal; readonly title?: string; readonly input?: JsonObject; readonly blockedReason?: 'package-changed'; readonly effectDigest?: string; readonly application?: BRegProposalApplication; readonly applicationStatus?: BRegProposalApplicationStatus; readonly links: Readonly>>; readonly attachments?: Readonly>; readonly additions?: Readonly>; readonly asks?: ReadonlyArray } export declare class BRegProposal { private constructor(); private readonly __opaque: void; readonly responseEtag: string | null; readonly identifier: string; readonly actionIdentifier: string; readonly documentJson: string; readonly inputJson?: string | null } export declare class BRegProposalGetBinding { private constructor(); private readonly __opaque: void } export declare class BRegProposalReviewBinding { private constructor(); private readonly __opaque: void } @@ -1122,3 +1136,20 @@ export declare class BRegProposalCollection { private constructor(); private rea export interface BRegProposalPage { readonly items: ReadonlyArray; readonly nextCursor?: string } export declare class BRegPreparedProposal { private constructor(); private readonly __opaque: void; static fromBytes(bytes: Buffer): BRegPreparedProposal; toBytes(): Buffer } + +export type BRegProposalAskState = 'open' | 'answered' | 'expired' | 'closed' +export type BRegProposalAskWant = {readonly kind: 'answer'} | {readonly kind: 'document'} +export interface BRegProposalAnswerRequest {readonly text?: string; readonly additions?: ReadonlyArray} +export interface BRegProposalAskAnswer {readonly text?: string; readonly additions: ReadonlyArray; readonly answeredAt: string} +export interface BRegProposalAsk { + readonly id: string; readonly text: string; readonly wants: ReadonlyArray + readonly askedAt: string; readonly dueAt?: string; readonly state: BRegProposalAskState + readonly answer?: BRegProposalAskAnswer; readonly links: Readonly>> +} +export interface BRegProposalReviewAnswerDownload {readonly method: 'GET'; readonly operation: 'get-review-context'; readonly accessProfile: string; readonly path: string} +export interface BRegProposalReviewAnswerDocument { + readonly id: string; readonly sha256: string; readonly contentType: string; readonly byteSize: number + readonly verificationStatus: 'notRequired' | 'pending' | 'approved' | 'rejected'; readonly download?: BRegProposalReviewAnswerDownload +} +export interface BRegProposalReviewAnswer {readonly text?: string; readonly documents: ReadonlyArray; readonly answeredAt: string} +export interface BRegProposalReviewAsk extends Omit {readonly answer?: BRegProposalReviewAnswer} diff --git a/crates/registry-stack-client-node/breg/client.js b/crates/registry-stack-client-node/breg/client.js index d5fe4108a0..4382702991 100644 --- a/crates/registry-stack-client-node/breg/client.js +++ b/crates/registry-stack-client-node/breg/client.js @@ -303,6 +303,8 @@ for (const [method, jsonIndexes, requiredIndexes] of [ ['patchRecord', [3], [3]], ['batchRecords', [1], [1]], ['tombstoneRecord'], ['startProposal', [1], [1]], ['readProposal'], ['readProposalSubmission'], ['getProposal'], ['listProposals', [1], [1]], ['executeProposal'], ['listProposalsJson'], ['downloadProposalAttachment'], ['uploadProposalAttachment'], ['deleteProposalAttachment'], + ['answerProposalAsk'], + ['addProposalAddition'], ['downloadProposalAddition'], ['downloadRecordAttachment'], ['readProposalReviewStatus'], ['readProposalReviewStatusWithProgress'], ['readProposalReviewContext'], ['readProposalReviewContextBatch', [1], [1]], diff --git a/crates/registry-stack-client-node/breg/index.d.ts b/crates/registry-stack-client-node/breg/index.d.ts index 05e3fe4270..1f85ead8fe 100644 --- a/crates/registry-stack-client-node/breg/index.d.ts +++ b/crates/registry-stack-client-node/breg/index.d.ts @@ -59,6 +59,9 @@ export declare class BaseRegistryClient { readProposalReviewStatusWithProgress(proposal: BRegProposal, cancellation?: ReadCancellation | undefined | null): Promise readProposalReviewContext(proposal: BRegProposal, cancellation?: ReadCancellation | undefined | null): Promise readProposalReviewContextBatch(binding: BRegProposalReviewBinding, ids: Array, cancellation?: ReadCancellation | undefined | null): Promise + answerProposalAsk(proposal: BRegProposal, askId: string, body: any, key: string): Promise + addProposalAddition(proposal: BRegProposal, slot: string, contentType: string, bytes: Buffer, key: string): Promise + downloadProposalAddition(proposal: BRegProposal, addition: string): Promise uploadProposalAttachment(proposal: BRegProposal, slot: string, contentType: string, bytes: Buffer, key: string): Promise deleteProposalAttachment(proposal: BRegProposal, slot: string, key: string): Promise listProposals(collection: BRegProposalCollection, query: any, cancellation?: ReadCancellation | undefined | null): Promise diff --git a/crates/registry-stack-client-node/casework/client.d.ts b/crates/registry-stack-client-node/casework/client.d.ts index 59aaecf02e..58df0dc542 100644 --- a/crates/registry-stack-client-node/casework/client.d.ts +++ b/crates/registry-stack-client-node/casework/client.d.ts @@ -146,6 +146,13 @@ export type KnownCaseworkProblemCode = | 'request.unprocessable' | 'request.unsupported-media-type' | 'review.distinct-approver-required' + | 'review.ask-already-open' + | 'review.ask-answer-time-invalid' + | 'review.ask-limit-reached' + | 'review.ask-not-offered' + | 'review.ask-not-open' + | 'review.ask-producer-unsupported' + | 'review.ask-task-inactive' | 'review.initiator-excluded' | 'review.initiator-required' | 'review.query-too-broad' @@ -268,7 +275,8 @@ export type ReviewCancelResponse = export interface ReviewPageQuery { cursor?: Uuid; limit?: SafeInteger } export type ReviewTaskOwnership = 'assigned-to-me' | 'unclaimed' export type ReviewTaskSort = 'due' | 'subject' | 'reference' -export interface ReviewStaffingPageQuery { queue?: string; ownership?: ReviewTaskOwnership; reference?: string; sort?: ReviewTaskSort; cursor?: Uuid; limit?: SafeInteger } +export type ReviewTaskMarker = 'waiting' | 'answered' | 'expired' +export interface ReviewStaffingPageQuery { queue?: string; ownership?: ReviewTaskOwnership; marker?: ReviewTaskMarker; reference?: string; sort?: ReviewTaskSort; cursor?: Uuid; limit?: SafeInteger } /** A subject selector is absent or names every component of its immutable binding. */ export type ReviewStaffingQuery = ReviewStaffingPageQuery & ( | { subjectSource?: never; subjectType?: never; subjectId?: never; subjectVersion?: never; subjectDigest?: never } @@ -310,6 +318,7 @@ export interface ReviewTask { staffingDiagnostic?: StaffingDiagnostic decidedByCaller?: boolean decisionReceipt?: ReviewDecisionReceipt + marker?: ReviewTaskMarker } export interface ReviewTaskPage { items: ReadonlyArray; nextCursor?: Uuid; status: PageStatus } export type SupervisoryReviewTaskState = 'open' | 'held' | 'decided' @@ -328,6 +337,52 @@ export interface ReviewSourceProjection { binding: SubjectBinding; displayRefere export type ReviewTaskContextData = | { mode: 'submitted'; snapshot: Readonly> } | { mode: 'current-source'; reference: string; bindingStatus: ReviewSourceBindingStatus; projection?: ReviewSourceProjection } +export type ReviewAskWant = { kind: 'answer' } | { kind: 'document' } +export type ReviewAskState = 'open' | 'answered' | 'expired' | 'closed' +export interface ReviewTaskAskRequest { text: string; wants: ReadonlyArray } +export interface ReviewAsk { + askId: Uuid + requestId: Uuid + subject: SubjectBinding + text: string + wants: ReadonlyArray + askedAt: string + dueAt?: string + state: ReviewAskState + answeredAt?: string + closedAt?: string +} +export interface ReviewTaskAsked { task: ReviewTask; ask: ReviewAsk } +export interface ReviewAnswerDownload { + method: 'GET' + operation: string + accessProfile: string + path: string +} +export interface ReviewAnswerDocument { + id: string + sha256: string + contentType: string + byteSize: number + verificationStatus?: string + download?: ReviewAnswerDownload +} +export interface ReviewContextAnswer { + text?: string + documents: ReadonlyArray + answeredAt: string +} +export interface ReviewContextAsk { + askId: Uuid + taskId: Uuid + text: string + wants: ReadonlyArray + askedAt: string + dueAt?: string + state: ReviewAskState + answeredAt?: string + answer?: ReviewContextAnswer +} export interface ReviewTaskContext { taskId: Uuid requestId: Uuid @@ -337,6 +392,7 @@ export interface ReviewTaskContext { policyClosure: ReviewPolicyClosure resultConstraints?: JsonObject context: ReviewTaskContextData + asks?: ReadonlyArray } export type ReviewClockCorrelation = | { scope: 'subject'; source: string; subjectType: string; id: string } @@ -346,7 +402,7 @@ export interface ReviewClockOccurrence { clockId: string requestId: Uuid correlation: ReviewClockCorrelation - state: 'running' | 'completed' | 'cancelled' | 'source-facts-missing' + state: 'running' | 'paused' | 'completed' | 'cancelled' | 'source-facts-missing' policyDigest: ContentDigest anchorAt: string dueAt?: string @@ -370,14 +426,16 @@ export interface ReviewAccountabilityRecord { occurredAt: string; retainedUntil: string decisionReceipt?: ReviewDecisionReceipt } -export interface ReviewStagePolicy { id: string; label?: string; publicProgressCode?: string; queue: string; decidingProfiles: ReadonlyArray; requiredApprovals: SafeInteger; outcomes?: ReadonlyArray; negativeDecisions?: 'settle' | 'advise'; excludeInitiator?: boolean; excludePreviousStageReviewers?: boolean } +export interface ReviewStageAsksPolicy { answerWithin?: ElapsedDuration; onDue?: 'return-to-reviewer'; pauseClocks?: boolean } +export interface ReviewStagePolicy { id: string; label?: string; publicProgressCode?: string; queue: string; decidingProfiles: ReadonlyArray; requiredApprovals: SafeInteger; outcomes?: ReadonlyArray; negativeDecisions?: 'settle' | 'advise'; asks?: ReviewStageAsksPolicy; excludeInitiator?: boolean; excludePreviousStageReviewers?: boolean } export interface ReviewRetentionPolicy { terminalRetentionDays: SafeInteger; accountabilityRetentionDays: SafeInteger } export interface ReviewContextContract { id: string; revision: ContentDigest; schemaDigest: ContentDigest } export type ReviewContextPolicy = { mode: 'submitted' } | { mode: 'current-source'; provider: string; contract: ReviewContextContract } export type ReviewContextCapability = 'human-display' | 'service-status' | 'task-grant-context' | 'routing-context' export interface ReviewContextProviderPolicy { id: string; capabilities: ReadonlyArray; sourceNamespace: string; deploymentRef: string; serviceProfiles?: Partial> } -export interface ReviewPolicy { id: string; label?: string; version: string; purpose: 'approval' | 'answer'; context: ReviewContextPolicy; routing?: ReadonlyArray; stages: ReadonlyArray; clocks?: ReadonlyArray; retention: ReviewRetentionPolicy; displaySchema: JsonValue; resultSchema?: JsonValue; outcomes?: ReadonlyArray<{ id: string; label: string; settlement: 'approved' | 'rejected' | 'changes-requested' | 'answered'; reasonRequired: boolean; publicReason: 'required' | 'optional' | 'none'; resultRequired?: boolean }> } +export interface ReviewPolicy { id: string; label?: string; version: string; purpose: 'approval' | 'answer'; resubmission?: 'first-stage' | 'resume-at-returning-stage'; context: ReviewContextPolicy; routing?: ReadonlyArray; stages: ReadonlyArray; clocks?: ReadonlyArray; retention: ReviewRetentionPolicy; displaySchema: JsonValue; resultSchema?: JsonValue; outcomes?: ReadonlyArray<{ id: string; label: string; settlement: 'approved' | 'rejected' | 'changes-requested' | 'answered'; reasonRequired: boolean; publicReason: 'required' | 'optional' | 'none'; resultRequired?: boolean }> } export interface ReviewPolicyClosure { + resubmission?: 'first-stage' | 'resume-at-returning-stage' identity: PolicyBinding label?: string purpose: 'approval' | 'answer' @@ -423,6 +481,7 @@ export class CaseworkClient { reviewTaskDraft(token: string, profile: string, taskId: Uuid, sourceProfile?: string, sourceCredential?: HumanSourceCredential | null): Promise> saveReviewTaskDraft(token: string, profile: string, taskId: Uuid, expectedRevision: SafeInteger, idempotencyKey: string, draft: ReviewTaskDraftInput, sourceProfile?: string, sourceCredential?: HumanSourceCredential | null): Promise> deleteReviewTaskDraft(token: string, profile: string, taskId: Uuid, expectedRevision: SafeInteger, idempotencyKey: string, sourceProfile?: string, sourceCredential?: HumanSourceCredential | null): Promise> + askApplicant(token: string, profile: string, taskId: Uuid, expectedRevision: SafeInteger, idempotencyKey: string, ask: ReviewTaskAskRequest, sourceProfile?: string | null, sourceCredential?: HumanSourceCredential | null): Promise> decideReviewTask(token: string, profile: string, taskId: Uuid, expectedRevision: SafeInteger, idempotencyKey: string, decision: ReviewTaskDecisionRequest, sourceProfile?: string | null, sourceCredential?: HumanSourceCredential | null): Promise> reviewHistory(token: string, profile: string, requestId: Uuid, query?: ReviewPageQuery | null, sourceProfile?: string | null, sourceCredential?: HumanSourceCredential | null): Promise> addReviewNote(token: string, profile: string, requestId: Uuid, idempotencyKey: string, note: ReviewNoteRequest, sourceProfile?: string | null, sourceCredential?: HumanSourceCredential | null): Promise> diff --git a/crates/registry-stack-client-node/casework/client.js b/crates/registry-stack-client-node/casework/client.js index b77a9d875d..a278b99483 100644 --- a/crates/registry-stack-client-node/casework/client.js +++ b/crates/registry-stack-client-node/casework/client.js @@ -165,7 +165,7 @@ function humanSourceCredentialValue(value) { return source; } -const sourceCredentialIndexes = new Map([["nextReviewTask", 4], ["reviewTasks", 4], ["supervisoryReviewTasks", 4], ["ownReviewDecisions", 4], ["reviewTask", 4], ["reviewTaskContext", 4], ["approveReviewTaskGrant", 7], ["claimReviewTask", 6], ["assignReviewTask", 7], ["delegateReviewTask", 7], ["reviewTaskDraft", 4], ["saveReviewTaskDraft", 7], ["deleteReviewTaskDraft", 6], ["decideReviewTask", 7], ["reviewHistory", 5], ["addReviewNote", 6], ["reviewClocks", 4], ["reviewTaskHoldings", 4], ["previewClockRecompute", 3], ["applyClockRecompute", 4], ["previewCaseloadMove", 4], ["applyCaseloadMove", 5]]); +const sourceCredentialIndexes = new Map([["nextReviewTask", 4], ["reviewTasks", 4], ["supervisoryReviewTasks", 4], ["ownReviewDecisions", 4], ["reviewTask", 4], ["reviewTaskContext", 4], ["approveReviewTaskGrant", 7], ["claimReviewTask", 6], ["assignReviewTask", 7], ["delegateReviewTask", 7], ["reviewTaskDraft", 4], ["saveReviewTaskDraft", 7], ["deleteReviewTaskDraft", 6], ["decideReviewTask", 7], ["askApplicant", 7], ["reviewHistory", 5], ["addReviewNote", 6], ["reviewClocks", 4], ["reviewTaskHoldings", 4], ["previewClockRecompute", 3], ["applyClockRecompute", 4], ["previewCaseloadMove", 4], ["applyCaseloadMove", 5]]); for (const [method, jsonIndexes] of [ ['description', []], ['createOrRecoverReviewRequest', [3]], @@ -192,6 +192,7 @@ for (const [method, jsonIndexes] of [ ['saveReviewTaskDraft', [5]], ['deleteReviewTaskDraft', []], ['decideReviewTask', [5]], + ['askApplicant', [5]], ['reviewHistory', [3]], ['addReviewNote', [4]], ['reviewClocks', []], diff --git a/crates/registry-stack-client-node/casework/index.d.ts b/crates/registry-stack-client-node/casework/index.d.ts index 99cc8e6605..575e9137ad 100644 --- a/crates/registry-stack-client-node/casework/index.d.ts +++ b/crates/registry-stack-client-node/casework/index.d.ts @@ -30,6 +30,7 @@ export declare class CaseworkClient { reviewTaskDraft(token: string, profile: string, taskId: string, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise saveReviewTaskDraft(token: string, profile: string, taskId: string, expectedRevision: number, idempotencyKey: string, draft: any, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise deleteReviewTaskDraft(token: string, profile: string, taskId: string, expectedRevision: number, idempotencyKey: string, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise + askApplicant(token: string, profile: string, taskId: string, expectedRevision: number, idempotencyKey: string, ask: any, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise decideReviewTask(token: string, profile: string, taskId: string, expectedRevision: number, idempotencyKey: string, decision: any, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise reviewHistory(token: string, profile: string, requestId: string, query?: any | undefined | null, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise addReviewNote(token: string, profile: string, requestId: string, idempotencyKey: string, note: any, sourceProfile?: string | undefined | null, sourceCredential?: HumanSourceCredential | undefined | null): Promise diff --git a/crates/registry-stack-client/src/lib.rs b/crates/registry-stack-client/src/lib.rs index 7135bf53be..2ff73222b8 100644 --- a/crates/registry-stack-client/src/lib.rs +++ b/crates/registry-stack-client/src/lib.rs @@ -19,18 +19,21 @@ pub mod breg { BRegLookupRequest, BRegMetadata, BRegMetadataOperation, BRegMetadataSelectionError, BRegMutationRequestError, BRegOperationKind, BRegPage, BRegPatchBinding, BRegPatchBuilder, BRegPatchRequest, BRegPreparedAction, BRegPreparedCreate, BRegPreparedProposal, - BRegProbeStatus, BRegProblemCode, BRegProposal, BRegProposalApplication, - BRegProposalAttachment, BRegProposalAttachmentValue, BRegProposalCollection, - BRegProposalDecision, BRegProposalDecisionStatus, BRegProposalGetBinding, BRegProposalLink, - BRegProposalPage, BRegProposalQuery, BRegProposalResultReference, - BRegProposalReviewBinding, BRegProposalReviewContext, BRegProposalReviewDocument, - BRegProposalReviewHandoff, BRegProposalReviewHandoffReason, BRegProposalReviewHandoffState, - BRegProposalReviewResult, BRegProposalReviewSubject, BRegProposalState, - BRegProposalSubmission, BRegProposalSubmissionApplication, BRegProposalTurn, - BRegProtocolFailure, BRegRawDocument, BRegRecordFormat, BRegRecordOptions, - BRegRecoveryHint, BRegRequestError, BRegResponseMetadata, BRegVerifiedHookDelivery, - BaseRegistryClient, BaseRegistryClientConfig, BaseRegistryClientError, PolicySelection, - ReviewProgressCode, Uuid, EVENT_RECORD_DESCRIPTOR_VERSION, EVENT_RECORD_VIEW_CONTRACT, + BRegProbeStatus, BRegProblemCode, BRegProposal, BRegProposalAnswerRequest, + BRegProposalApplication, BRegProposalAsk, BRegProposalAskAnswer, BRegProposalAskState, + BRegProposalAskWant, BRegProposalAttachment, BRegProposalAttachmentValue, + BRegProposalCollection, BRegProposalDecision, BRegProposalDecisionStatus, + BRegProposalGetBinding, BRegProposalLink, BRegProposalPage, BRegProposalQuery, + BRegProposalResultReference, BRegProposalReviewAnswer, BRegProposalReviewAnswerDocument, + BRegProposalReviewAnswerDownload, BRegProposalReviewAsk, BRegProposalReviewBinding, + BRegProposalReviewContext, BRegProposalReviewDocument, BRegProposalReviewHandoff, + BRegProposalReviewHandoffReason, BRegProposalReviewHandoffState, BRegProposalReviewResult, + BRegProposalReviewSubject, BRegProposalState, BRegProposalStatus, BRegProposalSubmission, + BRegProposalSubmissionApplication, BRegProposalTurn, BRegProtocolFailure, BRegRawDocument, + BRegRecordFormat, BRegRecordOptions, BRegRecoveryHint, BRegRequestError, + BRegResponseMetadata, BRegVerifiedHookDelivery, BaseRegistryClient, + BaseRegistryClientConfig, BaseRegistryClientError, PolicySelection, ReviewProgressCode, + Uuid, EVENT_RECORD_DESCRIPTOR_VERSION, EVENT_RECORD_VIEW_CONTRACT, }; } @@ -49,21 +52,24 @@ pub mod casework { HolidaySetRevisionInput, HumanIdentity, HumanSourceCredential, IssuerPrincipal, OneOfPredicate, OwnReviewDecision, OwnReviewDecisionPage, OwnReviewDecisionQuery, Page, PageStatus, PolicyBinding, PolicySelection, QueueRecord, ReviewAccountabilityRecord, - ReviewCancelRequest, ReviewCancelResponse, ReviewCaseloadApplyRequest, + ReviewAnswerDocument, ReviewAnswerDownload, ReviewAsk, ReviewAskOnDue, ReviewAskState, + ReviewAskWant, ReviewCancelRequest, ReviewCancelResponse, ReviewCaseloadApplyRequest, ReviewCaseloadMoveRequest, ReviewCaseloadPreview, ReviewCaseloadResult, ReviewCaseloadTask, ReviewClockOccurrence, ReviewClockRecomputeApplyRequest, ReviewClockRecomputePreview, ReviewClockRecomputeRequest, ReviewClockRecomputeResult, ReviewClockRecomputeTask, - ReviewCompletion, ReviewCompletionType, ReviewContext, ReviewContextCapability, - ReviewContextContract, ReviewContextPolicy, ReviewContextProviderPolicy, - ReviewCreateRequest, ReviewDecisionReceipt, ReviewDecisionType, ReviewHistoryAudience, - ReviewHistoryEntry, ReviewHistoryPage, ReviewMutationErrorClass, - ReviewNegativeDecisionMode, ReviewNoteRequest, ReviewPageQuery, ReviewPolicy, - ReviewPolicyClosure, ReviewPolicyDependencies, ReviewProgressCode, ReviewPurpose, - ReviewRequestAccepted, ReviewRequestLifecycle, ReviewRequestView, ReviewResult, - ReviewResultFeedEntry, ReviewResultFeedPage, ReviewResultObservation, ReviewResultResponse, - ReviewResultStatus, ReviewSourceBindingStatus, ReviewSourceProjection, ReviewStaffingQuery, - ReviewStagePolicy, ReviewTask, ReviewTaskContext, ReviewTaskContextData, - ReviewTaskDecisionRequest, ReviewTaskDraft, ReviewTaskDraftInput, ReviewTaskOwnership, + ReviewClockState, ReviewCompletion, ReviewCompletionType, ReviewContext, + ReviewContextAnswer, ReviewContextAsk, ReviewContextCapability, ReviewContextContract, + ReviewContextPolicy, ReviewContextProviderPolicy, ReviewCreateRequest, + ReviewDecisionReceipt, ReviewDecisionType, ReviewHistoryAudience, ReviewHistoryEntry, + ReviewHistoryPage, ReviewMutationErrorClass, ReviewNegativeDecisionMode, ReviewNoteRequest, + ReviewPageQuery, ReviewPolicy, ReviewPolicyClosure, ReviewPolicyDependencies, + ReviewProgressCode, ReviewPurpose, ReviewRequestAccepted, ReviewRequestLifecycle, + ReviewRequestView, ReviewResubmissionPolicy, ReviewResult, ReviewResultFeedEntry, + ReviewResultFeedPage, ReviewResultObservation, ReviewResultResponse, ReviewResultStatus, + ReviewSourceBindingStatus, ReviewSourceProjection, ReviewStaffingQuery, + ReviewStageAsksPolicy, ReviewStagePolicy, ReviewTask, ReviewTaskAskRequest, + ReviewTaskAsked, ReviewTaskContext, ReviewTaskContextData, ReviewTaskDecisionRequest, + ReviewTaskDraft, ReviewTaskDraftInput, ReviewTaskMarker, ReviewTaskOwnership, ReviewTaskPage, ReviewTaskSort, ReviewTaskState, ReviewValidationError, ReviewValidationReason, RoutingCondition, RoutingPredicate, RoutingRule, SchedulingTaskPermission, SourceContextBinding, StaffingDiagnostic, StageClockAnchor, diff --git a/docs/site/src/content/docs/configure/breg-proposals.mdx b/docs/site/src/content/docs/configure/breg-proposals.mdx index 3c8e6ee239..0eabb6f630 100644 --- a/docs/site/src/content/docs/configure/breg-proposals.mdx +++ b/docs/site/src/content/docs/configure/breg-proposals.mdx @@ -123,7 +123,7 @@ Any required Evidence is resolved under explicit operator trust and the Action's Profiles declare `permissions.records`, `permissions.actions`, and `permissions.proposals` independently. Start authorises creation of a draft. -Proposal Get, List, Edit, Submit, Revise, Rebase, Retry, Cancel, and Apply each need their own grant. +Proposal Get, List, Edit, Submit, Revise, Rebase, Retry, Cancel, Apply, Add, and Answer each need their own grant. `get-application-actor` is a supplemental disclosure grant and must appear with Get in the same Proposal grant. List requires List authority and conceals other owners' and jurisdictions' work before filters or counts. Record and changes projections in review context also require current Record disclosure. @@ -146,6 +146,13 @@ The list must name declared inputs and needs Start, Edit, Revise or Rebase autho When the grant holds Edit, Revise or Rebase, every input outside the list must be in `readableInputs`, so the equality check never reveals a value the caller cannot read. Attachments keep their own `writableAttachments` grant. +A grant that holds Edit, Revise or Rebase must also read every input it may write: `readableInputs` has to cover `writableInputs`, or every declared input when `writableInputs` is absent. +Get and List serve `input` projected to `readableInputs`, while a write replaces the stored input as a whole, so a client that merges its change into what it read would otherwise clear the inputs it could not see. +With the rule for inputs outside `writableInputs` above, such a grant reads every declared input, whatever `writableInputs` names. +`readableInputs` requires Get, so a grant that holds Edit, Revise or Rebase without `get` must add it. +The compiler refuses the grant with `breg.proposal.input-write-unreadable`, naming the access profile, the Action and the missing inputs. +An agent profile without a task grant cannot hold Get, drafts blind and is exempt. + For an Action whose inputs are `holder`, `statement` and `licence-number`, an applicant may write the first two while an officer, under a grant without the list, records the licence number: ```yaml @@ -315,10 +322,16 @@ Observation cannot establish whether an earlier uncertain Start or Submit execut Under required Review it reads `awaiting-review` until an approved result exists, then `pending`, `applying`, `blocked`, `applied`, `cancelled` or `rejected`. Its `application-refused` reason means an executor refused the frozen effects; a review outcome never appears there. +{/* Evidence: crates/registry-breg/src/mutation.rs ApplicationRefusal; + crates/registry-breg/tests/postgres_proposal.rs manual_apply_unique_conflict_and_stale_revision_offer_party_recovery, admitted_apply_outside_the_callers_write_boundary_persists_nothing; + crates/registry-breg/tests/postgres_proposal_guard_failure.rs apply_names_a_failed_field_guard_and_keeps_stale_revisions_generic. */} + A unique-constraint failure during manual Apply returns `409 mutation.conflict` without retaining any Record effects. -Subsequent reads report `applicationStatus.state: blocked`, `reason: application-refused`, and `recovery: correct-input`. -Apply is unavailable; Rebase remains available to correct the input and prepare a fresh submission. -A stale Record revision instead returns `412 precondition.failed` without creating that application block. +Subsequent reads report `applicationStatus.state: blocked`, `reason: application-refused`, and `recovery: revise`. +Apply is unavailable. Revise can correct the input, and Rebase can inspect the current target and prepare a fresh submission. +A stale Record revision returns `412 precondition.failed` and records the same application block with `recovery: rebase`. +A failed frozen field guard also needs Rebase. A frozen write that would leave the applying caller's row boundary answers `403 write.outside-boundary` and records nothing. +The boundary belongs to that caller, so the Proposal stays as it was and a caller whose boundary covers the result can still Apply. Read the current Proposal before choosing the next authorised operation. Submit and Apply check the Action's field commit guards against the current target Record. @@ -348,6 +361,45 @@ When Revise is the recovery, the Retry link reports the same reason instead of ` crates/registry-breg/src/problem.rs action.guard_failed; crates/registry-breg/src/review_store.rs review-ended. */} +### Complete required attachment slots + +Upload a file into each required attachment slot before submitting the Proposal. +BReg makes the Submit link unavailable while any required slot is empty. +The link names `attachment-required` with recovery `correct-input`. +BReg checks storage even when your profile may upload to a slot but cannot read its value. +A profile can hold Submit without permission to write a required slot. +Different people can fill the slot and submit the Proposal. A missing-file +problem tells the submitter only the slot's ID, without file metadata. + +A direct Submit request with an empty required slot answers `422 attachment.required`. +Its `fieldPath` names the slot, such as `/attachments/supporting-document`. +Upload the missing file and read the updated Proposal. +Follow the Submit link when it becomes available. +You do not need to infer availability from attachment values. +An upload with the wrong media type answers `415 attachment.content-type`. +A file larger than its slot's limit answers `413 attachment.too-large`. + +A required file rejected by verification counts as empty. +While verification is pending, Submit is unavailable with `attachment-pending` +and recovery `refresh`. A direct call answers `409 attachment.verification-pending`. +Refresh the Proposal until verification finishes. +A rejected file in an optional slot makes Submit unavailable with `invalid-input` +and recovery `correct-input`. A direct call answers `422 attachment.verification-rejected`. +Replace or remove that file before submitting. These problems identify only +the slot in `fieldPath`, including when you cannot read its metadata. +With several empty required slots, the response identifies the first in +compiled slot order. Correct that slot and read the Proposal again. + +{/* Evidence: crates/registry-breg/tests/support/proposal_required_attachment.rs + submit_names_an_empty_required_attachment_and_recovers_after_upload, + submit_checks_required_attachments_the_writer_cannot_read, + submit_and_link_agree_for_pending_verification, + submit_and_link_treat_a_rejected_required_file_as_empty, + submit_and_link_name_a_rejected_optional_file_without_metadata, + submit_without_slot_write_authority_names_the_first_empty_slot_only, + required_file_precedes_plan_evaluation, slot_upload_names_media_and_size_refusals; + crates/registry-breg/src/problem.rs AttachmentRequired, AttachmentVerificationPending, AttachmentVerificationRejected. */} + ### Whose turn it is Every Proposal document and lifecycle event carries a derived `turn`: @@ -356,11 +408,28 @@ Every Proposal document and lifecycle event carries a derived `turn`: - `official`: a reviewer or applier acts next. Review in progress or being retried, an approved or review-free manual submission awaiting Apply, and an automatic application blocked on a dependency outage are an official's turn. - `nobody`: no one needs to act. The Proposal is `applied`, `cancelled` or `rejected`, or its automatic application is queued or running. -`turn` is derived from the lifecycle state, the current submission's review progress and its application status when the Proposal is read; nothing stores it. +Proposal Get, list items and command responses also serve a derived `status` whenever the caller has claims, including for a draft: + +- `draft`: not yet submitted. +- `awaiting-party`: submitted and the party must act next, for example after a send-back, an ended review or a package or application block. +- `in-review`: with the review provider, with no open ask. +- `approved`: approved by review, with the change not yet in force. +- `processing`: submitted under an Action with no review, with the change not yet in force. +- `applied`: the change is in force. +- `rejected`: refused by review. +- `cancelled`: cancelled without applying the change. + +`status` and `turn` come from one pure rule over the lifecycle state, the current submission's review progress and its application status. Nothing stores either value. +Lifecycle events carry `turn` but do not carry `status`. An older retained command receipt can replay without `status`. +`bregctl explain lifecycle` lists each state's possible statuses and turns with their conditions in its `v1alpha9` explanation format. It says whose move the work waits on, not who is authorised to make it: the links still decide what the current caller may do. List Proposals by turn with `GET /v1/proposals?turn=party` (or `official`, `nobody`). +There is no `status` query filter. A page may hold fewer than `limit` items, so keep paging while `nextCursor` is present. +{/* Evidence: crates/registry-breg/src/lifecycle.rs proposal_status_and_turn_follow_the_exhaustive_lifecycle_table; + crates/registry-breg/tests/support/proposal_status.rs proposal_status_is_served_on_draft_review_approval_and_application. */} + Every Proposal document carries `createdAt`, the UTC time its draft was started (RFC 3339, microsecond precision). It does not change when the Proposal is submitted, revised or applied, so it orders attempts on the same target chronologically; the list itself is ordered by Proposal id, not by time. A command receipt stored before this member was served replays without it. @@ -417,7 +486,7 @@ Any other result leaves the Proposal `submitted` until it is applied or cancelle ### The decision -Proposal Get, each Proposal in a list, and the per-version submission read carry `decision` once the reviewer decided the submission: +Proposal Get, each Proposal in a list, the per-version submission read and, under Get authority, each command response carry `decision` once the reviewer decided the submission: ```json "decision": { @@ -431,14 +500,25 @@ Proposal Get, each Proposal in a list, and the per-version submission read carry `publicReason` appears only when the reviewer wrote one for the subject; it is the only reviewer text BReg serves. Notes, internal reasons and the reviewer's identity stay with the review provider. A provider-side end (`cancelled`, `superseded`) is not a decision and has no `decision`; neither has a result whose content retention erased. -A lifecycle command's response omits `decision`: read the Proposal to see it. -Each read that serves a public reason records a fixed `proposal-review-public-reason` marker in its audit entry, never the text. - -Revise after an approved, not yet applied, manual submission discards the approval. -The approval binds the earlier version only, and the revised version needs its own Review before it can be applied. -Apply first if the approved change must take effect. - -Cancel, and Revise or Rebase of a submitted Proposal, close the Proposal's queued, applying or blocked automatic application job in the same transaction. +Every Proposal command response, and each attachment upload or removal, carries `decision` and `input` exactly as a Get by the same caller would right after the command, so a client need not read the Proposal again. +A profile that may run a command but holds no Get grant on the Proposal gets neither, because command authority is not read authority. +A replay with the same `Idempotency-Key` returns the stored response of the first execution, not the Proposal's current state. +A command receipt stored before this release replays without `decision` and `input`. +A later package that narrows the grant's `readableInputs` makes an earlier key conflict instead of replaying an input a Get now withholds. +Each response that serves a public reason, a read, a command or a replay, records a fixed `proposal-review-public-reason` marker in its audit entry, never the text. + +Revise and Rebase of a submitted Proposal are available only at `awaiting-party` or `in-review`, subject to their other authority and package checks. +At `approved` or `processing`, both links are unavailable with `application-pending` and recovery `refresh`, and both commands answer 412. +Apply the current submission or Cancel it. If an admitted Apply fails because the target revision changed or a frozen field guard failed, BReg records a blocked application with recovery `rebase`. +A unique constraint conflict records recovery `revise`, so the party can correct its inputs. +A result outside the applying caller's row boundary records nothing: that caller is refused and the Proposal stays approved for a caller whose boundary covers it. +These blocks return the Proposal to `awaiting-party`, where Revise and Rebase can open a draft for a new submission. +An expired approval also returns the turn to the party and allows a new draft. +Deleted targets and targets outside the caller's current row boundary stay concealed. They do not create a recovery block or make the Proposal visible. +Rebase of a draft is unchanged. A revised or rebased version needs its own Review when the Action requires one. + +Cancel closes the Proposal's queued, applying or blocked automatic application job in the same transaction. +An allowed Revise or Rebase also closes the old submission's job. Queued or running work at `approved` or `processing` cannot be revised or rebased. The job reads `cancelled`; it never applies a superseded version. {/* Evidence: crates/registry-breg/tests/postgres_proposal.rs proposal-review-public-reason; @@ -461,7 +541,7 @@ The Proposal stays submitted and its authorised requester can still Rebase or Ca This includes an approved result received after withdrawal when no application job exists: Get, List and turn filtering keep the Proposal recoverable, while its retained decision remains historical evidence. Manual rounds also return the turn to the requester and refuse Apply after a restoring package clears the block. -A Proposal blocked by a refused manual Apply (`application-refused`) keeps that reason through every package activation; only Rebase clears it. +A Proposal blocked by a refused manual Apply (`application-refused`) keeps its refusal and recovery through every package activation. An authorised Revise or Rebase clears the block when it opens the next draft. A compatible activation leaves the block, its Review and its Apply refusal in place. An activation that changes the Action withdraws the Review as described but keeps `application-refused` as the reason, and a later restoring package neither clears the refusal nor reopens the withdrawn round. @@ -642,6 +722,165 @@ The facility template combines supporting-document display with current Record a {/* Evidence: crates/registry-breg/tests/postgres_facility_proposal.rs supporting-document; crates/registry-breg/src/compiler/review_context.rs review_context. */} +## Accept supporting files during review + +Declare `additions` when your applicant or an authorised officer needs to supply files after Submit. +Configure required review before declaring this slot. +BReg refuses an additions slot with `review.type: none` (`breg.addition.review-required`). +BReg keeps these files beside the current submission. +An addition changes the Proposal revision and ETag while preserving its submission version and frozen effect digest. + +```yaml +execution: + mode: proposal + proposal: + additions: + id: other-documents + contentTypes: [application/pdf] + maximumBytes: 1048576 + maximumCount: 8 + classification: restricted +``` + +You can declare one additions slot with a limit of 1 to 32 files per submission. +Give it an ID distinct from every attachment slot. +The byte and media-type rules match attachment slots. +Each accepted file consumes one place for that submission. +This release offers no operation to remove an addition. +BReg trusts the declared media type as it does for other attachments. +Downloads use `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`. + +Declaring or changing the slot changes the Action revision. +An existing submitted Proposal needs Rebase, then Submit, before the changed slot accepts files. +BReg withdraws the previous review and starts review for the rebased submission. + +Grant `add` and list the slot in `writableAttachments` to allow uploads. +Grant `get` and list it in `readableAttachments` to disclose its files and download links. +These grants remain independent. +BReg records the authenticated actor who added each file. + +Follow `additions..links.add` and send the file as the raw request body. +Use the declared media type and the link's `ifMatch` value. +Choose an idempotency key and retain the exact request for uncertain-outcome recovery. +The response contains the full Proposal and its changed ETag. +Refetch before adding another file from a second tab. + +BReg accepts additions only while the current submission's review is pending or retrying. +BReg closes the slot when review ends or the Proposal leaves `submitted`. +A blocked Proposal also refuses additions. +The descriptor retains an unavailable Add link when you have write authority. +At the file limit, its reason is `limit-reached` and its recovery is `receipt-only`. + +To show the files to your reviewer, declare a review-context field: + +```yaml +reviewContext: + id: supporting-review + fields: + otherDocuments: + type: additions + slot: other-documents +``` + +BReg serves an array of verified document descriptors for the bound submission. +Each download link uses the reviewer's own authority and carries the exact review-context binding. +Additions follow Proposal detail retention and share attachment byte verification and cleanup. +Revise starts a submission version with no additions. +Use the `added` hook transition to observe the value-free `proposal.added` event. +Proposal hooks without a `transitions` filter also receive `added`, `asked` and `answered`. +Configure an explicit transition filter if your receiver cannot accept those events. + +{/* Evidence: crates/registry-breg/src/contract.rs AdditionSlotSource; + crates/registry-breg/src/immediate_actions.rs breg.addition.review-required, definition_revision; + crates/registry-breg/src/api/attachments.rs; + crates/registry-breg/src/mutation/proposal/additions.rs append_additions; + crates/registry-breg/src/mutation/proposal/context_projection.rs; + crates/registry-breg/src/proposal_hooks.rs matching_transitions; + crates/registry-breg/tests/support/proposal_additions.rs; + crates/registry-breg/src/proposal_retention.rs. */} + +## Answer a reviewer's ask + +A reviewer can ask for an explanation, supporting files, or both while the review stays open. +BReg learns of asks by polling the review authority within its configured worker cadence. +The Proposal's `asks` array shows the current submission's questions newest first, with their wants, absolute `askedAt` and optional `dueAt`, state and answer link. +Each submission version retains at most 50 asks. BReg skips and counts further distinct announcements. +An announcement that arrives before BReg records acceptance waits as value-free identifiers and time until BReg can match the review request. +It expires within the submission recovery window without retaining question text. +The `asks` member, on Get, list items and command responses, goes only to a caller who may answer on this Proposal: the selected profile holds Get and `answer` for it, and the caller passes the same human test as review answers below. +Every other caller gets no `asks` member at all: another Get holder, a status profile, a standing or task-granted agent, a delegated actor and a service. +Status and turn still show them that an ask is open. +An open, unanswered ask changes the same derived status and turn to `awaiting-party` and `party`. +After the local answer commits, they return to `in-review` and `official` when review remains pending. + +Grant `answer` in the applicant profile's Proposal operations. +Only a verified human caller acting for no one else, under no task grant, on a profile written for humans or for any kind, may answer. Any other caller is refused, whatever its grant says. +If the ask wants documents, also grant `add` with the additions slot in `writableAttachments`, as described above. +Follow the ask's promoted `links.answer` with the current `If-Match` and a caller-chosen `Idempotency-Key`: + +```http +POST /v1/proposals/{proposal_id}/asks/{ask_id}/answer?accessProfile=applicant +Content-Type: application/json +If-Match: "" +Idempotency-Key: + +{"text":"The explanation","additions":[""]} +``` + +`text` is required for an `answer` want, must be nonblank and is bounded to 2,000 UTF-8 bytes. +A `document` want requires at least one addition ID from the current submission that no other answer cites. +An uncited file already on the submission can satisfy it, even when the additions slot is full. +The list holds at most 32 distinct IDs. Unknown body members are refused. +Every answer needs text or at least one cited file, even when the ask has no wants. +Use `request.invalid` and its `fieldPath` to correct the body. +The successful response is the full caller-filtered Proposal with a new ETag, unchanged submission version and unchanged frozen effects. +Resending the same key and request returns the stored response. Changing the body with that key conflicts. + +Page authors must tell applicants before they answer: + +> Your answer and any file you attach go to the reviewers of this application. + +Answering discloses the answer and its cited files to reviewers of this review even when the Action declares no additions context field. +BReg serves them live in the reserved `context.asks` sibling beside authored `context.fields`. +Casework joins validated answers onto its own asks by ask ID and does not store their text or file descriptors. +Only human reviewers receive answers. A reviewer uses their own review-context authority and token. +Agents, standing or task-granted, delegated reads and services receive neither asks nor answers, even with a `get-review-context` grant, and get no ask-bound download. +A file they can reach through an authored additions context field follows that field's grant as before. +The batch review-context read used for inboxes carries no asks. +The single review-context route includes them only with `include=answers`, which the BReg client's display read supplies. +Casework omits that option for claim, ask and decide preflight, so those reads neither disclose answers nor audit an answer disclosure. +A cited file is not limited by the reviewer's readable context fields, because it is admitted in place of an authored additions field. +A cited file's download remains bound to the current review request, submission version, frozen effect and context schema, and its bytes must pass verification. +A file not cited by an answer still needs an authored additions context field. + +The answer link becomes unavailable with `ask-answered`, `ask-closed` or `ask-due-passed`, each with recovery `receipt-only`. +Shared lifecycle refusals still apply. Availability is an observation, so refetch after a refusal. +The due date is absolute from the provider's ask, not from when BReg polls it. +Closing or expiring an ask through the feed advances the Proposal revision and ETag once. +The clock passing `dueAt` changes answer-link availability without changing the ETag. Pages must check the link's current availability before answering. +BReg refuses answers after that date by its own clock. The provider judges an answer by its stored `answeredAt`. +An on-time answer can therefore be delivered after the provider has marked the ask expired. +BReg rounds a higher-precision ask time up to a microsecond and uses the later of that instant and its own commit clock for `answeredAt`. + +The worker sends the provider only the frozen subject and stored answer time, using BReg's producer credential. +Answer text and files stay in BReg. +Transient failures retry with the same key and timestamp until this answer's recovery deadline, measured from `answeredAt`. +A deterministic refusal ends delivery and preserves the local answer. `review.ask-not-open` records that the provider no longer accepts it. +Keep BReg and Casework clocks synchronized within five minutes: a future `answeredAt` beyond that tolerance is permanently refused as `review.ask-answer-time-invalid` and raises `review.result_lookups.unavailable`. +Revise, Rebase and Cancel close open asks and supersede pending deliveries for that submission. +The `asked` and `answered` hook transitions carry value-free lifecycle events. +Question disclosure and ask-bound downloads are audited, and the answer audit records only cited file IDs. +Answers and added files follow the Action's `retention` mode and are erased per submission version by operator erasure. +Separately, review maintenance prunes value-free feed deduplication receipts after the authority's recovery window, measured from observation. +A feed cursor reset checks stored asks before fetching them again, including after those receipts expire. + +{/* Evidence: crates/registry-breg/tests/support/proposal_review_asks.rs + asks_reach_only_a_human_caller_who_may_answer_this_proposal, + a_human_reviewer_without_answer_reads_answers_only_through_the_review_context; + crates/registry-breg/src/review_store/asks.rs answer_time; + crates/registry-breg/src/review_store/asks/delivery.rs; + crates/registry-casework/src/review/source_answers.rs. */} + ## Keep a supporting document on the record A Proposal file can stay with the record that the Proposal writes. @@ -718,6 +957,7 @@ Expired or erased receipts cannot execute again. ### Bounded review-context reads A caller with the existing `get-review-context` grant can request up to 100 distinct canonical Proposal UUIDs in one exchange: `GET /v1/proposals/review-context?accessProfile=&ids=,`. +Batch items never carry `context.asks`. The ordered `items` contain the requested `id` and either `status: visible` with the ordinary `context` document, or `status: concealed` with no document. Unknown and currently unauthorised Proposals have the same concealed result. Every item retains its own current Proposal and Record disclosure checks, transaction, and paired audit entries. diff --git a/docs/site/src/content/docs/configure/casework.mdx b/docs/site/src/content/docs/configure/casework.mdx index a9ee1dcc69..dfea7e8621 100644 --- a/docs/site/src/content/docs/configure/casework.mdx +++ b/docs/site/src/content/docs/configure/casework.mdx @@ -458,7 +458,27 @@ Omitting the field offers every policy outcome. `caseworkctl explain` always reports the effective outcomes for each stage, including the all-policy default. A `changes-requested` result ends that review version. -A resubmission is a new version that starts at the policy's first stage; it does not resume the earlier review in place. +A resubmission creates a new request and starts at the first stage by default. +Set `resubmission: resume-at-returning-stage` on the review policy to start at the stage that requested changes. +Casework finds the same producer's latest earlier request, and resumes only if that request settled as `changes-requested`. +If the latest round was approved, rejected, cancelled, or is still open, the new request starts at the first stage. +The subject source, type, and ID must match. +Casework also requires the same policy ID. +Casework reads the stage of the decision that settled the earlier request. +Casework resumes only when the new policy revision has the same stage IDs, in the same order, as the earlier round for every stage up to and including the returning stage. +Otherwise, for example when a stage was removed or reordered at or below the returning stage, Casework starts at the first stage. +A revision that only adds or reorders stages above the returning stage still resumes. +Casework resumes within the earlier request's result retention, and starts a resubmission at the first stage after that. +Once any later request of the same producer and policy ID has been erased, Casework also starts at the first stage, because erasure removes the subject that would show whether that request was a later round. A later request whose records are already deleted cannot be detected. +The `review-resumed-at-stage` history detail carries only `stageId`, without linking to the earlier request. +Earlier approvals are not carried over. +The earlier stages do not see content that the resubmission changed: the producer may change any input on resubmission, and only the stages from the returning stage on review it. +A two-person control that needs every stage to see the final content must use the default, which starts at the first stage. +Use `resume-at-returning-stage` only where the earlier stages do not depend on what the applicant can change. +The staff who decided a stage of an earlier round, up to and including the returning stage, count as reviewers of that stage, so a later stage with `excludePreviousStageReviewers` keeps them out, as within one request, even after the earlier request is erased. +A reviewer of the returning stage may review that stage again. +The subject clock starts with a fresh budget. +Omitting `resubmission` preserves the policy digest. {/* Evidence: crates/registry-casework-core/src/review.rs ReviewNegativeDecisionMode; products/casework/examples/stage-outcomes/casework.yaml outcomes */} @@ -488,6 +508,115 @@ Neither refusal echoes the peer's header or source data. {/* Evidence: crates/registry-casework-breg/tests/support/peer_version.rs; crates/registry-casework/src/problem.rs source.version-mismatch */} +### Ask the applicant + +A reviewer who holds a task can ask the applicant for more before deciding. +Casework keeps the ask, and the producer shows it to the applicant and reports the answer. + +A stage opts in with `asks: {}`. +Only an approval policy can declare it, and a stage without `asks` behaves as before, with the same policy bytes and digest. +The producer must say it reads asks, with `readsAsks: true` on its `trustedProducers` entry. +`caseworkctl check` reports a policy with `asks` that a listed producer does not read. + +```yaml +reviewPolicies: + licence-renewal: + stages: + - id: review + queue: licensing + decidingProfiles: [licensing-officer] + requiredApprovals: 1 + asks: {} +trustedProducers: + licensing-registry: + readsAsks: true +``` + +The holder sends `POST /v1/review-tasks/{taskId}/asks` with `If-Match`, `Idempotency-Key` and a body of `text` and `wants`. +The text is plain, bounded like a public reason, and has no control characters. +`wants` lists what the applicant should give, from `answer` and `document`. +Casework refuses the ask when the caller does not hold the task, the request is no longer under review, the task is not at the active stage, the stage declares no `asks`, the producer does not read asks, or the request already has an open ask. +Each refusal has its own problem code: `review.ask-task-inactive`, `review.ask-not-offered`, `review.ask-producer-unsupported` and `review.ask-already-open`, besides `review.task-not-held` and the usual precondition failure. +Each review request allows at most 50 asks across all tasks and stages, including answered, expired and closed asks, and further attempts return `409 review.ask-limit-reached` without changing the request, task or clocks. +The task stays claimed by the same holder. + +The producer reads the ask on `GET /v1/review-asks`, a resumable feed of announcements, and then on `GET /v1/review-requests/{requestId}/asks/{askId}`. +It reports the answer with `POST /v1/review-requests/{requestId}/asks/{askId}/answer`, which carries the subject binding and the time the answer was committed. +It carries no text. +Only the producer that created the request can answer. +Casework returns an empty `404` for an unknown or foreign ask. +Casework returns `409 review.ask-not-open` for answered or closed asks and for answers given after `dueAt`. +The answer time must not precede the ask or lie more than five minutes ahead of Casework's clock, or Casework answers `review.ask-answer-time-invalid`. + +A task with an open ask carries the marker `waiting`, and the marker becomes `answered` when the producer reports the answer. +The marker stays with the task if the holder releases it or a supervisor reassigns it, so the next holder sees it. +`GET /v1/review-tasks` and the holdings list accept `marker=waiting`, `marker=answered`, or `marker=expired`. +The task context lists the request's asks with their text, wants, times, state and the task that asked. + +An ask closes when the task that holds it is decided, and every open ask closes when the request settles or is cancelled. +Asks and their feed announcements are erased with the request's history. + +Set `answerWithin` under `asks` to give the applicant an elapsed-time budget: + +```yaml +asks: + answerWithin: + hours: 48 + onDue: return-to-reviewer + pauseClocks: true +``` + +`answerWithin` accepts one unit: `minutes`, `hours`, or `days`, as elapsed clocks do. +Casework calculates the absolute `dueAt` from its own `askedAt` time. +Without `answerWithin`, the ask has no due date. +`onDue` defaults to `return-to-reviewer`, its only supported value. +After `dueAt`, clock maintenance expires an open ask and records `closedAt`. +Casework sets the task marker to `expired` and leaves the task with its holder. +Casework writes an `ask-expired` history row, an audit record, and a producer feed announcement. + +The producer learns of asks by polling, so delivery can lag. +Casework judges timeliness by `answeredAt`, the time the applicant answered, rather than when the report arrives. +Casework accepts an answer at or before `dueAt` even after maintenance marks the ask expired. +Delivery lag therefore never makes an on-time answer late. +The ask becomes `answered`. +The task marker follows its newest ask: `waiting` while open, `expired` after expiry, or `answered` after its answer. +Closing a task or request preserves an already expired ask's state and expiry time. +An expired ask can receive an on-time answer only while its request is still under review. +The `ask-answered` history detail records `arrivedAfterDue` when the report arrives after the deadline. +An answer after `dueAt` receives `409 review.ask-not-open` and changes nothing. + +`pauseClocks` defaults to `false`. +When `true`, Casework pauses the subject clock and current stage activity clocks while the ask is open. +Setting `pauseClocks: true` requires `answerWithin` on the same stage's asks. +Otherwise validation reports `casework.review-policy.ask-pause-requires-answer-within`. +Paused clocks produce no reminders, steps, or task deadlines. +`GET /v1/review-requests/{requestId}/clocks` shows their state as `paused`. +An answer, expiry, or close resumes those clocks. +Casework moves pending instants later by the elapsed wall-clock pause duration for both elapsed-time and working-day clocks. +Casework uses wall time for working-day clocks too, including weekends and holidays. +Clock recomputation retains the accumulated pause duration. +Reviewers see each ask's absolute `dueAt` in the task context. +The `clock-paused` and `clock-resumed` history rows identify each clock. +The resume row records `pausedSeconds`. +Casework audits both transitions. + +{/* Evidence: crates/registry-casework/tests/review_postgres.rs, + c2_ask_due_date_is_absolute_and_delivery_lag_does_not_make_an_answer_late; + c2_a_late_answer_is_refused_before_the_expiry_runner_runs; + c2_fix_old_answer_preserves_the_newest_expired_asks_marker; + c2_ask_pause_shifts_the_clock_and_resumes_on_answer; + c2_resubmission_resumes_at_the_returning_stage_with_a_fresh_clock; + c2_resubmission_starts_at_first_stage_after_result_retention */} + +{/* Evidence: crates/registry-casework/tests/review_postgres.rs, + the_holder_asks_the_applicant_and_the_producer_reads_the_ask; + an_ask_is_refused_unless_every_condition_holds; + the_producer_answer_marks_the_task_answered_and_obeys_its_rules; + deciding_the_task_closes_its_ask_and_clears_the_marker; + staff_list_tasks_that_wait_for_an_applicant_or_were_answered; + crates/registry-casework/tests/review_http.rs, + the_ask_command_and_the_producer_ask_routes_follow_the_contract_over_http */} + ## Pair a current-source provider A current-source review adds one read-only context provider. @@ -644,6 +773,18 @@ BReg must trust that issuer and audience, authorise the selected profile and sub It applies that profile's disclosure and checks the exact Proposal binding. Casework never substitutes its service credential for a human display read. +Casework joins live source answers onto the request's asks by ask ID. +Your task context shows each matching answer beside its question. +Casework reads those answers again for every context request and never stores their text or file descriptors. +The source controls their retention and file downloads. +Casework drops answers for unknown ask IDs and counts them in a value-free operational warning. +Delegated institutional readers receive neither asks nor answers. + +{/* Evidence: crates/registry-casework/tests/support/source_ask_answers.rs, + source_answers_join_known_asks_live_without_entering_the_display_schema_or_store; + crates/registry-casework/tests/review_http.rs, + delegated_institutional_reads_carry_neither_asks_nor_markers. */} + Casework selects the action and purpose from current caller-visible metadata, then checks the observed Proposal binding and exact context contract at visibility and decision boundaries. Context meaning, field semantics and schema bytes stay pinned while profile and row disclosure remain current. A concealed, changed or non-reviewable Proposal is refused or omitted from the visible task list. diff --git a/docs/site/src/content/docs/operate/breg-webhooks.mdx b/docs/site/src/content/docs/operate/breg-webhooks.mdx index 98cea0d321..fc0459a3db 100644 --- a/docs/site/src/content/docs/operate/breg-webhooks.mdx +++ b/docs/site/src/content/docs/operate/breg-webhooks.mdx @@ -91,6 +91,14 @@ there is no supported outbox consumer API. A Proposal lifecycle hook is declared on the Action under `execution.proposal.hooks`, selects native transitions, and uses its own value-free event schema; it is separate from Record field projections. +If you omit `transitions`, BReg matches every Proposal transition. +This includes `added`, `asked` and `answered`, with events `proposal.added`, `proposal.asked` and `proposal.answered`. +Your existing receiver must accept these events when its hook has no transition filter. +Set an explicit `transitions` list if your receiver accepts only selected events. + +{/* Evidence: crates/registry-breg/src/proposal_hooks.rs matching_transitions; + crates/registry-breg/tests/proposal_hooks.rs additions_hooks_select_added_by_default_and_by_explicit_transition. */} + A module may add hooks to an existing Record type, and it cannot replace an event another module owns. diff --git a/docs/site/src/content/docs/reference/apis/registry-casework.mdx b/docs/site/src/content/docs/reference/apis/registry-casework.mdx index 05d88d58d8..89eb052600 100644 --- a/docs/site/src/content/docs/reference/apis/registry-casework.mdx +++ b/docs/site/src/content/docs/reference/apis/registry-casework.mdx @@ -40,6 +40,9 @@ does not name is refused with `operation.not-authorized`. | POST | `/v1/review-requests/{request_id}/cancel` | Requester | The cancellation | | GET | `/v1/review-requests/{request_id}/result` | Requester | `200` with the ReviewResult; bodiless `202` pending, `410` erased | | GET | `/v1/review-results` | Requester | A resumable page of settled results | +| GET | `/v1/review-asks` | Requester that reads asks | A resumable page of ask announcements, `410` past retention | +| GET | `/v1/review-requests/{request_id}/asks/{ask_id}` | Requester that created the request | The ask; an empty `404` for any other ask | +| POST | `/v1/review-requests/{request_id}/asks/{ask_id}/answer` | Requester that created the request | The answered ask; `409` `review.ask-not-open` when it is not open | | GET | `/v1/review-requests/{request_id}/history`, `/clocks` | Reviewer or requester | History; clocks | | POST | `/v1/review-requests/{request_id}/notes` | Reviewer; requester for requester-audience notes | The entry | | GET | `/v1/review-tasks`, `/next`, `/holdings`, `/own-decisions` | Staff, supervisor | ReviewTasks | @@ -50,6 +53,7 @@ does not name is refused with `operation.not-authorized`. | POST | `/v1/review-tasks/{task_id}/delegate` | A reviewer whose profile decides the stage | The task | | GET, PUT, DELETE | `/v1/review-tasks/{task_id}/draft` | The holder | The private draft; `204` on delete | | POST | `/v1/review-tasks/{task_id}/decisions` | The holder | `204` | +| POST | `/v1/review-tasks/{task_id}/asks` | The holder, at a stage that declares `asks` | The task with its `waiting` marker, and the ask | | GET | `/v1/review-tasks/{task_id}/task-templates` | Staff, supervisor | Task grant previews | | GET, POST | `/v1/review-tasks/{task_id}/task-grants` | Staff, supervisor | Grants on the task; the approved grant | | POST | `/v1/review-tasks/{task_id}/task-grants/{grant_id}/revoke` | Staff, supervisor | The revocation | diff --git a/docs/site/src/content/docs/reference/breg-api.mdx b/docs/site/src/content/docs/reference/breg-api.mdx index 58d9746f34..31123f6b23 100644 --- a/docs/site/src/content/docs/reference/breg-api.mdx +++ b/docs/site/src/content/docs/reference/breg-api.mdx @@ -589,6 +589,24 @@ the Proposal Get authority: its frozen `effectDigest`, its `review` result, its progress. Once its result window has lapsed and no application receipt remains, it answers `410 proposal.submission_expired`; the Proposal stays readable. +### Proposal asks + +`POST /v1/proposals/{proposal_id}/asks/{ask_id}/answer` requires the selected profile's `answer` authority, `If-Match`, `Idempotency-Key` and an `application/json` body with optional `text` and `additions` members. +The ask's wants determine which members are required. Unknown members are refused. +A 200 response carries the updated caller-filtered Proposal and ETag. +Get authority controls the optional `asks` member on Proposal reads and command responses. +Follow each ask's `links.answer`, including its typed availability and recovery. +See [Answer a reviewer's ask](../../configure/breg-proposals/#answer-a-reviewers-ask) for limits, delivery and disclosure. + +Human review-context responses carry intrinsic answers in `context.asks`, outside the authored field schema. +A cited-file download selects `reviewAskId` instead of `reviewContextField`, with the existing `submissionVersion`, `effectDigest` and `contextSchemaDigest` query members. +The selector admits only a cited file in the current accepted review binding and preserves every existing download verification and authority check. +Institutional task-grant context does not carry asks or answers. + +{/* Evidence: crates/registry-breg/src/proposal_artifacts.rs; + crates/registry-breg/tests/proposal_asks.rs; + crates/registry-breg/tests/support/proposal_review_asks.rs. */} + ### Proposal attachments `GET`, `PATCH`, and `DELETE /v1/proposals/{proposal_id}/attachments/{slot_id}` read, upload, and @@ -603,6 +621,51 @@ exact content digest; changed content needs a new submission and fresh review. crates/registry-breg-client/src/proposal.rs; products/breg/examples/facility/registry.yaml. */} +Before Submit, follow the Proposal's attachment upload links to fill its required slots. +An empty required slot makes Submit unavailable with `attachment-required` and recovery `correct-input`. +A direct Submit answers `422 attachment.required`, with `fieldPath` naming `/attachments/`. +After an upload, the updated Submit link reflects the stored file even if your profile cannot read the slot's value. +A required file rejected by verification counts as empty. +Pending verification makes Submit unavailable with `attachment-pending` and recovery `refresh`. +A direct Submit answers `409 attachment.verification-pending`. +A rejected optional file gives `invalid-input` with recovery `correct-input`, and `422 attachment.verification-rejected` on Submit. +Each problem names only the slot location, including for a caller who cannot read file metadata. +Filling and submitting can use different profiles: Submit does not require permission to write the slot. +Slot uploads answer `413 attachment.too-large` and `415 attachment.content-type` for size and media-type refusals. + +The generated OpenAPI declares `application/problem+json` bodies for every documented error response on Proposal routes. +These include lifecycle commands, submission reads, review and task-grant context, and file routes. +The shared problem schema includes the problem code and optional field location. + +{/* Evidence: crates/registry-breg/tests/proposal_status_contract.rs every_proposal_error_response_declares_its_problem_body; + crates/registry-breg/tests/support/proposal_required_attachment.rs; + crates/registry-breg/src/proposal_artifacts.rs append_problem_codes; + crates/registry-breg/src/problem.rs AttachmentRequired, AttachmentVerificationPending, AttachmentVerificationRejected. */} + +### Proposal additions + +Follow the Add link at `additions..links.add` to upload a supporting file during an open review. +`POST /v1/proposals/{proposal_id}/additions/{slot_id}` takes the raw bytes with their `Content-Type`. +You must send `Idempotency-Key` and `If-Match`. +BReg returns 200 with the full Proposal and its changed ETag. +The submission version and frozen effect digest stay unchanged. + +The slot descriptor carries its byte limit and accepted media types. +It also carries `maximumCount` and the current submission's `items`. +Each readable item has a download link when verification permits content release. +`GET /v1/proposals/{proposal_id}/additions/{addition_id}` uses the link's submission-version query and the caller's current authority. + +BReg answers an unsupported media type with `415 attachment.content-type`. +An oversized file gets `413 attachment.too-large`. +An empty body gets `400 request.invalid`. +A full slot gets `409 attachment.limit-reached`. +The [Proposal configuration](../../configure/breg-proposals/#accept-supporting-files-during-review) explains the slot grants and reviewer field. + +{/* Evidence: crates/registry-breg/src/api/attachments.rs; + crates/registry-breg/src/proposal_artifacts.rs; + crates/registry-breg/src/problem.rs; + crates/registry-breg/tests/support/proposal_additions.rs. */} + ## Immediate actions An Action with `execution.mode: immediate` runs one atomic plan at `POST /v1/actions/{action}` with diff --git a/docs/site/src/content/docs/reference/client-api.mdx b/docs/site/src/content/docs/reference/client-api.mdx index 72f4c0fbe3..d95c64392b 100644 --- a/docs/site/src/content/docs/reference/client-api.mdx +++ b/docs/site/src/content/docs/reference/client-api.mdx @@ -1132,7 +1132,7 @@ Own-decisions and supervision lists still require current source disclosure. crates/registry-casework/tests/review_postgres.rs, decided_review_state_stays_readable_after_the_source_conceals_context */} -`ReviewStaffingQuery` supports queue, ownership, visible reference, and either all five exact +`ReviewStaffingQuery` supports queue, ownership, the task `marker` (`waiting` or `answered`), visible reference, and either all five exact subject selectors or none. Sort by `due`, `subject`, or `reference`. `next_review_task` is due-ordered and returns one task or no task; holdings return a bounded page. Caseload and clock apply calls send the reviewed preview ID and caller's key. The runtime @@ -1167,6 +1167,17 @@ remain available for a selected subset, with independent revisions and outcomes. crates/registry-casework-client/tests/http_boundary.rs; crates/registry-casework-client-node/client.d.ts, ReviewDecisionReceipt, SupervisoryReviewTask */} +Ask the applicant with `ask_applicant` (`askApplicant` in Node), which takes the task UUID, the +displayed revision, a key and a `{text, wants}` body, and returns the task with its `waiting` +marker and the open ask. The client refuses a response that is for another task, does not advance +the revision by one, leaves no `waiting` marker or carries an ask that is not open. The task +context lists the request's `asks`. The producer-side ask calls are not wrapped here: a producer +reads and answers asks through the review client. + +{/* Evidence: crates/registry-casework-client/src/client.rs, ask_applicant; + crates/registry-casework-client/tests/http_boundary.rs, + ask_applicant_refuses_a_response_that_breaks_its_postconditions */} + ### Casework outcomes Successful calls return `CaseworkComplete` in Rust, a Python dict with `kind: complete`, diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index d594b0112d..f5bf8a7140 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -76,6 +76,33 @@ An accepted completion only makes a result lookup due. crates/registry-breg/src/event_destination.rs, distinct_delivery_keys(); crates/registry-breg/src/review_store.rs, verify_completion(), receive_completion(). */} +### Review ask disclosure + +An applicant's answer and cited files are disclosed to the reviewers of the current accepted review, even when no authored additions context field exists. +The applicant page must explain this before answering. +Answers and their cited files reach only a human reviewer of the current review binding: a verified human caller on a profile written for humans or for any kind, acting for no one else and holding no task grant. +A standing agent, a task-granted agent, a delegated actor or a service receives neither questions nor answers, whatever its grant says, and BReg records no answer disclosure for it. +Its ask-bound download is concealed like any file it may not read. +A file it can reach through an authored additions context field follows that field's grant, as any other context field does. +On the Proposal document, Get, list items and command responses carry the `asks` member only for a caller who may answer on that Proposal: the selected profile holds Get and `answer`, and the caller passes the same human test. +Other Get holders, including status profiles, agents and services, receive no `asks` member. The `answer` command refuses any caller that fails the human test. +A human reviewer reads the questions and answers of its own review only through the single review-context read. +Cited-file downloads also check the exact current submission and review binding, so a link from an earlier round is refused. +A cited file is admitted in place of the authored additions field, so the reviewer's readable context fields do not limit it. +The batch review-context read carries no questions or answers and records no answer disclosure. +The single-Proposal review-context read serves them only with `include=answers`, which the client's display read supplies. +Casework claim, ask and decide preflight omit that option and record no answer disclosure. +No human token is forwarded to the review authority. The worker sends only the subject and stored answer timestamp under its producer credential. +Answer audits retain cited file IDs, and ask-bound download audits identify the actor, ask and file without recording content. +Casework reads answer content live and does not persist it. +Review maintenance prunes value-free feed receipts after their observation recovery window, independently of question and answer retention. + +{/* Evidence: crates/registry-breg/tests/support/proposal_review_asks.rs; + crates/registry-breg/tests/support/proposal_review_asks_final.rs; + crates/registry-casework/tests/support/source_ask_answers.rs; + crates/registry-casework/src/review/source_answers.rs; + crates/registry-casework-breg/src/lib.rs. */} + ### In-process refresh worker Indexed external views are refreshed by a worker inside BReg, not by an outside client. @@ -348,6 +375,33 @@ The link has these known limits: an_applied_proposal_stays_bounded_by_a_record_whose_revision_was_erased; products/breg/contracts/security-invariant-matrix.yaml, BREG-SEC-217. */} +### Supporting files during Proposal review + +BReg admits an addition through the independent `add` operation and the declared slot's `writableAttachments` grant. +BReg accepts it only while the current submission's review is pending or retrying. +The upload holds the Proposal lock and changes its workflow revision. +The idempotency binding covers the slot and the exact file identity. + +Additions remain separate from the frozen attachment manifest and effect digest. +BReg's Apply check continues to compare the frozen manifest with its original attachment references. +An addition grants no authority over the effects that Apply writes. + +Ordinary downloads require Get and the slot's `readableAttachments` grant. +Reviewer downloads instead require the declared review-context field and its exact submission and schema binding. +BReg rechecks current disclosure before releasing verified bytes under the reviewer's own token. +Proposal detail erasure counts and erases addition references with attachment references. +The shared blob store retains bytes while either kind of live reference needs them. +BReg trusts the declared media type within the slot's permitted types. +Downloads use attachment disposition and `nosniff` to limit browser interpretation. +Each addition occupies a place for the submission's lifetime because this release has no removal operation. + +{/* Evidence: crates/registry-breg/src/mutation/proposal.rs ensure_additions_open; + crates/registry-breg/src/postgres/proposal.rs proposal_attachment_download; + crates/registry-breg/src/attachment_store.rs; + crates/registry-breg/tests/support/proposal_additions.rs; + crates/registry-breg/tests/support/proposal_additions_authority.rs; + products/breg/contracts/security-invariant-matrix.yaml BREG-SEC-225, BREG-SEC-226, BREG-SEC-227, BREG-SEC-228. */} + ### One-call writes An immediate Action that patches an existing Record normally asks the caller for a condition: diff --git a/docs/site/src/content/docs/security/casework.mdx b/docs/site/src/content/docs/security/casework.mdx index 3d6a15d420..ac5c90878b 100644 --- a/docs/site/src/content/docs/security/casework.mdx +++ b/docs/site/src/content/docs/security/casework.mdx @@ -54,6 +54,17 @@ grants in [Registry Casework task grants](../../reference/casework-task-grants/) {/* Evidence: crates/registry-review-client/tests/http_boundary.rs, request_progress_rejects_each_substituted_binding_member; crates/registry-casework/tests/review_http.rs, producer_progress_omits_an_unmapped_active_stage. */} +- Applicant answer disclosure: displayed task context reads validated source answers live and joins them only to known ask IDs. + Claim, ask and decide preflight, and inbox hydration, request no answers. + The BReg provider adds `include=answers` only for displayed context, under the reviewer's own bearer. + Delegated institutional reads receive neither asks nor answers nor task markers. + Casework stores no source answer text or file descriptors (`CASEWORK-SEC-46`, `CASEWORK-SEC-48`). + {/* Evidence: crates/registry-casework/tests/support/source_ask_answers.rs, + source_answers_join_known_asks_live_without_entering_the_display_schema_or_store; + crates/registry-casework/tests/review_http.rs, + delegated_institutional_reads_carry_neither_asks_nor_markers; + crates/registry-casework-breg/tests/context_provider.rs, + preflight_omits_answers_and_only_display_opts_in_under_the_same_human_bearer. */} - Private reason versus public reason: every decision names an outcome declared by the pinned policy and offered at the current stage. The reviewer's private reason stays in the accountability record. @@ -235,6 +246,13 @@ The residuals refer to these obligations by number. crates/registry-casework/tests/review_postgres.rs, at_least_once_completion_durably_deduplicates_after_lost_ack_and_exhausts_bounded_retries; crates/registry-casework/src/http.rs, review_result_feed. */} 7. Treat reviewer-written public reasons as released text (`CASEWORK-RES-06`). + An ask of the applicant is released text too: its text goes to the producer, which shows it to + the applicant. The history row and audit record of an ask name only its identifier, and the + producer's answer call carries a subject binding and a time and no applicant text. + {/* Evidence: crates/registry-casework/tests/review_postgres.rs, + the_holder_asks_the_applicant_and_the_producer_reads_the_ask; + the_producer_answer_marks_the_task_answered_and_obeys_its_rules. */} + {/* Evidence: crates/registry-review-protocol/src/lib.rs, check_public_reason. */} 8. Use an HTTPS issuer and leave `authentication.oidc.allowInsecureHttp` unset. Declare only issuer and JWKS addresses you intend Casework to reach (`CASEWORK-RES-08`). diff --git a/docs/site/src/data/breg-api.yaml b/docs/site/src/data/breg-api.yaml index 1631dbbf95..1e5ff10454 100644 --- a/docs/site/src/data/breg-api.yaml +++ b/docs/site/src/data/breg-api.yaml @@ -81,16 +81,20 @@ - ['`action.refused`', '422', 'An Action function intentionally refused the operation. `refusalCode` identifies a declared reason, `detail` contains its static label, and optional `fieldPath` names an input. No effects commit.'] - ['`action.guard_failed`', '412', 'An immediate Action, or a Proposal Submit or Apply, failed a field guard and the selected profile can safely read every guard and row-boundary fact for the selected target. Optional `guardReason` carries its authored copy key. Hidden guard fields, failed authority, stale conditions, and Record revision mismatches remain `precondition.failed`. No effects commit.'] - ['`action.handler_failed`', '500', 'An activated Action function failed to produce an accepted result. Operators use the trace identifier and safe server diagnostics to repair the package. A function deadline returns `503 service.unavailable` instead.'] - - ['`action.evidence_failed`', '503', 'An immediate-action handler declared an Evidence dependency that could not be acquired or accepted: the provider did not answer, or the assertion was refused, failed verification, or exceeded the retention bound. `fieldPath` names the declared Evidence alias when the failure is bound to one. No effects commit.'] + - ['`action.evidence_failed`', '503', 'An immediate Action or Proposal Apply could not acquire or accept a declared Evidence dependency: the provider did not answer, or the assertion was refused, failed verification, or exceeded the retention bound. `fieldPath` names the declared Evidence alias when the failure is bound to one. No effects commit.'] - ['`unsupported.media_type`', '415', 'A body without the required `Content-Type`.'] - - ['`attachment.too-large`', '413', 'An immediate Action carried a file larger than the `maximumBytes` of its record attachment slot. No effects commit.'] - - ['`attachment.content-type`', '415', 'An immediate Action carried a file whose `contentType` is not in the `contentTypes` of its record attachment slot. No effects commit.'] + - ['`attachment.too-large`', '413', 'An immediate Action or Proposal file upload carried a file larger than its slot''s `maximumBytes`. No effects commit.'] + - ['`attachment.content-type`', '415', 'An immediate Action or Proposal file upload carried a file whose media type is not in its slot''s `contentTypes`. No effects commit.'] - ['`attachment.digest-mismatch`', '422', 'An immediate Action carried a file whose bytes do not hash to the `sha256` the request declared. No effects commit.'] - ['`attachment.slot-write-once`', '409', 'A record attachment slot already holds a file. Record slots are write-once, so the second write is refused and the stored file is unchanged. This covers an immediate Action file and a Proposal file that Apply promotes. No effects commit.'] + - ['`attachment.limit-reached`', '409', 'The current submission already holds the additions slot''s `maximumCount` files. BReg accepts no further addition in that submission.'] + - ['`attachment.required`', '422', 'Submit found an empty required attachment slot, including a required file rejected by verification. The problem''s `fieldPath` names only `/attachments/`. Upload an accepted file before submitting.'] + - ['`attachment.verification-pending`', '409', 'Submit found a file awaiting verification. Refresh the Proposal before submitting. The problem''s `fieldPath` names only `/attachments/`.'] + - ['`attachment.verification-rejected`', '422', 'Submit found a rejected file in an optional slot. Replace or remove the file before submitting. The problem''s `fieldPath` names only `/attachments/`.'] - ['`precondition.required`', '428', 'A route that requires `If-Match` was called without it.'] - ['`precondition.failed`', '412', '`If-Match` did not match the current revision, a Patch target was hidden or absent, or an ingestion item, immediate Action effect, or Proposal target or effect failed its boundary check. Invoke also answers this when a file already has a rejected verification verdict. Apply also answers this when a Proposal file it promotes is waiting for verification or was rejected by it. The response is value-free.'] - ['`write.outside-boundary`', '403', 'A direct Create, direct Batch item, or Patch of a visible Record would put the resulting Record outside the selected access profile''s row boundary, or would leave a Record that a `record` disclosure condition then withholds from that profile. An immediate Action, or a Proposal applied by hand, is refused the same way when its plan creates or patches a Record that a `record` disclosure condition binding the applying profile would then withhold from it. A Patch, Batch item, immediate Action or Proposal applied by hand is also refused when a disclosure condition that binds the applying profile matches the Record and the write names one of its withheld fields or would lift the mark. The response has no field, value, claim, or location extension, and no item commits.'] - - ['`proposal.rejected`', '409', 'A Review rejected the Proposal, and a rejection is final: Submit, Edit, Revise, Rebase, Apply, Retry and Cancel are refused. Start a new Proposal to try again.'] + - ['`proposal.rejected`', '409', 'A Review rejected the Proposal, and a rejection is final: Submit, Edit, Add, Revise, Rebase, Apply, Retry and Cancel are refused. Start a new Proposal to try again.'] - ['`proposal.review_result_mismatch`', '412', 'The current Review result differs from the retained approval. Apply commits no effects. Reconcile the review result before attempting application again.'] - ['`proposal.submission_expired`', '410', 'The submission''s review result window has lapsed or its detail was erased, and it has no application receipt. The Proposal itself stays readable.'] - ['`mutation.conflict`', '409', 'A constraint or workflow rule refused the write. A storage-pattern failure includes the declared `recordType` and `fieldId`; correct the input before retrying. A 409 does not imply that retrying an unchanged request can succeed.'] diff --git a/docs/site/src/data/casework-api.yaml b/docs/site/src/data/casework-api.yaml index 6751bed26f..4934887d92 100644 --- a/docs/site/src/data/casework-api.yaml +++ b/docs/site/src/data/casework-api.yaml @@ -24,6 +24,13 @@ - ['`request.not-found`', '404', 'The requested Casework route does not exist.'] - ['`request.unprocessable`', '422', 'The request body does not match the Casework contract.'] - ['`request.unsupported-media-type`', '415', 'Send a JSON request body with Content-Type application/json.'] + - ['`review.ask-already-open`', '409', 'Wait for the open ask on this request to be answered or closed before asking again.'] + - ['`review.ask-answer-time-invalid`', '422', 'Report the time the applicant''s answer was committed: not before the ask was made and no more than five minutes ahead of Casework''s clock.'] + - ['`review.ask-limit-reached`', '409', 'This review request has reached its limit of 50 asks. Continue the review without opening another ask.'] + - ['`review.ask-not-offered`', '409', 'The active stage of this review policy does not let a reviewer ask the applicant.'] + - ['`review.ask-not-open`', '409', 'This ask was already answered or closed, or the applicant answered after its due date.'] + - ['`review.ask-producer-unsupported`', '409', 'The producer of this request does not read asks, so the reviewer cannot ask the applicant.'] + - ['`review.ask-task-inactive`', '409', 'Ask from a task at the active stage of a request that is still under review.'] - ['`review.distinct-approver-required`', '403', 'Each approval in this stage must be supplied by a different reviewer.'] - ['`review.initiator-excluded`', '403', 'You submitted this request, and this review stage excludes the person who submitted it. Another reviewer must take it.'] - ['`review.initiator-required`', '422', 'This review policy excludes the person who submitted the request, so the request must name its initiator.'] diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index 4c6ce6f86e..032de225f5 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,6 +2,85 @@ ## Unreleased +- Proposal applicants can answer mirrored review asks with text and cited additions. + The independent `answer` grant and promoted link bind the command to the current + submission and ETag. Open asks derive `awaiting-party` status. Answer delivery + sends only subject and stored time under the producer credential, with its own + recovery deadline. Human reviewers read answers and cited verified files live + from `context.asks`, even without an authored additions context field. + Agents, standing or task-granted, delegated reads and services receive no + answers and cannot download cited files, and the batch review-context read + carries no asks. Applicant pages must explain that disclosure before answering. +- BREAKING: strict Proposal clients must accept `asks` and the availability reasons + `ask-answered`, `ask-closed` and `ask-due-passed` (all `receipt-only`). Hooks without + a transition filter also receive `proposal.asked` and `proposal.answered`. + Per-version erasure plans count questions, answers and citation references. + +- BREAKING: Proposal slot uploads now answer `413 attachment.too-large` and + `415 attachment.content-type`, matching supporting-document additions. + They previously used generic request and media-type codes. +- Submit and its link share the stored-file check before planning or identifier + reservation. Pending verification answers `409 attachment.verification-pending` + with `attachment-pending` / `refresh`; a rejected optional file answers + `422 attachment.verification-rejected` with `invalid-input` / `correct-input`. + A rejected required file counts as empty. Problems disclose only the slot + location, including to a caller who cannot read the file metadata. + +- Proposal routes declare problem bodies in generated OpenAPI. Submit with an + empty required attachment slot answers `422 attachment.required`, naming the + slot in `fieldPath`. Its link is unavailable with `attachment-required` and + recovery `correct-input`, including for write-only slots. An uploaded file + enables Submit once it passes any configured verification. Update BReg clients + for the added codes and availability reasons. + +- BREAKING: Proposal documents serve the closed display `status` from the same rule as + `turn`. Revise and Rebase preserve approved and processing submissions: + their unavailable links name `application-pending` with recovery `refresh`, + and the commands answer 412. Draft Rebase and party recovery remain available. + `bregctl explain lifecycle` advances to `v1alpha9`, listing status conditions + alongside turns. Update BReg clients to accept the additional Proposal member + and availability reason. Proposal link checks propagate unexpected failures. + +- Proposal hooks without a `transitions` filter also receive `added`, `asked` + and `answered` (`proposal.added`, `proposal.asked` and `proposal.answered`). + Existing receivers must accept those events or configure an explicit transition filter. +- Declaring or changing an `additions` slot changes the Action revision. + Previously submitted Proposals must Rebase and Submit again for fresh review. + Additions require required review. Each accepted file consumes a count place + for its submission, and this release has no addition removal operation. + BReg trusts the declared media type as for other attachments and serves + downloads as attachments with `nosniff`. + +- Proposal Actions can declare one bounded `additions` slot for supporting files + during an open review. The independent `add` grant uses `writableAttachments`. + Get uses `readableAttachments`. Each addition changes the Proposal ETag while + keeping the submission version and frozen effects unchanged. Review context + can project an `additions` field, and hooks can observe `proposal.added`. + +- BREAKING: the compiler refuses a Proposal grant that holds `edit`, `revise` + or `rebase` unless its `readableInputs` cover every input it may write + (`writableInputs`, or every declared input when absent), with + `breg.proposal.input-write-unreadable`. With the existing rule for inputs + outside `writableInputs`, such a grant reads every declared input. Add the + named inputs to `readableInputs`, and `get` if the grant lacks it, because + `readableInputs` requires Get. An agent profile without a task grant is + exempt. + +- Every Proposal command response, attachment uploads and removals included, + carries `decision` and `input` as a Get by the same caller would serve them + right after the command, so a client need not read the Proposal again. A + profile without Get on the Proposal gets neither. Attachment metadata on a + command response follows the same Get check. A replay returns the stored + response and records the `proposal-review-public-reason` audit marker when + that response holds a public reason. A command receipt stored before this + release replays without the two members. The idempotency binding covers the + grant's `readableInputs` when it names any, so after a package narrows them + an earlier key conflicts instead of replaying a withheld input. + +- The Proposal attachment download declares its 200 response as `*/*`, the + stored file's own media type, instead of `application/octet-stream`. + Generated clients that switch on the declared response type regenerate. + - BREAKING: BReg signs every URL hook delivery with Standard Webhooks. The POST carries `webhook-id`, `webhook-timestamp` and `webhook-signature`, an HMAC-SHA-256 over the id, the timestamp and the exact body. It no longer diff --git a/products/breg/acceptance/reviewed-evidence-journey/README.md b/products/breg/acceptance/reviewed-evidence-journey/README.md index eda6e86f63..8a57a61aaa 100644 --- a/products/breg/acceptance/reviewed-evidence-journey/README.md +++ b/products/breg/acceptance/reviewed-evidence-journey/README.md @@ -29,7 +29,8 @@ PATH="$HOME/.cargo/bin:$PATH" \ CARGO_INCREMENTAL=0 CARGO_PROFILE_DEV_DEBUG=0 CARGO_PROFILE_TEST_DEBUG=0 \ cargo build --locked -j2 \ -p registry-breg -p registry-bregctl -p registry-casework \ - -p registry-caseworkctl -p registry-evidence -p registry-evidencectl --bins + -p registry-caseworkctl -p registry-evidence -p registry-evidencectl \ + --features registry-breg/runtime --bins ``` On macOS direct Cargo-built binaries need the AWS-LC FIPS library directory in @@ -37,6 +38,10 @@ On macOS direct Cargo-built binaries need the AWS-LC FIPS library directory in `scripts/cargo-runtime-library-path.sh` build helper when preparing those binaries, or preserve the exact library path from the build's Cargo messages. Released executables use their installation's runtime dependencies. +For Cargo-built macOS binaries, source that helper and prepare the same six +packages with the build arguments above in the shell used for the run. +The runner carries the helper's `REGISTRY_CARGO_RUNTIME_LIBRARY_PATH` into +child processes if the Python launcher strips `DYLD_FALLBACK_LIBRARY_PATH`. ```sh uv sync --locked --project products/breg/acceptance/reviewed-evidence-journey @@ -70,7 +75,7 @@ Generated output is retained for inspection, including after a failed run. The administrator staffs its queue through the public Directory API. 3. The source exports only its lookup identity fields and `status`. Evidence imports the generated source contract into an ordinary normalized project, - checks it, runs the maintained 11 source/derivation/privacy fixtures, packages + checks it, runs the maintained 12 source/derivation/privacy fixtures, packages it and activates the separately compiled caller authority. 4. An independent consumer verifies a signed false assertion from the retired source record. A human author submits a frozen correction under an explicit @@ -78,26 +83,48 @@ Generated output is retained for inspection, including after a failed run. `{id, version, digest}` binding at acceptance. The source retains and exposes the exact accepted provider request ID under its service-status grant. 5. A separate synthetic human reads current-source review context, claims the - exact task and approves it. The runner compares request, policy, subject, + exact task and asks the applicant for one document. The opted-in stage gives + the ask an absolute one-hour due date, and the producer declares `readsAsks`. + BReg mirrors it as `awaiting-party` / `party`, and the applicant finds it in + the party-turn list. A receiver verifies the signed `proposal.asked` hook. +6. The applicant uses their own BReg token to add a file and answer with text + and that file's ID. The submission version and effects stay frozen, and the + Proposal returns to `in-review`. The same Casework task acquires its + `answered` marker. Its holder reads the answer live and downloads the cited + bytes through `reviewAskId` under the holder's own source authority. + The holder then approves that same task. A transparent loopback observer + records only actor labels, request identifiers, routes and HTTP states. + It asserts that every accepted create names the same review request and + that no Casework request carried the applicant's token, including worker + traffic. It forwards authentication unchanged to the real executable. + The runner compares request, policy, subject, submission version, effect digest and submission digest with the immutable result. Review approval leaves the source unchanged until explicit application. -6. The independently authorized applier commits the exact frozen correction. +7. The independently authorized applier commits the exact frozen correction. Reviewer, producer and source lookup credentials cannot apply it. Direct Patch cannot bypass the source's Proposal-required mutation policy; even the authorized applier cannot apply before approval. -7. The consumer prepares a new request, verifies a signed true assertion from +8. The consumer prepares a new request, verifies a signed true assertion from the corrected source, and checks the exact Boolean output and absence of private labels, business identifiers and raw status. An ungranted caller is refused and a tampered signature produces no verified output. -8. Cleanup verifies that child processes, owned databases, roles and container +9. Cleanup verifies that child processes, owned databases, roles and container are gone. A failed cleanup fails the journey. The unit suite tests the acceptance oracle with deliberately mismatched review identities, policies, digests, decisions, disclosed values and cleanup receipts. It also refuses before/after pairs whose subject, contract or issuer drifts. +The ask-loop oracle rejects wrong turns, missing due dates or hooks, changed +submissions, substituted asks, files, requests or deciding tasks, undelivered +markers, different answer content, and applicant-token disclosure to Casework. +`ask-loop.json` retains only identifiers and states. Answer text and file bytes +are compared in memory and are never written into proof summaries or traffic +logs. The authored scenario is `native-review-ask-answer-handoff`; the live +runner additionally checks signed hooks, exact bytes, request uniqueness and +the token boundary. `products/breg/scripts/check-contracts.sh` runs this unit suite. The live run needs Docker and matching binaries and runs only when invoked. -The 11 Evidence fixtures are synthetic calculation and protocol checks. The +The 12 Evidence fixtures are synthetic calculation and protocol checks. The combined run is real-runtime HTTP proof. Neither establishes released artifact installation, production issuer integration, outages, upgrades, or production readiness. @@ -120,7 +147,11 @@ it does not authorize or alter source writes. The runner copies authored fixtures into the fresh output tree. It imports the BReg-generated Evidence source, then reuses the maintained `record-active` -definition, Function and 11 cases from `products/breg/evidence/starter`. +definition, Function and 12 cases from `products/breg/evidence/starter`. +It omits the copied cases' OAuth replay exchanges to match this journey's +static source credential, while retaining every source-response and privacy +expectation. The Evidence target binds `connections.registry.endpoints.registry` +and removes the replaced starter's unused extract binding. Environment origins, test issuer identities, secret references and credentials are generated separately in that output tree. The crypto helpers come from the maintained farmer-landholding Evidence runner; its HTTP source is never used. diff --git a/products/breg/acceptance/reviewed-evidence-journey/casework/casework.yaml b/products/breg/acceptance/reviewed-evidence-journey/casework/casework.yaml index 311df4ff85..646ba0c2fd 100644 --- a/products/breg/acceptance/reviewed-evidence-journey/casework/casework.yaml +++ b/products/breg/acceptance/reviewed-evidence-journey/casework/casework.yaml @@ -54,6 +54,8 @@ reviewPolicies: - staff requiredApprovals: 1 excludeInitiator: true + asks: + answerWithin: {hours: 1} retention: terminalRetentionDays: 30 accountabilityRetentionDays: 90 @@ -73,6 +75,7 @@ reviewPolicies: trustedProducers: registry: profile: requester + readsAsks: true issuer: https://issuer.example.test subject: producer trustedInitiatorIssuer: https://issuer.example.test diff --git a/products/breg/acceptance/reviewed-evidence-journey/registry/registry.yaml b/products/breg/acceptance/reviewed-evidence-journey/registry/registry.yaml index 13b12e2705..327619449f 100644 --- a/products/breg/acceptance/reviewed-evidence-journey/registry/registry.yaml +++ b/products/breg/acceptance/reviewed-evidence-journey/registry/registry.yaml @@ -120,6 +120,11 @@ accessProfiles: operations: - get - submit + - list + - add + - answer + readableAttachments: [supporting] + writableAttachments: [supporting] ownership: caller readableInputs: - record @@ -225,6 +230,16 @@ actions: execution: mode: proposal proposal: + additions: + id: supporting + maximumBytes: 4096 + maximumCount: 1 + contentTypes: [text/plain] + classification: internal + hooks: + - id: asked-observer + transitions: [asked] + handler: {type: url, destinationId: ask-observer} review: type: required authority: casework diff --git a/products/breg/acceptance/reviewed-evidence-journey/tests/proof.py b/products/breg/acceptance/reviewed-evidence-journey/tests/proof.py index afcb5a64f7..20c5653672 100644 --- a/products/breg/acceptance/reviewed-evidence-journey/tests/proof.py +++ b/products/breg/acceptance/reviewed-evidence-journey/tests/proof.py @@ -1,6 +1,98 @@ """Value-free acceptance failures for exact correlation, disclosure and cleanup.""" import json +from datetime import datetime +from urllib.parse import parse_qs, urlsplit + + +def check_ask_loop(observed, text, content): + """Check served milestones, returning a content-free proof receipt.""" + submitted, asked = observed["submitted"], observed["asked"] + proposal, version = submitted["id"], submitted["submissionVersion"] + request, task, ask = observed["accepted"]["requestId"], asked["task"]["taskId"], asked["ask"]["askId"] + file = observed["additionId"] + question = asked["ask"] + assert question["state"] == "open" and question["wants"] == [{"kind": "document"}], "ask differs" + assert question.get("dueAt") and datetime.fromisoformat(question["dueAt"]) > datetime.fromisoformat( + question["askedAt"] + ), "ask has no future due date" + assert asked["task"]["requestId"] == request and asked["task"]["marker"] == "waiting", "ask task differs" + for name in ("party", "answered"): + document = observed[name] + assert all(document[key] == submitted[key] for key in ("id", "submissionVersion", "effectDigest")), ( + "answer changed the frozen submission" + ) + assert document["state"] == "submitted", "submission left review" + party = observed["party"] + assert (party["status"], party["turn"]) == ("awaiting-party", "party"), "party turn missing" + assert any(item["id"] == proposal for item in observed["partyPage"]["items"]), "party list omits proposal" + assert any( + item["id"] == ask + and item["state"] == "open" + and datetime.fromisoformat(item["dueAt"]) == datetime.fromisoformat(question["dueAt"]) + for item in party["asks"] + ), "mirror differs" + event = observed["hook"] + assert event["type"] == "proposal.asked" and event["data"]["transition"] == "asked", "asked hook missing" + assert event["data"]["proposalId"] == proposal and event["data"]["submissionVersion"] == version, ( + "asked hook names another submission" + ) + assert observed["answered"]["status"] == "in-review", "local answer did not return to review" + answers = [item for item in observed["answered"]["asks"] if item["id"] == ask] + assert len(answers) == 1 and answers[0]["state"] == "answered", "local answer missing" + assert answers[0]["answer"]["text"] == text and answers[0]["answer"]["additions"] == [file], ( + "local answer differs" + ) + assert observed["task"]["taskId"] == task and observed["task"]["marker"] == "answered", ( + "delivery marker missing" + ) + context = observed["context"] + assert context["taskId"] == task and context["requestId"] == request, "reviewer binding changed" + asks = [item for item in context["asks"] if item["askId"] == ask] + assert len(asks) == 1 and asks[0]["taskId"] == task and asks[0]["state"] == "answered", ( + "reviewer ask differs" + ) + answer = asks[0]["answer"] + assert answer["text"] == text and len(answer["documents"]) == 1, "reviewer answer differs" + document = answer["documents"][0] + assert document["id"] == file and document["verificationStatus"] in ("approved", "notRequired"), ( + "citation differs" + ) + download = document["download"] + parsed = urlsplit(download["path"]) + assert download["method"] == "GET" and download["operation"] == "get-review-context", ( + "download authority differs" + ) + assert parsed.path == f"/v1/proposals/{proposal}/additions/{file}", "download file differs" + assert parse_qs(parsed.query).get("reviewAskId") == [ask], "download ask differs" + assert observed["download"] == content, "cited download bytes differ" + assert set(observed["createdRequestIds"]) == {request}, "more than one review request created" + assert len(observed["correlations"]) >= 3 and all( + item["requestId"] == request for item in observed["correlations"] + ), "accepted request changed during the loop" + decided = observed["decidedTask"] + assert decided["taskId"] == task and decided["requestId"] == request, "decision changed task or request" + assert decided["state"] == "decided" and decided["decidedByCaller"] is True, "holder decision missing" + assert ( + decided["decisionReceipt"]["decision"] == "approve" + and decided["decisionReceipt"]["outcome"] == "approved" + ), "holder did not approve" + assert observed["requests"] and all(item["actor"] != "applicant" for item in observed["requests"]), ( + "Casework received the applicant token" + ) + return { + "proposalId": proposal, + "submissionVersion": version, + "requestId": request, + "taskId": task, + "askId": ask, + "additionId": file, + "hookEventId": event["id"], + "status": "in-review", + "marker": "answered", + "decision": "approved", + "applicantToken": "not-sent", + } def check_correlation(proposal, accepted, result): diff --git a/products/breg/acceptance/reviewed-evidence-journey/tests/run_live.py b/products/breg/acceptance/reviewed-evidence-journey/tests/run_live.py index 59b94db853..5984686fab 100644 --- a/products/breg/acceptance/reviewed-evidence-journey/tests/run_live.py +++ b/products/breg/acceptance/reviewed-evidence-journey/tests/run_live.py @@ -8,19 +8,178 @@ from __future__ import annotations import argparse +import base64 +import hashlib +import hmac +from http.client import HTTPConnection +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json import os from pathlib import Path import shutil import subprocess +import threading import time +from urllib.parse import urlsplit import yaml -from proof import check_cleanup, check_correlation, check_minimized, check_observations +from proof import check_ask_loop, check_cleanup, check_correlation, check_minimized, check_observations from support import Harness, INPUTS, ROOT, hashes, port, write, yaml_write +class JourneyHarness(Harness): + """Observe real Casework traffic and real signed hook delivery without keeping content.""" + + def __init__(self, output, binaries): + super().__init__(output, binaries) + # The maintained helper carries this across launchers that strip DYLD variables. + if os.environ.get("REGISTRY_CARGO_RUNTIME_LIBRARY_PATH"): + self.env["DYLD_FALLBACK_LIBRARY_PATH"] = os.environ["REGISTRY_CARGO_RUNTIME_LIBRARY_PATH"] + self.observers = [] + self.casework_requests = [] + self.created_request_ids = set() + self.asked_events = [] + self.observation_lock = threading.Lock() + + def listen(self, handler): + server = ThreadingHTTPServer(("127.0.0.1", 0), handler) + self.observers.append(server) + threading.Thread(target=server.serve_forever, daemon=True).start() + return f"http://127.0.0.1:{server.server_port}" + + def observe_casework(self, origin): + harness = self + + class Observer(BaseHTTPRequestHandler): + def log_message(self, *_args): + return + + def exchange(self): + size = int(self.headers.get("Content-Length", "0")) + if not 0 <= size <= 1024 * 1024: + self.send_error(413) + return + body = self.rfile.read(size) + connection = HTTPConnection(urlsplit(origin).netloc, timeout=15) + try: + connection.request(self.command, self.path, body, dict(self.headers)) + response = connection.getresponse() + content = response.read(1024 * 1024 + 1) + assert len(content) <= 1024 * 1024, "Casework observer response exceeded bound" + authorization = self.headers.get("Authorization") + actor = next( + ( + role + for role, token in harness.tokens.items() + if authorization == "Bearer " + token + ), + "unauthenticated", + ) + actor = "applicant" if actor == "operator" else actor + with harness.observation_lock: + harness.casework_requests.append( + { + "actor": actor, + "method": self.command, + "path": urlsplit(self.path).path, + "status": response.status, + } + ) + if ( + self.command == "POST" + and urlsplit(self.path).path == "/v1/review-requests" + and response.status in (200, 201) + ): + harness.created_request_ids.add(json.loads(content)["requestId"]) + write(harness.output / "casework-requests.json", harness.casework_requests) + self.send_response(response.status) + for name, value in response.getheaders(): + if name.lower() not in ("connection", "transfer-encoding", "content-length"): + self.send_header(name, value) + self.send_header("Content-Length", str(len(content))) + self.end_headers() + self.wfile.write(content) + finally: + connection.close() + + do_GET = do_POST = do_DELETE = do_PATCH = exchange + + self.casework_origin = self.listen(Observer) + return self.casework_origin + + def receive_hooks(self): + harness = self + key = os.urandom(32).hex().encode() + (self.secret_root / "ask-hook-key").write_bytes(key) + + class Receiver(BaseHTTPRequestHandler): + def log_message(self, *_args): + return + + def do_POST(self): + size = int(self.headers.get("Content-Length", "0")) + if self.path != "/events" or not 0 < size <= 8192: + self.send_error(400) + return + body = self.rfile.read(size) + identifier, timestamp = ( + self.headers.get("webhook-id", ""), + self.headers.get("webhook-timestamp", ""), + ) + expected = ( + "v1," + + base64.b64encode( + hmac.digest( + key, identifier.encode() + b"." + timestamp.encode() + b"." + body, "sha256" + ) + ).decode() + ) + if not hmac.compare_digest(self.headers.get("webhook-signature", ""), expected): + self.send_error(403) + return + event = json.loads(body) + if event["type"] != "proposal.asked" or event["id"] != identifier: + self.send_error(400) + return + data = event["data"] + with harness.observation_lock: + harness.asked_events.append( + { + "id": event["id"], + "type": event["type"], + "data": { + name: data[name] for name in ("proposalId", "submissionVersion", "transition") + }, + } + ) + write(harness.output / "asked-events.json", harness.asked_events) + self.send_response(204) + self.end_headers() + + self.hook_origin = self.listen(Receiver) + + def raw(self, origin, path, token, *, body=None, method="GET", headers=None): + """Bounded file exchange. Bytes remain in memory and never enter proof output.""" + connection = HTTPConnection(urlsplit(origin).netloc, timeout=15) + try: + connection.request(method, path, body, {**(headers or {}), "Authorization": "Bearer " + token}) + response = connection.getresponse() + content = response.read(1024 * 1024 + 1) + assert len(content) <= 1024 * 1024, "file exchange exceeded bound" + return response.status, content, {key.lower(): value for key, value in response.getheaders()} + finally: + connection.close() + + def cleanup(self): + try: + return super().cleanup() + finally: + for server in self.observers: + server.shutdown() + server.server_close() + + def breg_runtime(h, name, package, origin, casework): return { "apiVersion": "id.registrystack.org/formats/breg/runtime/v1alpha1", @@ -63,7 +222,20 @@ def breg_runtime(h, name, package, origin, casework): "path": str(h.output / (name + "-audit/audit.jsonl")), }, "cursor": {"secretRef": "secret:file/cursor-key", "maximumAgeSeconds": 300}, - "destinations": {"hooks": {}}, + "destinations": { + "hooks": { + "ask-observer": { + "origin": h.hook_origin, + "path": "/events", + "networkProfile": "loopback-development-http", + "dnsFamily": "dual-stack-strict", + "allowedPrivateCidrs": [], + "hmacSha256KeyRef": "secret:file/ask-hook-key", + "classificationCeiling": "internal", + "deliveryCeilings": {"attemptTimeoutMilliseconds": 1000, "maximumAttempts": 3}, + } + } + }, "reviewAuthorities": { "casework": { "endpoint": casework, @@ -220,7 +392,7 @@ def activate_casework(h, source_package, source, origin): h.ctl("caseworkctl", "review-apply", "apply", "--runtime-config", runtime) h.start("casework", [h.binaries["casework"], "--runtime-config", runtime, "serve"], origin) status, _, _ = h.http( - origin, + h.casework_origin, "/v1/directory/bootstrap", h.tokens["administrator"], "administrator", @@ -237,6 +409,30 @@ def activate_casework(h, source_package, source, origin): return checked["policyBindings"][0] +def registry_connection(origin): + return { + "endpoints": { + "registry": { + "origin": origin, + "authentication": {"type": "static-authorization", "tokenRef": "secret:file/source-token"}, + } + } + } + + +def bind_static_fixture(fixture): + """Match this journey's static source credential, retaining all HTTP/privacy cases.""" + for case in fixture["cases"]: + acquisition = case.get("acquisition") + if acquisition: + acquisition["intercepts"] = [ + item for item in acquisition["intercepts"] if item["type"] != "token-endpoint" + ] + acquisition["exchanges"] = [ + item for item in acquisition["exchanges"] if not item["request"].get("tokenRequest") + ] + + def activate_evidence(h, source_project, source, origin): exported = h.output / "source-export" h.ctl( @@ -293,6 +489,10 @@ def activate_evidence(h, source_project, source, origin): shutil.copyfile( ROOT / "products/breg/evidence/starter" / directory / name, project / directory / name ) + fixture_path = project / "fixtures/record-active.yaml" + fixture = yaml.safe_load(fixture_path.read_text()) + bind_static_fixture(fixture) + yaml_write(fixture_path, fixture) target_dir = h.output / "target" h.run( "evidence-target", @@ -314,10 +514,9 @@ def activate_evidence(h, source_project, source, origin): maximumTokenLifetimeSeconds=3600, jwksSource={"type": "uri", "uri": h.issuer_url + "/.well-known/jwks.json"}, ) - target["connections"]["registry"] = { - "origin": source, - "authentication": {"type": "static-authorization", "tokenRef": "secret:file/source-token"}, - } + target["connections"]["registry"] = registry_connection(source) + # This composition replaced the starter's extract-backed source with HTTP. + target["extracts"] = {} target["signer"].update( privateKeyRef="secret:file/signing-p256-private-jwk", publicJwkFile="signing-public.jwk.json", @@ -336,7 +535,11 @@ def activate_evidence(h, source_project, source, origin): yaml_write(authority_path, authority) h.ctl("evidencectl", "evidence-check", "check", project, "--target", target_dir) fixture = h.ctl("evidencectl", "evidence-fixtures", "test", project, "--target", target_dir) - h.check("evidence-11-fixture-cases", fixture["passed"] and fixture["fixtures"][0]["evaluatedCases"] == 11) + h.fixture_cases = len(yaml.safe_load(fixture_path.read_text())["cases"]) + h.check( + "evidence-fixture-cases", + fixture["passed"] and fixture["fixtures"][0]["evaluatedCases"] == h.fixture_cases, + ) candidate = h.output / "evidence-candidate" h.ctl( "evidencectl", "evidence-package", "package", project, "--target", target_dir, "--output", candidate @@ -467,6 +670,143 @@ def seed_record(h, source): return record["data"]["recordIdentifier"] +def await_served(label, read, ready): + deadline = time.monotonic() + 90 + while True: + observation = read() + if observation[0] == 200 and ready(observation[1]): + return observation + if time.monotonic() > deadline: + raise RuntimeError(label + " did not reach its served state") + time.sleep(0.25) + + +def ask_and_answer(h, source, casework, source_call, task_path, claimed, submitted, accepted, correlation): + observed = {"submitted": submitted, "accepted": accepted, "correlations": [correlation]} + status, asked, _ = h.http( + casework, + task_path + "/asks", + h.tokens["staff"], + "staff", + {"text": "Please provide one supporting document.", "wants": [{"kind": "document"}]}, + "POST", + { + "If-Match": '"' + str(claimed["revision"]) + '"', + "Idempotency-Key": "ask-document", + "Registry-Source-Profile": "reviewer", + }, + ) + h.check( + "task-holder-asks-for-one-document-with-due-date", status == 200 and bool(asked["ask"].get("dueAt")) + ) + observed["asked"] = asked + proposal_path = "/v1/proposals/" + submitted["id"] + ask_id = asked["ask"]["askId"] + _, party, headers = await_served( + "mirrored ask", + lambda: source_call(proposal_path), + lambda value: ( + value.get("status") == "awaiting-party" + and any(ask["id"] == ask_id for ask in value.get("asks", [])) + ), + ) + observed["party"] = party + h.check("mirrored-ask-returns-the-party-turn", party["turn"] == "party") + status, page, _ = source_call("/v1/proposals?turn=party&limit=100") + h.check( + "party-list-includes-the-asked-proposal", + status == 200 and any(item["id"] == submitted["id"] for item in page["items"]), + ) + observed["partyPage"] = page + deadline = time.monotonic() + 90 + while True: + with h.observation_lock: + events = [event for event in h.asked_events if event["data"]["proposalId"] == submitted["id"]] + if events: + observed["hook"] = events[0] + break + if time.monotonic() > deadline: + raise RuntimeError("signed asked hook did not arrive") + time.sleep(0.25) + h.check("asked-hook-delivered-and-signed", True) + answer_text, file_bytes = ( + "Synthetic explanation for this correction.", + b"Synthetic supporting document.\n", + ) + link = party["additions"]["supporting"]["links"]["add"] + status, body, _ = h.raw( + source, + link["path"] + "?accessProfile=" + link["accessProfile"], + h.tokens["operator"], + body=file_bytes, + method="POST", + headers={ + "Content-Type": "text/plain", + "If-Match": link["ifMatch"], + "Idempotency-Key": "supporting-document", + }, + ) + h.check("applicant-added-one-file", status == 200) + added = json.loads(body) + files = added["additions"]["supporting"]["items"] + h.check( + "added-file-metadata-matches-bytes", + len(files) == 1 and files[0]["sha256"] == hashlib.sha256(file_bytes).hexdigest(), + ) + file_id = files[0]["id"] + observed["additionId"] = file_id + ask = next(item for item in added["asks"] if item["id"] == ask_id) + link = ask["links"]["answer"] + status, answered, _ = source_call( + link["path"], + body={"text": answer_text, "additions": [file_id]}, + method="POST", + headers={"If-Match": link["ifMatch"], "Idempotency-Key": "answer-document"}, + ) + h.check("applicant-answered-and-returned-to-review", status == 200 and answered["status"] == "in-review") + observed["answered"] = answered + _, task, _ = await_served( + "delivered answer marker", + lambda: h.http( + casework, task_path, h.tokens["staff"], "staff", headers={"Registry-Source-Profile": "reviewer"} + ), + lambda value: value.get("marker") == "answered", + ) + observed["task"] = task + h.check("casework-received-the-answer-marker", True) + status, context, _ = h.http( + casework, + task_path + "/context", + h.tokens["staff"], + "staff", + headers={"Registry-Source-Profile": "reviewer"}, + ) + h.check("holder-reads-live-answer", status == 200) + observed["context"] = context + answer = next(item for item in context["asks"] if item["askId"] == ask_id)["answer"] + link = answer["documents"][0]["download"] + separator = "&" if "?" in link["path"] else "?" + status, downloaded, headers = h.raw( + source, link["path"] + separator + "accessProfile=" + link["accessProfile"], h.tokens["staff"] + ) + h.check( + "holder-downloads-the-cited-file-under-own-token", + status == 200 + and downloaded == file_bytes + and headers.get("x-content-type-options") == "nosniff" + and headers.get("cache-control") == "no-store" + and headers.get("content-disposition", "").startswith("attachment"), + ) + observed["download"] = downloaded + status, correlation, _ = source_call(proposal_path + "/review-status", "context-status", "review-status") + h.check( + "answer-keeps-the-accepted-request", + status == 200 and correlation["requestId"] == accepted["requestId"], + ) + observed["correlations"].append(correlation) + return observed, task, answer_text, file_bytes + + def reviewed_correction(h, source, casework, policy, record_id): def source_call(path, role="operator", profile="operator", body=None, method="GET", headers=None): separator = "&" if "?" in path else "?" @@ -591,6 +931,9 @@ def source_call(path, role="operator", profile="operator", body=None, method="GE }, ) h.check("independent-human-claimed", status == 200) + observed, claimed, answer_text, file_bytes = ask_and_answer( + h, source, casework, source_call, task_path, claimed, submitted, accepted, correlation + ) status, _, _ = h.http( casework, task_path + "/decisions", @@ -605,6 +948,21 @@ def source_call(path, role="operator", profile="operator", body=None, method="GE }, ) h.check("human-decision-recorded", status == 204) + status, decided, _ = h.http( + casework, task_path, h.tokens["staff"], "staff", headers={"Registry-Source-Profile": "reviewer"} + ) + h.check( + "the-task-that-asked-is-the-task-that-decided", status == 200 and decided["taskId"] == task["taskId"] + ) + observed["decidedTask"] = decided + status, correlation, _ = source_call(proposal_path + "/review-status", "context-status", "review-status") + h.check("decision-keeps-the-accepted-request", status == 200) + observed["correlations"].append(correlation) + with h.observation_lock: + observed["requests"] = list(h.casework_requests) + observed["createdRequestIds"] = sorted(h.created_request_ids) + write(h.output / "ask-loop.json", check_ask_loop(observed, answer_text, file_bytes)) + h.check("one-request-one-task-ask-answer-decision-and-no-applicant-token-in-casework", True) status, result, _ = h.http( casework, "/v1/review-requests/" + task["requestId"] + "/result", h.tokens["producer"], "requester" ) @@ -649,7 +1007,10 @@ def source_call(path, role="operator", profile="operator", body=None, method="GE "exact-source-correction-committed", status == 200 and after["data"]["domainData"]["status"] == "active", ) - write(h.output / "applied-submission.json", applied) + write( + h.output / "applied-submission.json", + {key: applied[key] for key in ("id", "actionId", "submissionVersion", "revision", "state", "status")}, + ) def main(): @@ -677,7 +1038,7 @@ def main(): assert all(path.is_file() and os.access(path, os.X_OK) for path in binaries.values()), ( "build all six product binaries first" ) - h = Harness(output, binaries) + h = JourneyHarness(output, binaries) versions = { name: h.run("version-" + name, [binary, "--version"]).strip() for name, binary in binaries.items() } @@ -709,9 +1070,11 @@ def main(): try: h.database() h.identity() - source, casework, evidence = [f"http://127.0.0.1:{port()}" for _ in range(3)] + h.receive_hooks() + source, casework_origin, evidence = [f"http://127.0.0.1:{port()}" for _ in range(3)] + casework = h.observe_casework(casework_origin) source_project, source_package, source_runtime = activate_source(h, source, casework) - policy = activate_casework(h, source_package, source, casework) + policy = activate_casework(h, source_package, source, casework_origin) h.start("breg", [h.binaries["breg"], "--runtime-config", source_runtime], source) evidence_project, client = activate_evidence(h, source_project, source, evidence) record_id = seed_record(h, source) @@ -762,13 +1125,13 @@ def main(): "passed": success, "journeyChecksPassed": len(h.checks), "journeyChecksFailed": 0 if success else 1, - "fixtureCases": 11 if "evidence-11-fixture-cases" in h.checks else 0, + "fixtureCases": getattr(h, "fixture_cases", 0) if "evidence-fixture-cases" in h.checks else 0, "skipped": 0, "cleanup": cleanup, }, ) print( - f"PASS: {len(h.checks)} journey checks; 11 synthetic fixture cases; cleanup verified. Owner-only evidence: {output}" + f"PASS: {len(h.checks)} journey checks; {h.fixture_cases} synthetic fixture cases; cleanup verified. Owner-only evidence: {output}" ) diff --git a/products/breg/acceptance/reviewed-evidence-journey/tests/scenarios.yaml b/products/breg/acceptance/reviewed-evidence-journey/tests/scenarios.yaml index 2ddfa5dc12..d73ef2a16b 100644 --- a/products/breg/acceptance/reviewed-evidence-journey/tests/scenarios.yaml +++ b/products/breg/acceptance/reviewed-evidence-journey/tests/scenarios.yaml @@ -2,7 +2,7 @@ apiVersion: id.registrystack.org/formats/rstack/scenarios/v1alpha1 kind: RStackScenarios scenarios: - - id: native-review-handoff + - id: native-review-ask-answer-handoff steps: - id: staff-queue product: casework @@ -79,12 +79,87 @@ scenarios: headers: {If-Match: '"{{taskRevision}}"', Idempotency-Key: claim-task, Registry-Source-Profile: reviewer} expect: {status: 200} capture: {claimRevision: {type: pointer, pointer: /revision}} + - id: ask-for-document + product: casework + as: reviewer + method: POST + path: "/v1/review-tasks/{{task}}/asks" + headers: {If-Match: '"{{claimRevision}}"', Idempotency-Key: ask-document, Registry-Source-Profile: reviewer} + body: {text: Please provide one supporting document., wants: [{kind: document}]} + expect: {status: 200, json: {/task/marker: waiting, /ask/state: open}} + capture: + ask: {type: pointer, pointer: /ask/askId} + due: {type: pointer, pointer: /ask/dueAt} + - id: await-mirrored-ask + product: breg + as: operator + method: GET + path: "/v1/proposals/{{proposal}}" + expect: {status: 200, json: {/status: awaiting-party, /turn: party, /asks/0/id: "{{ask}}"}} + poll: {maximumWaitMilliseconds: 60000, pollIntervalMilliseconds: 500} + capture: {askedEtag: {type: header, header: etag}} + - id: find-party-turn + product: breg + as: operator + method: GET + path: /v1/proposals?turn=party + expect: {status: 200, json: {/items/0/id: "{{proposal}}"}} + - id: add-supporting-document + product: breg + as: operator + method: POST + path: "/v1/proposals/{{proposal}}/additions/supporting" + headers: {If-Match: "{{askedEtag}}", Idempotency-Key: supporting-document} + raw: {contentType: text/plain, base64: U3ludGhldGljIHN1cHBvcnRpbmcgZG9jdW1lbnQuCg==} + expect: {status: 200} + capture: + addition: {type: pointer, pointer: /additions/supporting/items/0/id} + addedEtag: {type: header, header: etag} + - id: answer-through-source + product: breg + as: operator + method: POST + path: "/v1/proposals/{{proposal}}/asks/{{ask}}/answer" + headers: {If-Match: "{{addedEtag}}", Idempotency-Key: answer-document} + body: {text: Synthetic explanation for this correction., additions: ["{{addition}}"]} + expect: {status: 200, json: {/status: in-review, /submissionVersion: "{{submissionVersion}}", /effectDigest: "{{effectDigest}}"}} + - id: await-answer-delivery + product: casework + as: reviewer + method: GET + path: "/v1/review-tasks/{{task}}" + headers: {Registry-Source-Profile: reviewer} + expect: {status: 200, json: {/taskId: "{{task}}", /requestId: "{{request}}", /marker: answered}} + poll: {maximumWaitMilliseconds: 60000, pollIntervalMilliseconds: 500} + capture: {answerTaskRevision: {type: pointer, pointer: /revision}} + - id: read-live-answer + product: casework + as: reviewer + method: GET + path: "/v1/review-tasks/{{task}}/context" + headers: {Registry-Source-Profile: reviewer} + expect: + status: 200 + json: + /asks/0/askId: "{{ask}}" + /asks/0/taskId: "{{task}}" + /asks/0/answer/text: Synthetic explanation for this correction. + /asks/0/answer/documents/0/id: "{{addition}}" + capture: + downloadEffect: {type: value, pointer: /asks/0/answer/documents/0/download/path, query: effectDigest} + downloadSchema: {type: value, pointer: /asks/0/answer/documents/0/download/path, query: contextSchemaDigest} + - id: download-cited-file + product: breg + as: reviewer + method: GET + path: "/v1/proposals/{{proposal}}/additions/{{addition}}?accessProfile=reviewer&submissionVersion={{submissionVersion}}&reviewAskId={{ask}}&effectDigest={{downloadEffect}}&contextSchemaDigest={{downloadSchema}}" + expect: {status: 200} - id: approve-correction product: casework as: reviewer method: POST path: "/v1/review-tasks/{{task}}/decisions" - headers: {If-Match: '"{{claimRevision}}"', Idempotency-Key: approve-correction, Registry-Source-Profile: reviewer} + headers: {If-Match: '"{{answerTaskRevision}}"', Idempotency-Key: approve-correction, Registry-Source-Profile: reviewer} body: {decision: {type: approve, outcome: approved}} expect: {status: 204} - id: read-review-result diff --git a/products/breg/acceptance/reviewed-evidence-journey/tests/test_proof.py b/products/breg/acceptance/reviewed-evidence-journey/tests/test_proof.py index 58991fd4bf..de657f03de 100644 --- a/products/breg/acceptance/reviewed-evidence-journey/tests/test_proof.py +++ b/products/breg/acceptance/reviewed-evidence-journey/tests/test_proof.py @@ -3,7 +3,210 @@ import copy import unittest -from proof import check_correlation, check_minimized, check_cleanup, check_observations +from proof import check_correlation, check_minimized, check_cleanup, check_observations, check_ask_loop + + +class AskLoopTests(unittest.TestCase): + def test_static_source_fixture_omits_only_oauth_replay(self): + from run_live import bind_static_fixture + + fixture = { + "cases": [ + { + "id": "positive", + "acquisition": { + "intercepts": [ + {"type": "endpoint", "endpoint": "registry"}, + {"type": "token-endpoint", "endpoint": "registry"}, + ], + "exchanges": [ + {"request": {"tokenRequest": True}}, + {"request": {"path": "/lookup"}, "response": {"status": 200}}, + ], + }, + }, + {"id": "timeout", "sourceFailure": "timeout"}, + ] + } + bind_static_fixture(fixture) + self.assertEqual( + fixture["cases"][0]["acquisition"], + { + "intercepts": [{"type": "endpoint", "endpoint": "registry"}], + "exchanges": [{"request": {"path": "/lookup"}, "response": {"status": 200}}], + }, + ) + self.assertEqual(fixture["cases"][1], {"id": "timeout", "sourceFailure": "timeout"}) + + def test_evidence_connection_uses_the_current_endpoint_binding(self): + from run_live import registry_connection + + self.assertEqual( + registry_connection("http://127.0.0.1:1234"), + { + "endpoints": { + "registry": { + "origin": "http://127.0.0.1:1234", + "authentication": { + "type": "static-authorization", + "tokenRef": "secret:file/source-token", + }, + } + } + }, + ) + + def test_literal_loopback_hook_uses_the_default_dns_policy(self): + from pathlib import Path + from types import SimpleNamespace + from run_live import breg_runtime + + harness = SimpleNamespace( + output=Path("/unused"), + secret_root=Path("/unused/secrets"), + hook_origin="http://127.0.0.1:1234", + db_configs={"source": {}}, + issuer_url="http://127.0.0.1:1235", + tokens={}, + ) + runtime = breg_runtime( + harness, "source", Path("/unused/package"), "http://127.0.0.1:1236", "http://127.0.0.1:1237" + ) + self.assertEqual(runtime["destinations"]["hooks"]["ask-observer"]["dnsFamily"], "dual-stack-strict") + + def observations(self): + submitted = {"id": "p1", "submissionVersion": 1, "effectDigest": "sha256:effects"} + ask = { + "askId": "q1", + "state": "open", + "wants": [{"kind": "document"}], + "askedAt": "2026-11-28T00:00:00Z", + "dueAt": "2026-11-28T01:00:00Z", + } + task = {"taskId": "t1", "requestId": "r1", "marker": "waiting"} + party = dict( + submitted, + state="submitted", + status="awaiting-party", + turn="party", + asks=[{"id": "q1", "state": "open", "dueAt": ask["dueAt"]}], + ) + answered = dict( + submitted, + state="submitted", + status="in-review", + turn="official", + asks=[ + {"id": "q1", "state": "answered", "answer": {"text": "PRIVATE-ANSWER", "additions": ["f1"]}} + ], + ) + document = { + "id": "f1", + "verificationStatus": "notRequired", + "download": { + "method": "GET", + "operation": "get-review-context", + "accessProfile": "reviewer", + "path": "/v1/proposals/p1/additions/f1?reviewAskId=q1&submissionVersion=1", + }, + } + return { + "submitted": submitted, + "accepted": {"requestId": "r1"}, + "asked": {"task": task, "ask": ask}, + "party": party, + "partyPage": {"items": [party]}, + "hook": { + "id": "e1", + "type": "proposal.asked", + "data": {"proposalId": "p1", "submissionVersion": 1, "transition": "asked"}, + }, + "answered": answered, + "additionId": "f1", + "task": dict(task, marker="answered"), + "context": { + "taskId": "t1", + "requestId": "r1", + "asks": [ + { + "askId": "q1", + "taskId": "t1", + "state": "answered", + "answer": {"text": "PRIVATE-ANSWER", "documents": [document]}, + } + ], + }, + "download": b"PRIVATE-FILE", + "createdRequestIds": ["r1"], + "correlations": [{"requestId": "r1"}] * 3, + "decidedTask": dict( + task, + state="decided", + decidedByCaller=True, + decisionReceipt={"decision": "approve", "outcome": "approved"}, + ), + "requests": [{"actor": "producer", "method": "POST", "status": 201}], + } + + def test_served_loop_returns_only_identifiers_and_states(self): + summary = check_ask_loop(self.observations(), "PRIVATE-ANSWER", b"PRIVATE-FILE") + self.assertEqual(summary["requestId"], "r1") + self.assertEqual(summary["taskId"], "t1") + self.assertNotIn("PRIVATE", str(summary)) + self.assertEqual(summary["marker"], "answered") + + def test_mirror_compares_absolute_deadlines_across_utc_spellings(self): + observations = self.observations() + observations["party"]["asks"][0]["dueAt"] = "2026-11-28T01:00:00+00:00" + check_ask_loop(observations, "PRIVATE-ANSWER", b"PRIVATE-FILE") + + def test_each_loop_boundary_rejects_a_mismatched_observation(self): + mutations = [ + ("party", "status", "in-review"), + ("party", "turn", "official"), + ("answered", "submissionVersion", 2), + ("answered", "effectDigest", "other"), + ("answered", "status", "awaiting-party"), + ("task", "marker", "waiting"), + ("task", "taskId", "another-task"), + ("context", "requestId", "another-request"), + ("decidedTask", "taskId", "another-task"), + ("decidedTask", "decidedByCaller", False), + ] + for member, key, value in mutations: + observations = self.observations() + observations[member][key] = value + with self.subTest(member=member, key=key), self.assertRaises(AssertionError): + check_ask_loop(observations, "PRIVATE-ANSWER", b"PRIVATE-FILE") + for member, value in [ + ("partyPage", {"items": []}), + ("createdRequestIds", ["r1", "r2"]), + ("download", b"other"), + ("requests", [{"actor": "applicant"}]), + ]: + observations = self.observations() + observations[member] = value + with self.subTest(member=member), self.assertRaises(AssertionError): + check_ask_loop(observations, "PRIVATE-ANSWER", b"PRIVATE-FILE") + + def test_answer_and_citation_are_read_from_the_right_ask(self): + for change in ("text", "file", "ask", "link", "deadline", "event"): + observations = self.observations() + answer = observations["context"]["asks"][0]["answer"] + if change == "text": + answer["text"] = "another answer" + elif change == "file": + answer["documents"][0]["id"] = "another-file" + elif change == "ask": + observations["context"]["asks"][0]["askId"] = "another-ask" + elif change == "link": + answer["documents"][0]["download"]["path"] = "/v1/proposals/p1/additions/f1?reviewAskId=q2" + elif change == "deadline": + del observations["asked"]["ask"]["dueAt"] + else: + observations["hook"]["type"] = "proposal.submitted" + with self.subTest(change=change), self.assertRaises(AssertionError): + check_ask_loop(observations, "PRIVATE-ANSWER", b"PRIVATE-FILE") class CorrelationTests(unittest.TestCase): diff --git a/products/breg/contracts/explain/LifecycleExplanation.schema.json b/products/breg/contracts/explain/LifecycleExplanation.schema.json index 101c4d2901..f717446a5e 100644 --- a/products/breg/contracts/explain/LifecycleExplanation.schema.json +++ b/products/breg/contracts/explain/LifecycleExplanation.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://id.registrystack.org/schemas/breg/lifecycle-explanation/lifecycle-explanation.v1alpha8.schema.json", + "$id": "https://id.registrystack.org/schemas/breg/lifecycle-explanation/lifecycle-explanation.v1alpha9.schema.json", "title": "LifecycleExplanation", "description": "The native engine-owned Proposal lifecycle, pinned independently of project source.", "type": "object", @@ -12,7 +12,7 @@ ], "properties": { "apiVersion": { - "const": "id.registrystack.org/formats/breg/lifecycle-explanation/v1alpha8" + "const": "id.registrystack.org/formats/breg/lifecycle-explanation/v1alpha9" }, "kind": { "const": "BRegLifecycleExplanation" @@ -74,6 +74,14 @@ ], "id": "explicit-contract-rebase" }, + { + "description": "Revise and Rebase of a submitted Proposal require awaiting-party or in-review status from the shared status and turn rule. Approval and review-free processing preserve the current submission until Apply or Cancel, unless a recovery returns the turn to the party. Rebase of a draft is unchanged.", + "events": [ + "revise", + "rebase" + ], + "id": "submission-status" + }, { "description": "Application revalidates the frozen Action revision, submission version, effect digest, current caller or restricted executor authority, and any required current approval and Evidence. Manual and automatic execution use the same application boundary.", "events": [ @@ -104,6 +112,12 @@ "incomingTransitions": 4, "initial": true, "outgoingTransitions": 4, + "statuses": [ + { + "condition": "Always while the Proposal is in this state.", + "status": "draft" + } + ], "terminal": false, "turns": [ { @@ -118,14 +132,32 @@ "incomingTransitions": 2, "initial": false, "outgoingTransitions": 6, + "statuses": [ + { + "condition": "The submission package is blocked; Review is pending or retrying with an open ask; Review ended without a usable approval; or, after approval or when Review is not required, application is not manual and is blocked without recovery retry.", + "status": "awaiting-party" + }, + { + "condition": "The submission package is not blocked, Review is pending or retrying, and no ask is open.", + "status": "in-review" + }, + { + "condition": "Review is approved and neither the submission package nor application needs action by the party.", + "status": "approved" + }, + { + "condition": "Review is not required and neither the submission package nor application needs action by the party.", + "status": "processing" + } + ], "terminal": false, "turns": [ { - "condition": "The submission package is blocked; Review ended without a usable approval; or, after approval or when Review is not required, application is not manual and is blocked without recovery retry.", + "condition": "The submission package is blocked; Review is pending or retrying with an open ask; Review ended without a usable approval; or, after approval or when Review is not required, application is not manual and is blocked without recovery retry.", "turn": "party" }, { - "condition": "The submission package is not blocked, and either Review is pending or being retried, or, after approval or when Review is not required, application is manual or is blocked with recovery retry.", + "condition": "The submission package is not blocked, and either Review is pending or being retried without an open ask, or, after approval or when Review is not required, application is manual or is blocked with recovery retry.", "turn": "official" }, { @@ -140,6 +172,12 @@ "incomingTransitions": 2, "initial": false, "outgoingTransitions": 0, + "statuses": [ + { + "condition": "Always while the Proposal is in this state.", + "status": "cancelled" + } + ], "terminal": true, "turns": [ { @@ -154,6 +192,12 @@ "incomingTransitions": 1, "initial": false, "outgoingTransitions": 0, + "statuses": [ + { + "condition": "Always while the Proposal is in this state.", + "status": "applied" + } + ], "terminal": true, "turns": [ { @@ -168,6 +212,12 @@ "incomingTransitions": 1, "initial": false, "outgoingTransitions": 0, + "statuses": [ + { + "condition": "Always while the Proposal is in this state.", + "status": "rejected" + } + ], "terminal": true, "turns": [ { @@ -183,74 +233,74 @@ "event": "edit", "from": "draft", "guard": "The Proposal is draft; replace validated Action input and advance its lifecycle revision.", - "to": "draft", - "recoveryReasons": [] + "recoveryReasons": [], + "to": "draft" }, { "event": "submit", "from": "draft", "guard": "The Proposal is draft and this submission version has not been frozen; accept the prepared plan and freeze its digest.", - "to": "submitted", - "recoveryReasons": [] + "recoveryReasons": [], + "to": "submitted" }, { "event": "rebase", "from": "draft", "guard": "The Proposal is draft; explicitly bind the active Action definition and preserve the current submission version.", - "to": "draft", - "recoveryReasons": [] + "recoveryReasons": [], + "to": "draft" }, { "event": "cancel", "from": "draft", "guard": "The Proposal is draft or submitted; cancel without applying its effects.", - "to": "cancelled", - "recoveryReasons": [] + "recoveryReasons": [], + "to": "cancelled" }, { "event": "revise", "from": "submitted", "guard": "The Proposal is submitted; open a new draft submission version without modifying the frozen prior submission.", - "to": "draft", - "recoveryReasons": [] + "recoveryReasons": [], + "to": "draft" }, { "event": "rebase", "from": "submitted", "guard": "The Proposal is submitted; open a new draft version explicitly bound to the active Action definition.", - "to": "draft", - "recoveryReasons": [] + "recoveryReasons": [], + "to": "draft" }, { "event": "retry", "from": "submitted", "guard": "The Proposal remains submitted; schedule another eligible review or application attempt without changing the frozen plan.", - "to": "submitted", "recoveryReasons": [ "dependency-outage", "lease-expired" - ] + ], + "to": "submitted" }, { "event": "cancel", "from": "submitted", "guard": "The Proposal is draft or submitted; cancel without applying its effects.", - "to": "cancelled", - "recoveryReasons": [] + "recoveryReasons": [], + "to": "cancelled" }, { "event": "apply", "from": "submitted", "guard": "The submission version, displayed digest, frozen Action contract, authorized targets, commit guards, and required approval match the application attempt.", - "to": "applied", - "recoveryReasons": [] + "recoveryReasons": [], + "to": "applied" }, { "event": "reject", "from": "submitted", "guard": "The configured review authority returned a rejected result for the exact current submission. A rejection is terminal; a changes-requested result leaves the Proposal submitted and revisable.", - "to": "rejected", - "recoveryReasons": [] + "recoveryReasons": [], + "to": "rejected" } ] } diff --git a/products/breg/contracts/security-invariant-matrix.yaml b/products/breg/contracts/security-invariant-matrix.yaml index 3bd4be5955..7a3911d36e 100644 --- a/products/breg/contracts/security-invariant-matrix.yaml +++ b/products/breg/contracts/security-invariant-matrix.yaml @@ -237,3 +237,26 @@ invariants: - {"id": "BREG-SEC-222", "state": "enforced", "targetWave": "W5", "threat": "Applying a Proposal fills a Record slot that already holds a file, or commits part of its effects when a promotion fails, so the file a decision rests on changes or a record exists without the file the Proposal froze.", "enforcementPoint": "the promotion inserts the record reference in the apply transaction after the effect writes its record revision; the reference key (Record type, record, slot) refuses a second write, live or erased, and any refusal rolls back the records, revisions, references, outbox and the Proposal's application", "refusal": "Refuse with 409 attachment.slot-write-once, keep the stored file, and leave no record, revision or reference from the apply.", "negativeId": "BREG-NEG-222", "negativeTest": {"path": "crates/registry-breg/tests/postgres_record_attachments.rs", "name": "promotion_into_a_filled_slot_answers_409_and_rolls_back_the_whole_apply"}} - {"id": "BREG-SEC-223", "state": "enforced", "targetWave": "W5", "threat": "Operator erasure of a Proposal deletes the bytes of a file the Proposal promoted to a Record, or keeps the bytes of a Proposal file nothing promoted.", "enforcementPoint": "promotion adds a Record reference to the content hash the Proposal file holds and copies no bytes; Proposal erasure tombstones the Proposal references and retire_unreferenced deletes a hash under the content-hash lock only when no live Proposal or Record reference remains", "refusal": "Keep promoted bytes readable through the Record download after the Proposal is erased. Remove the bytes of Proposal files nothing promoted.", "negativeId": "BREG-NEG-223", "negativeTest": {"path": "crates/registry-breg/tests/postgres_record_attachments.rs", "name": "an_applied_proposal_promotes_its_file_by_reference_and_erasure_keeps_it"}} - {"id": "BREG-SEC-224", "state": "enforced", "targetWave": "W5", "threat": "A one-call Action loses a concurrent update, writes against a revision its guards did not see, or tells a hidden record from a missing one.", "enforcementPoint": "an immediate Action declares concurrency: current-revision; bregctl check refuses it unless every record it patches has an equals or isNull commit guard that its own write makes false, and refuses a revision: unchanged guard, a function plan that writes an existing record, and any fromInput or fromEffect value written into an existing record; at runtime the guards are evaluated against the row locked FOR UPDATE and the patch applies to that same locked row, so a second write against the same record fails the guard", "refusal": "Refuse the project with breg.action.concurrency-revision-guard, breg.action.concurrency-caller-value or breg.action.concurrency-guard-missing. Answer a stale call, a missing record and a record outside the caller's row boundary with the generic 412 precondition.failed, with identical bodies apart from traceId.", "negativeId": "BREG-NEG-224", "negativeTest": {"path": "crates/registry-breg/tests/postgres_immediate_actions.rs", "name": "two_concurrent_current_revision_invocations_commit_exactly_once"}} + # Submitted additions and exact ETag/idempotency admission: crates/registry-breg/tests/support/proposal_additions.rs::additions_keep_the_submission_and_digest_but_fence_tabs_and_replay + # Live review additions retain exact context disclosure: crates/registry-breg/tests/support/proposal_additions.rs::additions_reviewer_reads_live_files_under_the_exact_context_binding + # Shared addition references survive until exact detail erasure: crates/registry-breg/tests/support/proposal_additions.rs::additions_keep_shared_blobs_live_until_their_retention_erases_them + # Added event, hook selection and minimized audit: crates/registry-breg/tests/support/proposal_additions.rs::additions_emit_a_value_free_event_and_enqueue_the_selected_hook + - {"id":"BREG-SEC-225","state":"enforced","targetWave":"W5","threat":"An applicant uploads supporting files without Add authority, outside Proposal ownership or row boundaries, or through a stale task grant or standing agent.","enforcementPoint":"Declared additions slot, Add operation and writableAttachments admission; current Proposal target and caller ownership authorization; fresh task-grant status and submitted/open-review checks under the Proposal lock.","refusal":"Conceal missing operation authority and standing agents; refuse lost ownership, target visibility, stale task grants and closed lifecycle state before any addition reference commits.","negativeId":"BREG-NEG-225","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_additions_authority.rs","name":"additions_require_add_even_when_the_caller_holds_edit_or_get"}} + - {"id":"BREG-SEC-226","state":"enforced","targetWave":"W5","threat":"A Proposal or reviewer download releases an addition outside the caller's slot read grant or the live review-context projection.","enforcementPoint":"Get with readableAttachments for ordinary descriptors and downloads; GetReviewContext with the named field and exact submission/effect/schema binding; fresh context disclosure and verified file identity under the hash lock.","refusal":"Hide addition metadata and downloads without the slot read grant, and conceal a reviewer file absent from the bound live context or using a different field, submission, effect or schema.","negativeId":"BREG-NEG-226","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_additions.rs","name":"additions_reviewer_reads_live_files_under_the_exact_context_binding"}} + - {"id":"BREG-SEC-227","state":"enforced","targetWave":"W5","threat":"A supporting addition alters the frozen effects or attachment manifest and changes what an accepted review permits Apply to write.","enforcementPoint":"Additions have separate live references and only advance workflow revision; Proposal snapshots, effect digests and Apply's original attachment-manifest equality check remain frozen.","refusal":"Keep the submission version, snapshot, effect digest and manifest unchanged after each addition, and require Apply to execute the exact originally reviewed effects.","negativeId":"BREG-NEG-227","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_additions.rs","name":"additions_leave_the_frozen_manifest_unchanged_and_apply_still_succeeds"}} + - {"id":"BREG-SEC-228","state":"enforced","targetWave":"W5","threat":"Attachment cleanup removes bytes a live addition still needs, or Proposal detail erasure leaves its addition references and private metadata retained.","enforcementPoint":"Hash-locked shared blob reachability includes additions, ordinary Proposal attachments and Record references; detail erasure plans and removes the exact combined reference count.","refusal":"Retain shared bytes until the final live reference is erased; tombstone addition detail and clean unreferenced bytes through the existing database or external-store cleanup path.","negativeId":"BREG-NEG-228","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_additions.rs","name":"additions_keep_shared_blobs_live_until_their_retention_erases_them"}} + - {"id":"BREG-SEC-229","state":"enforced","targetWave":"W5","threat":"A standing or task-granted agent, a delegated actor or a service holding get-review-context receives an applicant's answers or downloads the files they cite.","enforcementPoint":"Proposal admission marks only a verified human caller on a human or any-kind profile, with no delegated actor and no task grant, as receiving answers; the review-context projection and both ask-bound download checks require that mark under the current review binding.","refusal":"Omit context.asks and record no ask disclosure for any other caller, and conceal the ask-bound download as for any file the caller may not read. A file reachable through an authored additions context field follows that field's grant.","negativeId":"BREG-NEG-229","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks.rs","name":"agents_holding_review_context_authority_get_no_answers_and_no_cited_files"}} + - {"id":"BREG-SEC-230","state":"enforced","targetWave":"W5","threat":"The batch review-context inbox read ships applicant answers nobody is shown and records that the reviewer saw them.","enforcementPoint":"The batch route admits each item without answer delivery, so the review-context projection serves no asks and the read audit carries no ask disclosure; only the single-Proposal review-context read serves answers.","refusal":"Serve every batch item without context.asks and without an ask disclosure marker.","negativeId":"BREG-NEG-230","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks.rs","name":"batch_review_context_carries_no_answers_and_records_no_ask_disclosure"}} + - {"id":"BREG-SEC-231","state":"enforced","targetWave":"W5","threat":"A Get holder that may not answer, such as a status profile without readableInputs, another officer, a standing or task-granted agent or a service, reads reviewers' questions and the applicant's answer text from the Proposal document, its list items or a command response, or an agent or service holding answer answers in the applicant's name.","enforcementPoint":"Answer admission requires the human caller test: a verified human on a human or any-kind profile, with no delegated actor and no task grant. The Proposal document serves the asks member only when the selected profile also passes Answer admission and the document check for that Proposal.","refusal":"Serve no asks member to any other caller and record no ask disclosure for it; refuse the answer command for any caller that fails the human test.","negativeId":"BREG-NEG-231","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks.rs","name":"asks_reach_only_a_human_caller_who_may_answer_this_proposal"}} + - {"id":"BREG-SEC-232","state":"enforced","targetWave":"W5","threat":"A caller with a narrower row boundary calls manual Apply on an approved Proposal whose result lies outside that boundary, blocking it for everyone and sending the applicant back to revise.","enforcementPoint":"Manual Apply checks the after-snapshot against the applying caller's boundary; that refusal is not a Proposal-level application refusal, so the transaction rolls back.","refusal":"Answer 403 write.outside-boundary and persist nothing: no application-refused block and no workflow revision change, so a caller whose boundary covers the result can still Apply.","negativeId":"BREG-NEG-232","negativeTest":{"path":"crates/registry-breg/tests/postgres_proposal.rs","name":"admitted_apply_outside_the_callers_write_boundary_persists_nothing"}} + - {"id":"BREG-SEC-233","state":"enforced","targetWave":"W4","threat":"A caller without the applicant operation, ownership, human identity or current row boundary answers an ask.","enforcementPoint":"Human-only Answer admission, ownership and frozen target readmission before mutation.","refusal":"Conceal ungranted, non-owner and agent callers; refuse moved targets before storing an answer.","negativeId":"BREG-NEG-233","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"answering_requires_the_human_owner_operation_and_current_row_boundary"}} + - {"id":"BREG-SEC-234","state":"enforced","targetWave":"W4","threat":"A stale delegated task grant answers for the applicant.","enforcementPoint":"Human-only Answer admission excludes every task-granted caller even when its profile lists Answer.","refusal":"Conceal the answer route without an answer row.","negativeId":"BREG-NEG-234","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"a_stale_task_grant_cannot_answer_even_when_its_profile_lists_answer"}} + - {"id":"BREG-SEC-235","state":"enforced","targetWave":"W4","threat":"Answer delivery forwards the applicant token, answer text or files to the provider.","enforcementPoint":"Feed, ask read and answer delivery use the configured producer credential and the value-free protocol.","refusal":"Send only the frozen subject and stored answer time, preserving the same key on retries.","negativeId":"BREG-NEG-235","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks.rs","name":"answer_delivery_retries_transient_exchanges_with_the_exact_key_and_stored_time"}} + - {"id":"BREG-SEC-236","state":"enforced","targetWave":"W4","threat":"Erasure leaves question, answer, actor or cited-file detail behind.","enforcementPoint":"Per-version Proposal retention exact-count plan and erasure transaction.","refusal":"Scrub question and answer text, answering actor and citation references with that submission detail.","negativeId":"BREG-NEG-236","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks.rs","name":"operator_erasure_counts_and_scrubs_question_answer_actor_and_cited_files_per_version"}} + - {"id":"BREG-SEC-237","state":"enforced","targetWave":"W4","threat":"A lifecycle command discloses the decision or inputs without Get.","enforcementPoint":"Command response uses the same Get disclosure projection as an ordinary read.","refusal":"Omit the decision and inputs without Get authority.","negativeId":"BREG-NEG-237","negativeTest":{"path":"crates/registry-breg/tests/postgres_proposal.rs","name":"command_response_withholds_the_decision_from_a_profile_without_get"}} + - {"id":"BREG-SEC-238","state":"enforced","targetWave":"W4","threat":"An exact receipt replay discloses a public reason without its disclosure audit marker.","enforcementPoint":"Replay terminal audit derives the public-reason marker from the stored served body.","refusal":"Return the exact receipt and audit its served public reason.","negativeId":"BREG-NEG-238","negativeTest":{"path":"crates/registry-breg/tests/postgres_proposal.rs","name":"apply_replay_marks_the_public_reason_it_serves"}} + - {"id":"BREG-SEC-239","state":"enforced","targetWave":"W4","threat":"A narrowed readable-input grant recovers a broader stored receipt.","enforcementPoint":"Current disclosure fingerprint is checked before exact receipt release.","refusal":"Refuse recovery without reexecution or leaking previously readable input.","negativeId":"BREG-NEG-239","negativeTest":{"path":"crates/registry-breg/tests/postgres_proposal.rs","name":"narrowed_input_disclosure_refuses_the_old_exact_receipt"}} + - {"id":"BREG-SEC-240","state":"enforced","targetWave":"W4","threat":"A reviewer uses a stale review binding to download a previous round cited file.","enforcementPoint":"Ask-bound file read checks the current request, submission, effect and context binding.","refusal":"Conceal a stale binding and return no bytes.","negativeId":"BREG-NEG-240","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks.rs","name":"a_human_reviewer_under_a_stale_binding_is_refused_the_previous_rounds_cited_file"}} + - {"id":"BREG-SEC-241","state":"enforced","targetWave":"W4","threat":"A concealed or deleted target at Apply leaves a party-visible block or changes the Proposal revision.","enforcementPoint":"Apply target readmission preserves concealment before recording recoverable application refusals.","refusal":"Refuse with precondition.failed, persist no block and leave the Proposal unchanged.","negativeId":"BREG-NEG-241","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_final.rs","name":"concealed_or_deleted_apply_targets_create_no_block_or_revision"}} + - {"id":"BREG-SEC-242","state":"enforced","targetWave":"W4","threat":"A claim, ask or decide preflight discloses answers and audits a disclosure nobody displayed.","enforcementPoint":"Single review-context read includes intrinsic answers only with include=answers and existing human review authority.","refusal":"Omit asks and their disclosure marker on preflight; audit actual displayed answers.","negativeId":"BREG-NEG-242","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"only_an_explicit_display_read_serves_and_audits_intrinsic_answers"}} + - {"id":"BREG-SEC-243","state":"enforced","targetWave":"W4","threat":"Pruning value-free dedupe receipts causes a cursor reset to fetch or duplicate a retained ask.","enforcementPoint":"Maintenance uses the observation recovery window; feed processing checks the stored mirror before network I/O.","refusal":"Prune exact bounded receipt counts while preserving mirrored questions and answers and skipping stored observations.","negativeId":"BREG-NEG-243","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"pruning_a_receipt_then_resetting_the_cursor_never_refetches_or_duplicates_its_stored_ask"}} diff --git a/products/breg/contracts/security-test-traceability.yaml b/products/breg/contracts/security-test-traceability.yaml index 3128387b06..26f3d6b79f 100644 --- a/products/breg/contracts/security-test-traceability.yaml +++ b/products/breg/contracts/security-test-traceability.yaml @@ -276,3 +276,28 @@ traceability: # Compile rules refuse a revision guard, a caller value and a missing falsifiable guard: crates/registry-breg/tests/immediate_action_requirements.rs::current_revision_needs_a_guard_the_write_falsifies # A missing and a hidden record answer identically: crates/registry-breg/tests/postgres_immediate_actions.rs::a_current_revision_action_does_not_tell_a_hidden_record_from_a_missing_one - {"id": "BREG-SEC-224", "state": "enforced", "negativeId": "BREG-NEG-224", "negativeTest": {"path": "crates/registry-breg/tests/postgres_immediate_actions.rs", "name": "two_concurrent_current_revision_invocations_commit_exactly_once"}} + # Submitted additions and exact ETag/idempotency admission: crates/registry-breg/tests/support/proposal_additions.rs::additions_keep_the_submission_and_digest_but_fence_tabs_and_replay + # Live review additions retain exact context disclosure: crates/registry-breg/tests/support/proposal_additions.rs::additions_reviewer_reads_live_files_under_the_exact_context_binding + # Shared addition references survive until exact detail erasure: crates/registry-breg/tests/support/proposal_additions.rs::additions_keep_shared_blobs_live_until_their_retention_erases_them + # Added event, hook selection and minimized audit: crates/registry-breg/tests/support/proposal_additions.rs::additions_emit_a_value_free_event_and_enqueue_the_selected_hook + - {"id":"BREG-SEC-225","state":"enforced","negativeId":"BREG-NEG-225","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_additions_authority.rs","name":"additions_require_add_even_when_the_caller_holds_edit_or_get"}} + - {"id":"BREG-SEC-226","state":"enforced","negativeId":"BREG-NEG-226","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_additions.rs","name":"additions_reviewer_reads_live_files_under_the_exact_context_binding"}} + - {"id":"BREG-SEC-227","state":"enforced","negativeId":"BREG-NEG-227","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_additions.rs","name":"additions_leave_the_frozen_manifest_unchanged_and_apply_still_succeeds"}} + - {"id":"BREG-SEC-228","state":"enforced","negativeId":"BREG-NEG-228","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_additions.rs","name":"additions_keep_shared_blobs_live_until_their_retention_erases_them"}} + # Stale review binding: crates/registry-breg/tests/support/proposal_review_asks.rs::a_human_reviewer_under_a_stale_binding_is_refused_the_previous_rounds_cited_file + - {"id":"BREG-SEC-229","state":"enforced","negativeId":"BREG-NEG-229","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks.rs","name":"agents_holding_review_context_authority_get_no_answers_and_no_cited_files"}} + - {"id":"BREG-SEC-230","state":"enforced","negativeId":"BREG-NEG-230","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks.rs","name":"batch_review_context_carries_no_answers_and_records_no_ask_disclosure"}} + # Human reviewer without answer: crates/registry-breg/tests/support/proposal_review_asks.rs::a_human_reviewer_without_answer_reads_answers_only_through_the_review_context + - {"id":"BREG-SEC-231","state":"enforced","negativeId":"BREG-NEG-231","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks.rs","name":"asks_reach_only_a_human_caller_who_may_answer_this_proposal"}} + - {"id":"BREG-SEC-232","state":"enforced","negativeId":"BREG-NEG-232","negativeTest":{"path":"crates/registry-breg/tests/postgres_proposal.rs","name":"admitted_apply_outside_the_callers_write_boundary_persists_nothing"}} + - {"id":"BREG-SEC-233","state":"enforced","negativeId":"BREG-NEG-233","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"answering_requires_the_human_owner_operation_and_current_row_boundary"}} + - {"id":"BREG-SEC-234","state":"enforced","negativeId":"BREG-NEG-234","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"a_stale_task_grant_cannot_answer_even_when_its_profile_lists_answer"}} + - {"id":"BREG-SEC-235","state":"enforced","negativeId":"BREG-NEG-235","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks.rs","name":"answer_delivery_retries_transient_exchanges_with_the_exact_key_and_stored_time"}} + - {"id":"BREG-SEC-236","state":"enforced","negativeId":"BREG-NEG-236","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks.rs","name":"operator_erasure_counts_and_scrubs_question_answer_actor_and_cited_files_per_version"}} + - {"id":"BREG-SEC-237","state":"enforced","negativeId":"BREG-NEG-237","negativeTest":{"path":"crates/registry-breg/tests/postgres_proposal.rs","name":"command_response_withholds_the_decision_from_a_profile_without_get"}} + - {"id":"BREG-SEC-238","state":"enforced","negativeId":"BREG-NEG-238","negativeTest":{"path":"crates/registry-breg/tests/postgres_proposal.rs","name":"apply_replay_marks_the_public_reason_it_serves"}} + - {"id":"BREG-SEC-239","state":"enforced","negativeId":"BREG-NEG-239","negativeTest":{"path":"crates/registry-breg/tests/postgres_proposal.rs","name":"narrowed_input_disclosure_refuses_the_old_exact_receipt"}} + - {"id":"BREG-SEC-240","state":"enforced","negativeId":"BREG-NEG-240","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks.rs","name":"a_human_reviewer_under_a_stale_binding_is_refused_the_previous_rounds_cited_file"}} + - {"id":"BREG-SEC-241","state":"enforced","negativeId":"BREG-NEG-241","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_final.rs","name":"concealed_or_deleted_apply_targets_create_no_block_or_revision"}} + - {"id":"BREG-SEC-242","state":"enforced","negativeId":"BREG-NEG-242","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"only_an_explicit_display_read_serves_and_audits_intrinsic_answers"}} + - {"id":"BREG-SEC-243","state":"enforced","negativeId":"BREG-NEG-243","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"pruning_a_receipt_then_resetting_the_cursor_never_refetches_or_duplicates_its_stored_ask"}} diff --git a/products/breg/examples/README.md b/products/breg/examples/README.md index 37bc2c5c7a..175ec3f110 100644 --- a/products/breg/examples/README.md +++ b/products/breg/examples/README.md @@ -1,6 +1,9 @@ # Standalone BReg examples `minimal/` is a directory project with one Record type and generated CRUD. +[`required-attachment/`](required-attachment/README.md) adds a manual name +correction whose Submit requires a supporting text file. It includes a +reproducible OpenAPI document with the attachment problem responses. `reviewed-change/registry.yaml` adds one fixed-plan name correction to one Record type. It requires an external review authority and uses the omitted automatic application default. Its explicit profile grants record creation and reading, diff --git a/products/breg/examples/formats/ctl-report.json b/products/breg/examples/formats/ctl-report.json index 83479bc25d..411cd24c33 100644 --- a/products/breg/examples/formats/ctl-report.json +++ b/products/breg/examples/formats/ctl-report.json @@ -1664,13 +1664,13 @@ "protocol": "id.registrystack.org/protocols/review/v1" } ], - "revision": "sha256:97f59e130fd42843a91e60744a48f8c425a6df587fbdc804f05058c60a713b45", + "revision": "sha256:a6e151af7e19b3e1675d76c67cc5d7c6c3c52fb009f857ebe534e8a913c2e4e0", "statisticalDatasets": [] }, "kind": "BRegCtlReport", "ok": true, "profile": "authoring", - "revision": "sha256:97f59e130fd42843a91e60744a48f8c425a6df587fbdc804f05058c60a713b45", + "revision": "sha256:a6e151af7e19b3e1675d76c67cc5d7c6c3c52fb009f857ebe534e8a913c2e4e0", "status": "complete", "version": "0.49.0-dev" } diff --git a/products/breg/examples/formats/explain/actions-explanation.json b/products/breg/examples/formats/explain/actions-explanation.json index a3af9259d5..e0bd5ace14 100644 --- a/products/breg/examples/formats/explain/actions-explanation.json +++ b/products/breg/examples/formats/explain/actions-explanation.json @@ -1641,6 +1641,6 @@ "protocol": "id.registrystack.org/protocols/review/v1" } ], - "revision": "sha256:97f59e130fd42843a91e60744a48f8c425a6df587fbdc804f05058c60a713b45", + "revision": "sha256:a6e151af7e19b3e1675d76c67cc5d7c6c3c52fb009f857ebe534e8a913c2e4e0", "statisticalDatasets": [] } diff --git a/products/breg/examples/formats/explain/authored-display-actions-explanation.json b/products/breg/examples/formats/explain/authored-display-actions-explanation.json index 2b81453968..24e637f59b 100644 --- a/products/breg/examples/formats/explain/authored-display-actions-explanation.json +++ b/products/breg/examples/formats/explain/authored-display-actions-explanation.json @@ -366,7 +366,7 @@ ], "registryId": "labelled-directory", "reviewAuthorities": [], - "revision": "sha256:d587e3b406851c3d1b8f5c9817e9fd2fc2b1f5c1d5eca6240a23aea3273e8ff8", + "revision": "sha256:a8029771ed51a121b4a6bb38774f704489fe6549f130b601aba652ee468e547e", "statisticalDatasets": [ { "accessProfiles": { diff --git a/products/breg/examples/formats/explain/authored-display-model-explanation.json b/products/breg/examples/formats/explain/authored-display-model-explanation.json index 7bb86dc7c8..7a4c403e4f 100644 --- a/products/breg/examples/formats/explain/authored-display-model-explanation.json +++ b/products/breg/examples/formats/explain/authored-display-model-explanation.json @@ -634,7 +634,7 @@ "registryId": "labelled-directory", "requiresPostgis": false, "reviewAuthorities": [], - "revision": "sha256:d587e3b406851c3d1b8f5c9817e9fd2fc2b1f5c1d5eca6240a23aea3273e8ff8", + "revision": "sha256:a8029771ed51a121b4a6bb38774f704489fe6549f130b601aba652ee468e547e", "statisticalDatasets": [ { "accessProfiles": { diff --git a/products/breg/examples/formats/explain/lifecycle-explanation.json b/products/breg/examples/formats/explain/lifecycle-explanation.json index 91f114ddd0..0171369703 100644 --- a/products/breg/examples/formats/explain/lifecycle-explanation.json +++ b/products/breg/examples/formats/explain/lifecycle-explanation.json @@ -1,5 +1,5 @@ { - "apiVersion": "id.registrystack.org/formats/breg/lifecycle-explanation/v1alpha8", + "apiVersion": "id.registrystack.org/formats/breg/lifecycle-explanation/v1alpha9", "kind": "BRegLifecycleExplanation", "lifecycles": [ { @@ -57,6 +57,14 @@ ], "id": "explicit-contract-rebase" }, + { + "description": "Revise and Rebase of a submitted Proposal require awaiting-party or in-review status from the shared status and turn rule. Approval and review-free processing preserve the current submission until Apply or Cancel, unless a recovery returns the turn to the party. Rebase of a draft is unchanged.", + "events": [ + "revise", + "rebase" + ], + "id": "submission-status" + }, { "description": "Application revalidates the frozen Action revision, submission version, effect digest, current caller or restricted executor authority, and any required current approval and Evidence. Manual and automatic execution use the same application boundary.", "events": [ @@ -87,6 +95,12 @@ "incomingTransitions": 4, "initial": true, "outgoingTransitions": 4, + "statuses": [ + { + "condition": "Always while the Proposal is in this state.", + "status": "draft" + } + ], "terminal": false, "turns": [ { @@ -101,14 +115,32 @@ "incomingTransitions": 2, "initial": false, "outgoingTransitions": 6, + "statuses": [ + { + "condition": "The submission package is blocked; Review is pending or retrying with an open ask; Review ended without a usable approval; or, after approval or when Review is not required, application is not manual and is blocked without recovery retry.", + "status": "awaiting-party" + }, + { + "condition": "The submission package is not blocked, Review is pending or retrying, and no ask is open.", + "status": "in-review" + }, + { + "condition": "Review is approved and neither the submission package nor application needs action by the party.", + "status": "approved" + }, + { + "condition": "Review is not required and neither the submission package nor application needs action by the party.", + "status": "processing" + } + ], "terminal": false, "turns": [ { - "condition": "The submission package is blocked; Review ended without a usable approval; or, after approval or when Review is not required, application is not manual and is blocked without recovery retry.", + "condition": "The submission package is blocked; Review is pending or retrying with an open ask; Review ended without a usable approval; or, after approval or when Review is not required, application is not manual and is blocked without recovery retry.", "turn": "party" }, { - "condition": "The submission package is not blocked, and either Review is pending or being retried, or, after approval or when Review is not required, application is manual or is blocked with recovery retry.", + "condition": "The submission package is not blocked, and either Review is pending or being retried without an open ask, or, after approval or when Review is not required, application is manual or is blocked with recovery retry.", "turn": "official" }, { @@ -123,6 +155,12 @@ "incomingTransitions": 2, "initial": false, "outgoingTransitions": 0, + "statuses": [ + { + "condition": "Always while the Proposal is in this state.", + "status": "cancelled" + } + ], "terminal": true, "turns": [ { @@ -137,6 +175,12 @@ "incomingTransitions": 1, "initial": false, "outgoingTransitions": 0, + "statuses": [ + { + "condition": "Always while the Proposal is in this state.", + "status": "applied" + } + ], "terminal": true, "turns": [ { @@ -151,6 +195,12 @@ "incomingTransitions": 1, "initial": false, "outgoingTransitions": 0, + "statuses": [ + { + "condition": "Always while the Proposal is in this state.", + "status": "rejected" + } + ], "terminal": true, "turns": [ { diff --git a/products/breg/examples/formats/explain/model-explanation.json b/products/breg/examples/formats/explain/model-explanation.json index 9c40603995..a5cbafe84d 100644 --- a/products/breg/examples/formats/explain/model-explanation.json +++ b/products/breg/examples/formats/explain/model-explanation.json @@ -2602,7 +2602,7 @@ "protocol": "id.registrystack.org/protocols/review/v1" } ], - "revision": "sha256:97f59e130fd42843a91e60744a48f8c425a6df587fbdc804f05058c60a713b45", + "revision": "sha256:a6e151af7e19b3e1675d76c67cc5d7c6c3c52fb009f857ebe534e8a913c2e4e0", "statisticalDatasets": [], "version": "0.1.0" } diff --git a/products/breg/examples/required-attachment/README.md b/products/breg/examples/required-attachment/README.md new file mode 100644 index 0000000000..d572159410 --- /dev/null +++ b/products/breg/examples/required-attachment/README.md @@ -0,0 +1,25 @@ +# Submit a Proposal with a required file + +This project changes a target Record's name through a manual Proposal. Its +`support` slot requires one text file before Submit. The caller holds the +`clerk` profile and a direct `jurisdiction` claim matching the target. + +Start the Proposal with `target` and `value`, then follow its attachment upload +link with a `text/plain` body. Before upload, Submit is unavailable with +`attachment-required` and recovery `correct-input`. Calling Submit still +answers `422 attachment.required` with `fieldPath: /attachments/support`. +Upload the file, read the updated Proposal, and follow its available Submit +link. Apply uses the exact submitted version and effect digest. + +The committed `openapi.json` is generated from `registry.yaml`. Its Submit +responses include the required-file problem and verification outcomes. +The authoring check warns that `package.sourceRevision` is absent. Set it to +your source revision when preparing a production package. + +From the repository root: + +```sh +cargo run --locked -p registry-bregctl -- check products/breg/examples/required-attachment +cargo run --locked -p registry-breg --example example-artifacts -- \ + --output generated-required-attachment --project required-attachment +``` diff --git a/products/breg/examples/required-attachment/openapi.json b/products/breg/examples/required-attachment/openapi.json new file mode 100644 index 0000000000..1bc798e2a4 --- /dev/null +++ b/products/breg/examples/required-attachment/openapi.json @@ -0,0 +1 @@ +{"components":{"schemas":{"ImmediateActionPrecondition":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"},"ImmediateActionResultReference":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"Problem":{"additionalProperties":false,"allOf":[{"if":{"properties":{"code":{"enum":["attachment.required","attachment.verification-pending","attachment.verification-rejected"]}}},"then":{"allOf":[{"else":{"properties":{"status":{"const":422}}},"if":{"properties":{"code":{"const":"attachment.verification-pending"}}},"then":{"properties":{"status":{"const":409}}}}],"properties":{"fieldPath":{"pattern":"^/attachments/[a-z][a-z0-9_-]{0,63}$","type":"string"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId","fieldPath"]},"required":["fieldPath"]}},{"if":{"properties":{"code":{"const":"write.outside-boundary"}}},"then":{"properties":{"code":{"const":"write.outside-boundary"},"detail":{"const":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."},"status":{"const":403},"title":{"const":"Forbidden"},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId"]}}},{"if":{"properties":{"code":{"not":{"const":"action.guard_failed"}}}},"then":{"not":{"required":["guardReason"]}}},{"if":{"properties":{"code":{"const":"action.refused"}}},"then":{"properties":{"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"const":"statistical_dataset.release_refused"}}},"then":{"properties":{"refusalCode":{"enum":["period-not-ended","before-first-period","provisional-after-final","already-withdrawn","negative-value"]},"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"not":{"enum":["action.refused","statistical_dataset.release_refused"]}}}},"then":{"not":{"required":["refusalCode"]}}},{"if":{"properties":{"code":{"const":"statistical_dataset.version_withdrawn"}}},"then":{"properties":{"status":{"const":410}},"required":["reasonCode"]}},{"if":{"properties":{"code":{"not":{"const":"statistical_dataset.version_withdrawn"}}}},"then":{"not":{"required":["reasonCode"]}}},{"if":{"properties":{"code":{"const":"action.evidence_failed"}}},"then":{"properties":{"detail":{"const":"The declared Evidence dependency could not be accepted."},"fieldPath":{"pattern":"^/evidence/[a-z][a-z0-9_-]{0,63}$","type":"string"},"status":{"const":503}}}},{"if":{"properties":{"code":{"const":"action.handler_failed"}}},"then":{"properties":{"status":{"const":500}}}},{"if":{"anyOf":[{"required":["atField"]},{"required":["notAfterField"]}]},"then":{"properties":{"code":{"const":"request.invalid"},"status":{"const":400}},"required":["atField","notAfterField"]}},{"if":{"anyOf":[{"required":["recordType"]},{"required":["fieldId"]},{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"then":{"oneOf":[{"not":{"anyOf":[{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"required":["fieldId"]},{"not":{"required":["fieldId"]},"oneOf":[{"not":{"required":["field"]},"properties":{"constraintKind":{"const":"compare"}},"required":["left","right"]},{"not":{"anyOf":[{"required":["left"]},{"required":["right"]}]},"properties":{"constraintKind":{"enum":["int-range","vocabulary"]}},"required":["field"]}],"required":["constraintId","constraintKind"]}],"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409}},"required":["recordType"]}}],"properties":{"atField":{"maxLength":128,"minLength":1,"type":"string"},"code":{"enum":["action.evidence_failed","action.guard_failed","action.handler_failed","action.refused","attachment.content-type","attachment.digest-mismatch","attachment.limit-reached","attachment.required","attachment.slot-write-once","attachment.too-large","attachment.verification-pending","attachment.verification-rejected","authentication.refused","idempotency.expired","idempotency.key-reused","ingestion.chunk_mismatch","ingestion.profile_mismatch","ingestion.receipt_erased","ingestion.run_blocked","ingestion.run_not_open","lookup.unresolved","mutation.conflict","precondition.failed","precondition.required","proposal.rejected","proposal.review_result_mismatch","proposal.submission_expired","query.cursor_invalid","query.filter_required","query.invalid","request.access_reason_required","request.invalid","request.timeout","resource.not_found","runtime.field_encryption.unavailable","service.unavailable","source.unavailable","statistical_dataset.domain_violation","statistical_dataset.release_refused","statistical_dataset.version_conflict","statistical_dataset.version_withdrawn","unsupported.media_type","write.outside-boundary"],"type":"string"},"constraintId":{"maxLength":128,"minLength":1,"type":"string"},"constraintKind":{"enum":["compare","int-range","vocabulary"],"type":"string"},"detail":{"maxLength":256,"type":"string"},"field":{"maxLength":128,"minLength":1,"type":"string"},"fieldId":{"maxLength":128,"minLength":1,"type":"string"},"fieldPath":{"maxLength":256,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"left":{"maxLength":128,"minLength":1,"type":"string"},"notAfterField":{"maxLength":128,"minLength":1,"type":"string"},"reasonCode":{"enum":["computation-error","source-data-error","disclosure-risk"],"type":"string"},"recordType":{"maxLength":128,"minLength":1,"type":"string"},"refusalCode":{"maxLength":128,"minLength":1,"type":"string"},"requiredFilters":{"items":{"items":{"maxLength":64,"minLength":1,"type":"string"},"maxItems":32,"minItems":1,"type":"array","uniqueItems":true},"maxItems":8,"minItems":1,"type":"array"},"right":{"maxLength":128,"minLength":1,"type":"string"},"status":{"maximum":599,"minimum":400,"type":"integer"},"title":{"maxLength":128,"type":"string"},"traceId":{"maxLength":32,"minLength":32,"pattern":"^[0-9a-f]{32}$","type":"string"},"type":{"format":"uri","maxLength":256,"type":"string"}},"required":["type","title","status","detail","code","traceId"],"type":"object"},"ReviewCompletion":{"additionalProperties":false,"properties":{"completedAt":{"format":"date-time","type":"string"},"eventId":{"format":"uuid","type":"string"},"requestId":{"format":"uuid","type":"string"},"resultId":{"format":"uuid","type":"string"},"type":{"const":"review.completed"}},"required":["type","eventId","requestId","resultId","completedAt"],"type":"object"},"action-correct-name-invoke-input":{"$id":"urn:breg:action:correct-name:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"target":{"format":"uuid","type":"string"},"value":{"maxLength":64,"minLength":0,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-name","x-registry-requiredConditionKeys":[]},"action-correct-name-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"target":{"$id":"urn:breg:record-type:target","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":64,"minLength":0,"type":"string"},"name":{"maxLength":64,"minLength":0,"type":"string"}},"required":["name","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable","x-registry-mutationPolicy":{"patch":"proposal-required"}},"target-create-input":{"$id":"urn:breg:record-type:target:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":64,"minLength":0,"type":"string"},"name":{"maxLength":64,"minLength":0,"type":"string"}},"required":["name","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"}},"securitySchemes":{"bearerAuth":{"bearerFormat":"JWT","scheme":"bearer","type":"http"},"reviewCompletion":{"description":"The review authority's configured completion key verifies the Standard Webhooks signature.","in":"header","name":"webhook-signature","type":"apiKey"}}},"info":{"title":"required-attachment","version":"1"},"openapi":"3.1.0","paths":{"/v1/actions/correct-name/proposals":{"post":{"operationId":"actions.correct-name.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-name-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-name-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["clerk"],"x-registry-action":{"access":{"accessProfiles":["clerk"]},"apiName":"correctName","attachments":[{"contentTypes":["text/plain"],"id":"support","maximumBytes":4096,"required":true}],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{},"execution":{"application":"manual","mode":"proposal","review":"none"},"id":"correct-name","inputMode":"fixed","inputs":[{"apiName":"target","classification":"internal","fieldType":{"onDelete":"restrict","target":"target","type":"reference"},"id":"target","label":"target","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"value","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":0,"type":"string"},"id":"value","label":"value","nullable":false,"required":true,"schema":{"maxLength":64,"minLength":0,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"target","input":"target","targetRecordType":"target"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"name","operation":"patch","recordType":"target"}],"revision":"sha256:bc33d44acbc56e239cd2c88aa76698302a40bba0bf7298b80317a82c9fc4cb36","route":"/v1/actions/correct-name/proposals","routes":{"availability":null,"start":{"inputSchema":"action-correct-name-invoke-input","method":"POST","operationId":"actions.correct-name.start","path":"/v1/actions/correct-name/proposals","requiresIdempotencyKey":true,"responseSchema":"action-correct-name-invoke-response"}}},"x-registry-defaultAccessProfile":"clerk","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/proposals":{"get":{"operationId":"proposals.list","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["clerk"],"type":"string"}},{"in":"query","name":"action","schema":{"type":"string"}},{"in":"query","name":"owner","schema":{"const":"caller"}},{"in":"query","name":"target","schema":{"format":"uuid","type":"string"}},{"in":"query","name":"state","schema":{"enum":["draft","submitted","applied","cancelled","rejected"]}},{"in":"query","name":"turn","schema":{"enum":["party","official","nobody"]}},{"in":"query","name":"cursor","schema":{"type":"string"}},{"description":"The most items a page holds. A page may hold fewer than `limit` items, so keep paging while `nextCursor` is present.","in":"query","name":"limit","schema":{"default":50,"maximum":100,"minimum":1,"type":"integer"}},{"in":"query","name":"pendingManualApplication","schema":{"default":false,"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"maxItems":100,"type":"array"},"nextCursor":{"type":"string"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["query.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["clerk"]}},"/v1/proposals/{proposal_id}":{"get":{"operationId":"proposals.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["clerk"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["clerk"]}},"/v1/proposals/{proposal_id}/apply":{"post":{"operationId":"proposals.apply","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["clerk"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"reason":{"description":"Optional application explanation, preserved unchanged. At most 4096 Unicode characters; NUL is refused.","maxLength":4096,"pattern":"^[^\\u0000]*$","type":"string"},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["submissionVersion","effectDigest"],"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["clerk"]}},"/v1/proposals/{proposal_id}/attachments/support":{"delete":{"operationId":"proposals.attachments.support.delete","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["clerk"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["clerk"]},"get":{"operationId":"proposals.attachments.support.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["clerk"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"query","name":"submissionVersion","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"reviewContextField","required":false,"schema":{"pattern":"^[a-z][a-zA-Z0-9]{0,63}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"effectDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"contextSchemaDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}}],"responses":{"200":{"content":{"*/*":{"schema":{"contentMediaType":"application/octet-stream","maxLength":16777216,"type":"string"}}},"description":"Authorized Proposal operation"},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["clerk"]},"patch":{"operationId":"proposals.attachments.support.patch","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["clerk"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"text/plain":{"schema":{"format":"binary","maxLength":4096,"type":"string"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"413":{"content":{"application/problem+json":{"examples":{"attachment.too-large":{"value":{"code":"attachment.too-large","detail":"The file is larger than the attachment slot accepts.","status":413,"title":"Content Too Large","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/too-large"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["attachment.too-large"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"attachment.content-type":{"value":{"code":"attachment.content-type","detail":"The file media type is not one the attachment slot accepts.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/content-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["attachment.content-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["clerk"]}},"/v1/proposals/{proposal_id}/cancel":{"post":{"operationId":"proposals.cancel","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["clerk"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["clerk"]}},"/v1/proposals/{proposal_id}/edit":{"post":{"operationId":"proposals.edit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["clerk"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-name:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"target":{"format":"uuid","type":"string"},"value":{"maxLength":64,"minLength":0,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-name","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["clerk"]}},"/v1/proposals/{proposal_id}/rebase":{"post":{"operationId":"proposals.rebase","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["clerk"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-name:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"target":{"format":"uuid","type":"string"},"value":{"maxLength":64,"minLength":0,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-name","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["clerk"]}},"/v1/proposals/{proposal_id}/revise":{"post":{"operationId":"proposals.revise","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["clerk"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-name:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"target":{"format":"uuid","type":"string"},"value":{"maxLength":64,"minLength":0,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-name","x-registry-requiredConditionKeys":[]},{"additionalProperties":false,"type":"object"}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["clerk"]}},"/v1/proposals/{proposal_id}/submissions/{submission_version}":{"get":{"operationId":"proposals.get-submission","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["clerk"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"path","name":"submission_version","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"application":{"anyOf":[{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"state":{"const":"applied"}},"required":["state","applicationId"],"type":"object"},{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},{"type":"null"}]},"current":{"type":"boolean"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"review":{"anyOf":[{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},{"type":"null"}]},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["id","actionId","submissionVersion","current","effectDigest","review","application"],"type":"object"}}},"description":"Authorized Proposal operation"},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"proposal.submission_expired":{"value":{"code":"proposal.submission_expired","detail":"The review result and application receipt of the submission are no longer retained.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/submission_expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["proposal.submission_expired"]}},"type":"object"}]}}},"description":"The submission's review result and application receipt are no longer retained","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["clerk"]}},"/v1/proposals/{proposal_id}/submit":{"post":{"operationId":"proposals.submit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["clerk"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"attachment.verification-pending":{"value":{"code":"attachment.verification-pending","detail":"The attachment is awaiting verification. Refresh the Proposal before submitting.","fieldPath":"/attachments/support","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/verification-pending"}},"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["attachment.verification-pending","idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"422":{"content":{"application/problem+json":{"examples":{"attachment.required":{"value":{"code":"attachment.required","detail":"The required attachment slot is empty.","fieldPath":"/attachments/support","status":422,"title":"Unprocessable Entity","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["attachment.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["clerk"]}},"/v1/records/targets":{"get":{"operationId":"records.target.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":64,"minLength":0,"type":"string"},"name":{"maxLength":64,"minLength":0,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"target"},"registryIdentifier":{"const":"required-attachment"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":64,"minLength":0,"type":"string"},"name":{"maxLength":64,"minLength":0,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"target"},"registryIdentifier":{"const":"required-attachment"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["clerk"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"clerk":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"clerk","selectableProperties":["jurisdiction","name"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"target","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"target","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.target.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/target-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/target"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"target"},"registryIdentifier":{"const":"required-attachment"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/target"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"target"},"registryIdentifier":{"const":"required-attachment"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["clerk"],"x-registry-operation":"create","x-registry-recordType":"target","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"target","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/targets/{record_id}":{"get":{"operationId":"records.target.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":64,"minLength":0,"type":"string"},"name":{"maxLength":64,"minLength":0,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"target"},"registryIdentifier":{"const":"required-attachment"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":64,"minLength":0,"type":"string"},"name":{"maxLength":64,"minLength":0,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"target"},"registryIdentifier":{"const":"required-attachment"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["clerk"],"x-registry-operation":"get","x-registry-recordType":"target","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"target","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/review-completions":{"post":{"description":"Available when a review authority configures a completion block.","operationId":"receiveReviewCompletion","parameters":[{"in":"header","name":"Registry-Recipient-Binding","required":true,"schema":{"maxLength":256,"minLength":1,"type":"string"}},{"description":"Must equal eventId.","in":"header","name":"webhook-id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"webhook-timestamp","required":true,"schema":{"pattern":"^(0|[1-9][0-9]{0,19})$","type":"string"}},{"in":"header","name":"webhook-signature","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewCompletion"}}},"required":true},"responses":{"204":{"description":"Completion accepted or already recorded."},"400":{"description":"The completion is invalid or eventId differs from webhook-id."},"401":{"description":"The completion authority could not be authenticated.","headers":{"WWW-Authenticate":{"schema":{"const":"Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"","type":"string"}}}},"413":{"description":"The completion body exceeds 2048 bytes. The response body is empty."},"415":{"description":"The request is not application/json."},"503":{"description":"The completion could not be durably recorded."}},"security":[{"reviewCompletion":[]}],"summary":"Receive a Casework review completion"}}}} \ No newline at end of file diff --git a/products/breg/examples/required-attachment/registry.yaml b/products/breg/examples/required-attachment/registry.yaml new file mode 100644 index 0000000000..6b2f9afb33 --- /dev/null +++ b/products/breg/examples/required-attachment/registry.yaml @@ -0,0 +1,66 @@ +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: + id: required-attachment + version: '1' + defaultLanguage: en + canonicalBaseIri: https://documents.example.test +datasets: + directory: {} +recordTypes: + target: + primaryDataset: directory + route: targets + mutationMode: mutable + mutationPolicy: {patch: proposal-required} + fields: + - {id: name, type: string, required: true, maximumLength: 64, classification: internal} + - {id: jurisdiction, type: string, required: true, maximumLength: 64, classification: internal} +actions: + correct-name: + execution: + mode: proposal + proposal: + review: {type: none} + application: {mode: manual} + retention: {mode: operator-erase} + attachments: + - {id: support, required: true, maximumBytes: 4096, contentTypes: [text/plain], classification: restricted} + inputs: + - {id: target, type: reference, target: target, required: true, classification: internal} + - {id: value, type: string, required: true, maximumLength: 64, classification: internal} + commitGuards: + targets: + - {input: target, revision: unchanged} + plan: + type: fixed + effects: + - id: name + target: {fromInput: target} + operation: patch + set: {name: {fromInput: value}} +accessProfiles: + clerk: + default: true + principalClaim: sub + requiredScopes: [proposal:manage] + requiredPurposes: [registry-administration] + permissions: + records: + - recordType: target + operations: [create, get, list] + readableFields: [name, jurisdiction] + writableFields: [name, jurisdiction] + rowBoundaries: [{field: jurisdiction, claim: jurisdiction, operator: equals}] + actions: + - action: correct-name + operations: [start] + targets: [{recordType: target, rowBoundaries: [{field: jurisdiction, claim: jurisdiction, operator: equals}]}] + proposals: + - action: correct-name + operations: [get, list, edit, submit, revise, rebase, cancel, apply] + ownership: caller + readableInputs: [target, value] + readableAttachments: [support] + writableAttachments: [support] + targets: [{recordType: target, rowBoundaries: [{field: jurisdiction, claim: jurisdiction, operator: equals}]}] diff --git a/products/breg/generated/authoring/registry-module.schema.json b/products/breg/generated/authoring/registry-module.schema.json index 7979faa60d..cbec1161fb 100644 --- a/products/breg/generated/authoring/registry-module.schema.json +++ b/products/breg/generated/authoring/registry-module.schema.json @@ -804,6 +804,44 @@ ], "type": "string" }, + "AdditionSlotSource": { + "additionalProperties": false, + "description": "Supporting files added to the current submission while its review is open.", + "properties": { + "classification": { + "$ref": "#/$defs/Classification" + }, + "contentTypes": { + "items": { + "type": "string" + }, + "type": "array" + }, + "id": { + "$ref": "#/$defs/LocalId" + }, + "maximumBytes": { + "format": "uint32", + "maximum": 16777216, + "minimum": 1, + "type": "integer" + }, + "maximumCount": { + "format": "uint32", + "maximum": 32, + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "id", + "maximumBytes", + "maximumCount", + "contentTypes", + "classification" + ], + "type": "object" + }, "AttachmentSlotSource": { "additionalProperties": false, "properties": { @@ -3067,6 +3105,23 @@ }, "ProposalContextValueSource": { "oneOf": [ + { + "additionalProperties": false, + "properties": { + "slot": { + "$ref": "#/$defs/LocalId" + }, + "type": { + "const": "additions", + "type": "string" + } + }, + "required": [ + "type", + "slot" + ], + "type": "object" + }, { "additionalProperties": false, "properties": { @@ -3150,6 +3205,9 @@ }, "ProposalEventTransition": { "enum": [ + "asked", + "answered", + "added", "started", "edited", "submitted", @@ -3194,6 +3252,9 @@ "ProposalPolicySource": { "additionalProperties": false, "properties": { + "additions": { + "$ref": "#/$defs/AdditionSlotSource" + }, "application": { "$ref": "#/$defs/ProposalApplicationSource", "default": { diff --git a/products/breg/generated/authoring/registry-project.schema.json b/products/breg/generated/authoring/registry-project.schema.json index a493bb66a2..d57077b68e 100644 --- a/products/breg/generated/authoring/registry-project.schema.json +++ b/products/breg/generated/authoring/registry-project.schema.json @@ -857,6 +857,44 @@ ], "type": "string" }, + "AdditionSlotSource": { + "additionalProperties": false, + "description": "Supporting files added to the current submission while its review is open.", + "properties": { + "classification": { + "$ref": "#/$defs/Classification" + }, + "contentTypes": { + "items": { + "type": "string" + }, + "type": "array" + }, + "id": { + "$ref": "#/$defs/LocalId" + }, + "maximumBytes": { + "format": "uint32", + "maximum": 16777216, + "minimum": 1, + "type": "integer" + }, + "maximumCount": { + "format": "uint32", + "maximum": 32, + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "id", + "maximumBytes", + "maximumCount", + "contentTypes", + "classification" + ], + "type": "object" + }, "AttachmentSlotSource": { "additionalProperties": false, "properties": { @@ -4018,6 +4056,23 @@ }, "ProposalContextValueSource": { "oneOf": [ + { + "additionalProperties": false, + "properties": { + "slot": { + "$ref": "#/$defs/LocalId" + }, + "type": { + "const": "additions", + "type": "string" + } + }, + "required": [ + "type", + "slot" + ], + "type": "object" + }, { "additionalProperties": false, "properties": { @@ -4101,6 +4156,9 @@ }, "ProposalEventTransition": { "enum": [ + "asked", + "answered", + "added", "started", "edited", "submitted", @@ -4144,9 +4202,11 @@ }, "ProposalOperation": { "enum": [ + "answer", "get", "list", "edit", + "add", "submit", "revise", "cancel", @@ -4245,6 +4305,9 @@ "ProposalPolicySource": { "additionalProperties": false, "properties": { + "additions": { + "$ref": "#/$defs/AdditionSlotSource" + }, "application": { "$ref": "#/$defs/ProposalApplicationSource", "default": { diff --git a/products/breg/generated/event-schemas/proposal-lifecycle.schema.json b/products/breg/generated/event-schemas/proposal-lifecycle.schema.json index eaa915041f..625fc00c6d 100644 --- a/products/breg/generated/event-schemas/proposal-lifecycle.schema.json +++ b/products/breg/generated/event-schemas/proposal-lifecycle.schema.json @@ -1 +1 @@ -{"$id":"https://id.registrystack.org/contracts/breg/proposal-event/v1","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"actionId":{"maxLength":64,"minLength":1,"type":"string"},"actionRevision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"authorityKind":{"enum":["caller","system","review"]},"effectDigest":{"anyOf":[{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},{"type":"null"}]},"fromState":{"anyOf":[{"enum":["draft","submitted","applied","cancelled","rejected"],"type":"string"},{"const":"none"}]},"proposalId":{"format":"uuid","type":"string"},"revision":{"maximum":9007199254740991,"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"],"type":"string"},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"},"systemApplyGrantRevision":{"anyOf":[{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},{"type":"null"}]},"transition":{"enum":["started","edited","submitted","revised","rebased","retried","cancelled","applied","rejected","review-returned"],"type":"string"},"turn":{"enum":["party","official","nobody"],"type":"string"}},"required":["actionId","actionRevision","proposalId","submissionVersion","revision","fromState","state","transition","effectDigest","authorityKind","systemApplyGrantRevision","turn"],"type":"object"} \ No newline at end of file +{"$id":"https://id.registrystack.org/contracts/breg/proposal-event/v1","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"actionId":{"maxLength":64,"minLength":1,"type":"string"},"actionRevision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"authorityKind":{"enum":["caller","system","review"]},"effectDigest":{"anyOf":[{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},{"type":"null"}]},"fromState":{"anyOf":[{"enum":["draft","submitted","applied","cancelled","rejected"],"type":"string"},{"const":"none"}]},"proposalId":{"format":"uuid","type":"string"},"revision":{"maximum":9007199254740991,"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"],"type":"string"},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"},"systemApplyGrantRevision":{"anyOf":[{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},{"type":"null"}]},"transition":{"enum":["started","edited","submitted","revised","rebased","retried","cancelled","applied","rejected","review-returned","added","asked","answered"],"type":"string"},"turn":{"enum":["party","official","nobody"],"type":"string"}},"required":["actionId","actionRevision","proposalId","submissionVersion","revision","fromState","state","transition","effectDigest","authorityKind","systemApplyGrantRevision","turn"],"type":"object"} \ No newline at end of file diff --git a/products/breg/generated/facility/generated/action-contracts.json b/products/breg/generated/facility/generated/action-contracts.json index 329887e122..c620b424d1 100644 --- a/products/breg/generated/facility/generated/action-contracts.json +++ b/products/breg/generated/facility/generated/action-contracts.json @@ -1 +1 @@ -{"actions":[{"application":{"maximumAttempts":3,"mode":"automatic"},"display":{"description":"Submit a frozen address correction for independent review and later application.","label":"Correct facility address"},"id":"correct-address","input":{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},"mode":"proposal","output":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"review":{"authority":"casework","policy":{"id":"facility-address-review"},"source":"facility-registry","type":"required"},"revision":"sha256:efb20d40704ae6c133b660f2fe3d556b4a00ee5478a5871cf1fd026e7d7b6b7a"},{"application":{"mode":"manual"},"display":{"description":"Submit a durable deactivation that requires no external review.","label":"Deactivate facility"},"id":"deactivate-facility","input":{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},"mode":"proposal","output":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"review":{"type":"none"},"revision":"sha256:9237300ee419a0014c3b123cc7ac90eb9623cb4c45bba4a65c03936083299f1d"},{"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"id":"register-facility","input":{"$id":"urn:breg:action:register-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-facility","x-registry-requiredConditionKeys":[]},"mode":"immediate","output":{"$id":"urn:breg:action:register-facility:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"register-facility"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"assignment":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility-assignment"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"facility":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["assignment","facility"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6"}],"apiVersion":"id.registrystack.org/formats/breg/action-contracts/v1","kind":"BRegActionContracts"} \ No newline at end of file +{"actions":[{"application":{"maximumAttempts":3,"mode":"automatic"},"display":{"description":"Submit a frozen address correction for independent review and later application.","label":"Correct facility address"},"id":"correct-address","input":{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},"mode":"proposal","output":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"review":{"authority":"casework","policy":{"id":"facility-address-review"},"source":"facility-registry","type":"required"},"revision":"sha256:efb20d40704ae6c133b660f2fe3d556b4a00ee5478a5871cf1fd026e7d7b6b7a"},{"application":{"mode":"manual"},"display":{"description":"Submit a durable deactivation that requires no external review.","label":"Deactivate facility"},"id":"deactivate-facility","input":{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},"mode":"proposal","output":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"review":{"type":"none"},"revision":"sha256:9237300ee419a0014c3b123cc7ac90eb9623cb4c45bba4a65c03936083299f1d"},{"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"id":"register-facility","input":{"$id":"urn:breg:action:register-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-facility","x-registry-requiredConditionKeys":[]},"mode":"immediate","output":{"$id":"urn:breg:action:register-facility:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"register-facility"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"assignment":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility-assignment"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"facility":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["assignment","facility"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6"}],"apiVersion":"id.registrystack.org/formats/breg/action-contracts/v1","kind":"BRegActionContracts"} \ No newline at end of file diff --git a/products/breg/generated/facility/generated/action-schemas/correct-address.invoke.response.schema.json b/products/breg/generated/facility/generated/action-schemas/correct-address.invoke.response.schema.json index 5599f4c48a..fbfdbff5d7 100644 --- a/products/breg/generated/facility/generated/action-schemas/correct-address.invoke.response.schema.json +++ b/products/breg/generated/facility/generated/action-schemas/correct-address.invoke.response.schema.json @@ -1 +1 @@ -{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"} \ No newline at end of file +{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"} \ No newline at end of file diff --git a/products/breg/generated/facility/generated/action-schemas/deactivate-facility.invoke.response.schema.json b/products/breg/generated/facility/generated/action-schemas/deactivate-facility.invoke.response.schema.json index 5599f4c48a..fbfdbff5d7 100644 --- a/products/breg/generated/facility/generated/action-schemas/deactivate-facility.invoke.response.schema.json +++ b/products/breg/generated/facility/generated/action-schemas/deactivate-facility.invoke.response.schema.json @@ -1 +1 @@ -{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"} \ No newline at end of file +{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"} \ No newline at end of file diff --git a/products/breg/generated/facility/generated/openapi.json b/products/breg/generated/facility/generated/openapi.json index 950af69b36..964c49db68 100644 --- a/products/breg/generated/facility/generated/openapi.json +++ b/products/breg/generated/facility/generated/openapi.json @@ -1 +1 @@ -{"components":{"schemas":{"ImmediateActionPrecondition":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"},"ImmediateActionResultReference":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"Problem":{"additionalProperties":false,"allOf":[{"if":{"properties":{"code":{"const":"write.outside-boundary"}}},"then":{"properties":{"code":{"const":"write.outside-boundary"},"detail":{"const":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."},"status":{"const":403},"title":{"const":"Forbidden"},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId"]}}},{"if":{"properties":{"code":{"not":{"const":"action.guard_failed"}}}},"then":{"not":{"required":["guardReason"]}}},{"if":{"properties":{"code":{"const":"action.refused"}}},"then":{"properties":{"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"const":"statistical_dataset.release_refused"}}},"then":{"properties":{"refusalCode":{"enum":["period-not-ended","before-first-period","provisional-after-final","already-withdrawn","negative-value"]},"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"not":{"enum":["action.refused","statistical_dataset.release_refused"]}}}},"then":{"not":{"required":["refusalCode"]}}},{"if":{"properties":{"code":{"const":"statistical_dataset.version_withdrawn"}}},"then":{"properties":{"status":{"const":410}},"required":["reasonCode"]}},{"if":{"properties":{"code":{"not":{"const":"statistical_dataset.version_withdrawn"}}}},"then":{"not":{"required":["reasonCode"]}}},{"if":{"properties":{"code":{"const":"action.evidence_failed"}}},"then":{"properties":{"detail":{"const":"The declared Evidence dependency could not be accepted."},"fieldPath":{"pattern":"^/evidence/[a-z][a-z0-9_-]{0,63}$","type":"string"},"status":{"const":503}}}},{"if":{"properties":{"code":{"const":"action.handler_failed"}}},"then":{"properties":{"status":{"const":500}}}},{"if":{"anyOf":[{"required":["atField"]},{"required":["notAfterField"]}]},"then":{"properties":{"code":{"const":"request.invalid"},"status":{"const":400}},"required":["atField","notAfterField"]}},{"if":{"anyOf":[{"required":["recordType"]},{"required":["fieldId"]},{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"then":{"oneOf":[{"not":{"anyOf":[{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"required":["fieldId"]},{"not":{"required":["fieldId"]},"oneOf":[{"not":{"required":["field"]},"properties":{"constraintKind":{"const":"compare"}},"required":["left","right"]},{"not":{"anyOf":[{"required":["left"]},{"required":["right"]}]},"properties":{"constraintKind":{"enum":["int-range","vocabulary"]}},"required":["field"]}],"required":["constraintId","constraintKind"]}],"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409}},"required":["recordType"]}}],"properties":{"atField":{"maxLength":128,"minLength":1,"type":"string"},"code":{"enum":["action.evidence_failed","action.guard_failed","action.handler_failed","action.refused","attachment.content-type","attachment.digest-mismatch","attachment.slot-write-once","attachment.too-large","authentication.refused","idempotency.expired","idempotency.key-reused","ingestion.chunk_mismatch","ingestion.profile_mismatch","ingestion.receipt_erased","ingestion.run_blocked","ingestion.run_not_open","lookup.unresolved","mutation.conflict","precondition.failed","precondition.required","proposal.rejected","proposal.review_result_mismatch","proposal.submission_expired","query.cursor_invalid","query.filter_required","query.invalid","request.access_reason_required","request.invalid","request.timeout","resource.not_found","runtime.field_encryption.unavailable","service.unavailable","source.unavailable","statistical_dataset.domain_violation","statistical_dataset.release_refused","statistical_dataset.version_conflict","statistical_dataset.version_withdrawn","unsupported.media_type","write.outside-boundary"],"type":"string"},"constraintId":{"maxLength":128,"minLength":1,"type":"string"},"constraintKind":{"enum":["compare","int-range","vocabulary"],"type":"string"},"detail":{"maxLength":256,"type":"string"},"field":{"maxLength":128,"minLength":1,"type":"string"},"fieldId":{"maxLength":128,"minLength":1,"type":"string"},"fieldPath":{"maxLength":256,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"left":{"maxLength":128,"minLength":1,"type":"string"},"notAfterField":{"maxLength":128,"minLength":1,"type":"string"},"reasonCode":{"enum":["computation-error","source-data-error","disclosure-risk"],"type":"string"},"recordType":{"maxLength":128,"minLength":1,"type":"string"},"refusalCode":{"maxLength":128,"minLength":1,"type":"string"},"requiredFilters":{"items":{"items":{"maxLength":64,"minLength":1,"type":"string"},"maxItems":32,"minItems":1,"type":"array","uniqueItems":true},"maxItems":8,"minItems":1,"type":"array"},"right":{"maxLength":128,"minLength":1,"type":"string"},"status":{"maximum":599,"minimum":400,"type":"integer"},"title":{"maxLength":128,"type":"string"},"traceId":{"maxLength":32,"minLength":32,"pattern":"^[0-9a-f]{32}$","type":"string"},"type":{"format":"uri","maxLength":256,"type":"string"}},"required":["type","title","status","detail","code","traceId"],"type":"object"},"ReviewCompletion":{"additionalProperties":false,"properties":{"completedAt":{"format":"date-time","type":"string"},"eventId":{"format":"uuid","type":"string"},"requestId":{"format":"uuid","type":"string"},"resultId":{"format":"uuid","type":"string"},"type":{"const":"review.completed"}},"required":["type","eventId","requestId","resultId","completedAt"],"type":"object"},"action-correct-address-invoke-input":{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},"action-correct-address-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-deactivate-facility-invoke-input":{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},"action-deactivate-facility-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-register-facility-availability-input":{"$id":"urn:breg:action:register-facility:availability-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"oneOf":[{"properties":{"input":{"properties":{"operatorId":{"format":"uuid","type":"string"}},"required":["operatorId"]},"targetInput":{"const":"operatorId"}}}],"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"},"targetInput":{"enum":["operatorId"],"type":"string"}},"required":["targetInput","input"],"type":"object","x-registry-action":"register-facility"},"action-register-facility-availability-response":{"$id":"urn:breg:action:register-facility:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardLabel":{"maxLength":256,"minLength":1,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"register-facility"},"action-register-facility-invoke-input":{"$id":"urn:breg:action:register-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-facility","x-registry-requiredConditionKeys":[]},"action-register-facility-invoke-response":{"$id":"urn:breg:action:register-facility:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"register-facility"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"assignment":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility-assignment"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"facility":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["assignment","facility"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"directory-entry":{"$id":"urn:breg:record-type:directory-entry","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"directory-entry-create-input":{"$id":"urn:breg:record-type:directory-entry:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"facility":{"$id":"urn:breg:record-type:facility","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"required":["facilityCode","name","addressLine","city","postalCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable","x-registry-mutationPolicy":{"patch":"proposal-required"}},"facility-assignment":{"$id":"urn:breg:record-type:facility-assignment","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"required":["facility","operator","jurisdiction"],"type":"object","x-registry-mutationMode":"create-only"},"operator":{"$id":"urn:breg:record-type:operator","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"required":["operatorCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"operator-create-input":{"$id":"urn:breg:record-type:operator:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"required":["operatorCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"}},"securitySchemes":{"bearerAuth":{"bearerFormat":"JWT","scheme":"bearer","type":"http"},"reviewCompletion":{"description":"The review authority's configured completion key verifies the Standard Webhooks signature.","in":"header","name":"webhook-signature","type":"apiKey"}}},"info":{"title":"facility-registry","version":"0.1.0"},"openapi":"3.1.0","paths":{"/v1/actions/correct-address/proposals":{"post":{"operationId":"actions.correct-address.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-address-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-address-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-correction-author"],"x-registry-action":{"access":{"accessProfiles":["facility-correction-author"]},"apiName":"correctAddress","attachments":[{"contentTypes":["application/pdf"],"id":"supporting-document","maximumBytes":1048576,"required":false}],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Submit a frozen address correction for independent review and later application.","label":"Correct facility address"},"execution":{"application":"automatic","mode":"proposal","review":"required"},"id":"correct-address","inputMode":"handler","inputs":[{"apiName":"facilityId","classification":"internal","fieldType":{"onDelete":"restrict","target":"facility","type":"reference"},"id":"facility","label":"facilityId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}}],"maximumInputStringBytes":16384,"referenceInputs":[{"apiName":"facilityId","input":"facility","targetRecordType":"facility"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility-address","operation":"patch","recordType":"facility"}],"revision":"sha256:efb20d40704ae6c133b660f2fe3d556b4a00ee5478a5871cf1fd026e7d7b6b7a","route":"/v1/actions/correct-address/proposals","routes":{"availability":null,"start":{"inputSchema":"action-correct-address-invoke-input","method":"POST","operationId":"actions.correct-address.start","path":"/v1/actions/correct-address/proposals","requiresIdempotencyKey":true,"responseSchema":"action-correct-address-invoke-response"}}},"x-registry-defaultAccessProfile":"facility-correction-author","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/deactivate-facility/proposals":{"post":{"operationId":"actions.deactivate-facility.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-deactivate-facility-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-deactivate-facility-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-correction-author"],"x-registry-action":{"access":{"accessProfiles":["facility-correction-author"]},"apiName":"deactivateFacility","attachments":[],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Submit a durable deactivation that requires no external review.","label":"Deactivate facility"},"execution":{"application":"manual","mode":"proposal","review":"none"},"id":"deactivate-facility","inputMode":"fixed","inputs":[{"apiName":"facilityId","classification":"internal","fieldType":{"onDelete":"restrict","target":"facility","type":"reference"},"id":"facility","label":"facilityId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"facilityId","input":"facility","targetRecordType":"facility"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility-status","operation":"patch","recordType":"facility"}],"revision":"sha256:9237300ee419a0014c3b123cc7ac90eb9623cb4c45bba4a65c03936083299f1d","route":"/v1/actions/deactivate-facility/proposals","routes":{"availability":null,"start":{"inputSchema":"action-deactivate-facility-invoke-input","method":"POST","operationId":"actions.deactivate-facility.start","path":"/v1/actions/deactivate-facility/proposals","requiresIdempotencyKey":true,"responseSchema":"action-deactivate-facility-invoke-response"}}},"x-registry-defaultAccessProfile":"facility-correction-author","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/register-facility":{"post":{"operationId":"actions.register-facility.invoke","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-invoke-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-invoke-response"}}},"description":"Immediate action committed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard_failed":{"value":{"code":"action.guard_failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard_failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-registrar"],"x-registry-action":{"access":{"accessProfiles":["facility-registrar"]},"apiName":"registerFacility","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":null,"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"execution":{"mode":"immediate"},"id":"register-facility","inputMode":"fixed","inputs":[{"apiName":"facilityCode","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":1,"type":"string"},"id":"facility-code","label":"facilityCode","nullable":false,"required":true,"schema":{"maxLength":64,"minLength":1,"type":"string"}},{"apiName":"name","classification":"internal","fieldType":{"maximumLength":200,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":200,"minLength":1,"type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}},{"apiName":"operatorId","classification":"internal","fieldType":{"onDelete":"restrict","target":"operator","type":"reference"},"id":"operator","label":"operatorId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"operatorId","input":"operator","targetRecordType":"operator"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility","operation":"create","recordType":"facility"},{"effect":"assignment","operation":"create","recordType":"facility-assignment"}],"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6","route":"/v1/actions/register-facility","routes":{"availability":{"inputSchema":"action-register-facility-availability-input","method":"POST","operationId":"actions.register-facility.availability","path":"/v1/actions/register-facility/availability","requiresIdempotencyKey":false,"responseSchema":"action-register-facility-availability-response"},"invoke":{"inputSchema":"action-register-facility-invoke-input","method":"POST","operationId":"actions.register-facility.invoke","path":"/v1/actions/register-facility","requiresIdempotencyKey":true,"responseSchema":"action-register-facility-invoke-response"},"targetConditions":null}},"x-registry-defaultAccessProfile":"facility-registrar","x-registry-operation":"invoke","x-registry-routeKind":"invoke"}},"/v1/actions/register-facility/availability":{"post":{"operationId":"actions.register-facility.availability","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-availability-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-availability-response"}}},"description":"Action availability returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-registrar"],"x-registry-action":{"access":{"accessProfiles":["facility-registrar"]},"apiName":"registerFacility","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":null,"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"execution":{"mode":"immediate"},"id":"register-facility","inputMode":"fixed","inputs":[{"apiName":"facilityCode","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":1,"type":"string"},"id":"facility-code","label":"facilityCode","nullable":false,"required":true,"schema":{"maxLength":64,"minLength":1,"type":"string"}},{"apiName":"name","classification":"internal","fieldType":{"maximumLength":200,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":200,"minLength":1,"type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}},{"apiName":"operatorId","classification":"internal","fieldType":{"onDelete":"restrict","target":"operator","type":"reference"},"id":"operator","label":"operatorId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"operatorId","input":"operator","targetRecordType":"operator"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility","operation":"create","recordType":"facility"},{"effect":"assignment","operation":"create","recordType":"facility-assignment"}],"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6","route":"/v1/actions/register-facility","routes":{"availability":{"inputSchema":"action-register-facility-availability-input","method":"POST","operationId":"actions.register-facility.availability","path":"/v1/actions/register-facility/availability","requiresIdempotencyKey":false,"responseSchema":"action-register-facility-availability-response"},"invoke":{"inputSchema":"action-register-facility-invoke-input","method":"POST","operationId":"actions.register-facility.invoke","path":"/v1/actions/register-facility","requiresIdempotencyKey":true,"responseSchema":"action-register-facility-invoke-response"},"targetConditions":null}},"x-registry-defaultAccessProfile":"facility-registrar","x-registry-operation":"invoke","x-registry-routeKind":"availability"}},"/v1/proposals":{"get":{"operationId":"proposals.list","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"type":"string"}},{"in":"query","name":"action","schema":{"type":"string"}},{"in":"query","name":"owner","schema":{"const":"caller"}},{"in":"query","name":"target","schema":{"format":"uuid","type":"string"}},{"in":"query","name":"state","schema":{"enum":["draft","submitted","applied","cancelled","rejected"]}},{"in":"query","name":"turn","schema":{"enum":["party","official","nobody"]}},{"in":"query","name":"cursor","schema":{"type":"string"}},{"description":"The most items a page holds. A page may hold fewer than `limit` items, so keep paging while `nextCursor` is present.","in":"query","name":"limit","schema":{"default":50,"maximum":100,"minimum":1,"type":"integer"}},{"in":"query","name":"pendingManualApplication","schema":{"default":false,"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"maxItems":100,"type":"array"},"nextCursor":{"type":"string"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/review-context":{"get":{"description":"One bounded transport exchange under each item's current get-review-context authority. Ordered visible or concealed results; operational failures refuse the whole batch. Maximum response is 8 MiB.","operationId":"proposals.get-review-context-batch","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["proposal-reviewer"],"type":"string"}},{"description":"One to 100 distinct canonical Proposal UUIDs, in response order.","explode":false,"in":"query","name":"ids","required":true,"schema":{"items":{"format":"uuid","type":"string"},"maxItems":100,"minItems":1,"type":"array","uniqueItems":true},"style":"form"}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"context":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"fields":{"type":"object"},"reference":{"type":"string"}},"required":["reference","contract","fields"],"type":"object"},"effectDigest":{"type":"string"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"},"id":{"format":"uuid","type":"string"},"status":{"const":"visible"}},"required":["id","status","context"],"type":"object"},{"additionalProperties":false,"properties":{"id":{"format":"uuid","type":"string"},"status":{"const":"concealed"}},"required":["id","status"],"type":"object"}]},"maxItems":100,"minItems":1,"type":"array"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["proposal-reviewer"]}},"/v1/proposals/{proposal_id}":{"get":{"operationId":"proposals.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/{proposal_id}/apply":{"post":{"operationId":"proposals.apply","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"reason":{"description":"Optional application explanation, preserved unchanged. At most 4096 Unicode characters; NUL is refused.","maxLength":4096,"pattern":"^[^\\u0000]*$","type":"string"},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["submissionVersion","effectDigest"],"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it"}},"x-registry-accessProfiles":["facility-correction-applier"]}},"/v1/proposals/{proposal_id}/attachments/supporting-document":{"delete":{"operationId":"proposals.attachments.supporting-document.delete","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]},"get":{"operationId":"proposals.attachments.supporting-document.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author","proposal-reviewer"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"query","name":"submissionVersion","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"reviewContextField","required":false,"schema":{"pattern":"^[a-z][a-zA-Z0-9]{0,63}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"effectDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"contextSchemaDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}}],"responses":{"200":{"content":{"application/octet-stream":{"schema":{"format":"binary","maxLength":16777216,"type":"string"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author","proposal-reviewer"]},"patch":{"operationId":"proposals.attachments.supporting-document.patch","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/pdf":{"schema":{"format":"binary","maxLength":1048576,"type":"string"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/cancel":{"post":{"operationId":"proposals.cancel","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/edit":{"post":{"operationId":"proposals.edit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/rebase":{"post":{"operationId":"proposals.rebase","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/retry":{"post":{"operationId":"proposals.retry","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/review-context":{"get":{"operationId":"proposals.get-review-context","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["proposal-reviewer"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"fields":{"type":"object"},"reference":{"type":"string"}},"required":["reference","contract","fields"],"type":"object"},"effectDigest":{"type":"string"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["proposal-reviewer"]}},"/v1/proposals/{proposal_id}/review-status":{"get":{"operationId":"proposals.get-review-status","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["casework-review-status","facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Request the institution's optional applicant-visible progress code. The code is returned only when the selected caller-owned grant enables readableReviewProgress.","in":"query","name":"include","required":false,"schema":{"const":"progress"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"reference":{"type":"string"}},"required":["reference"],"type":"object"},"effectDigest":{"type":"string"},"handoff":{"additionalProperties":false,"properties":{"reason":{"enum":["remote-refused","producer-identity-mismatch","review-acceptance-changed","review-policy-changed","submission-recovery-expired","operator-closed","unspecified"]},"state":{"enum":["pending","accepted","failed","withdrawn"]}},"required":["state"],"type":"object"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"progressCode":{"description":"Institution-defined applicant-visible progress. Absent when the institution conceals the current stage, progress was not requested or granted, the provider is unavailable, or the accepted review round is no longer live.","maxLength":64,"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"requestId":{"format":"uuid","type":"string"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["casework-review-status","facility-correction-author"]}},"/v1/proposals/{proposal_id}/revise":{"post":{"operationId":"proposals.revise","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},{"additionalProperties":false,"type":"object"}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/submissions/{submission_version}":{"get":{"operationId":"proposals.get-submission","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"path","name":"submission_version","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"application":{"anyOf":[{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"state":{"const":"applied"}},"required":["state","applicationId"],"type":"object"},{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},{"type":"null"}]},"current":{"type":"boolean"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"review":{"anyOf":[{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},{"type":"null"}]},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["id","actionId","submissionVersion","current","effectDigest","review","application"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"410":{"description":"The submission's review result and application receipt are no longer retained"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/{proposal_id}/submit":{"post":{"operationId":"proposals.submit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it"}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/records/directory-entries":{"get":{"operationId":"records.directory-entry.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"directory-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"directory-editor","selectableProperties":["email","jurisdiction","name"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.directory-entry.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/directory-entry-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"create","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/directory-entries/{record_id}":{"get":{"operationId":"records.directory-entry.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"get","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.directory-entry.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"patch","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/facilities":{"get":{"operationId":"records.facility.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["addressLine","city","facilityCode","jurisdiction","name","postalCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facilities/{record_id}":{"get":{"operationId":"records.facility.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":true,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","proposal-reviewer"],"x-registry-operation":"get","x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/facilities/{record_id}/operators":{"get":{"operationId":"records.facility.path.operators","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facility-assignments":{"get":{"operationId":"records.facility-assignment.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[{"operators":["equals","in","is-null","is-not-null"],"property":"facility"},{"operators":["equals","in","is-null","is-not-null"],"property":"operator"}],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["facility","jurisdiction","operator"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility-assignment","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility-assignment","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facility-assignments/{record_id}":{"get":{"operationId":"records.facility-assignment.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"get","x-registry-recordType":"facility-assignment","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility-assignment","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/operators":{"get":{"operationId":"records.operator.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":true,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","operator-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null},"operator-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"operator-editor","selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.operator.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/operator-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["operator-editor"],"x-registry-operation":"create","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/operators/{record_id}":{"get":{"operationId":"records.operator.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":true,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","operator-editor"],"x-registry-operation":"get","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.operator.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["operator-editor"],"x-registry-operation":"patch","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/review-completions":{"post":{"description":"Available when a review authority configures a completion block.","operationId":"receiveReviewCompletion","parameters":[{"in":"header","name":"Registry-Recipient-Binding","required":true,"schema":{"maxLength":256,"minLength":1,"type":"string"}},{"description":"Must equal eventId.","in":"header","name":"webhook-id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"webhook-timestamp","required":true,"schema":{"pattern":"^(0|[1-9][0-9]{0,19})$","type":"string"}},{"in":"header","name":"webhook-signature","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewCompletion"}}},"required":true},"responses":{"204":{"description":"Completion accepted or already recorded."},"400":{"description":"The completion is invalid or eventId differs from webhook-id."},"401":{"description":"The completion authority could not be authenticated.","headers":{"WWW-Authenticate":{"schema":{"const":"Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"","type":"string"}}}},"413":{"description":"The completion body exceeds 2048 bytes. The response body is empty."},"415":{"description":"The request is not application/json."},"503":{"description":"The completion could not be durably recorded."}},"security":[{"reviewCompletion":[]}],"summary":"Receive a Casework review completion"}}}} \ No newline at end of file +{"components":{"schemas":{"ImmediateActionPrecondition":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"},"ImmediateActionResultReference":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"Problem":{"additionalProperties":false,"allOf":[{"if":{"properties":{"code":{"enum":["attachment.required","attachment.verification-pending","attachment.verification-rejected"]}}},"then":{"allOf":[{"else":{"properties":{"status":{"const":422}}},"if":{"properties":{"code":{"const":"attachment.verification-pending"}}},"then":{"properties":{"status":{"const":409}}}}],"properties":{"fieldPath":{"pattern":"^/attachments/[a-z][a-z0-9_-]{0,63}$","type":"string"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId","fieldPath"]},"required":["fieldPath"]}},{"if":{"properties":{"code":{"const":"write.outside-boundary"}}},"then":{"properties":{"code":{"const":"write.outside-boundary"},"detail":{"const":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."},"status":{"const":403},"title":{"const":"Forbidden"},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId"]}}},{"if":{"properties":{"code":{"not":{"const":"action.guard_failed"}}}},"then":{"not":{"required":["guardReason"]}}},{"if":{"properties":{"code":{"const":"action.refused"}}},"then":{"properties":{"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"const":"statistical_dataset.release_refused"}}},"then":{"properties":{"refusalCode":{"enum":["period-not-ended","before-first-period","provisional-after-final","already-withdrawn","negative-value"]},"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"not":{"enum":["action.refused","statistical_dataset.release_refused"]}}}},"then":{"not":{"required":["refusalCode"]}}},{"if":{"properties":{"code":{"const":"statistical_dataset.version_withdrawn"}}},"then":{"properties":{"status":{"const":410}},"required":["reasonCode"]}},{"if":{"properties":{"code":{"not":{"const":"statistical_dataset.version_withdrawn"}}}},"then":{"not":{"required":["reasonCode"]}}},{"if":{"properties":{"code":{"const":"action.evidence_failed"}}},"then":{"properties":{"detail":{"const":"The declared Evidence dependency could not be accepted."},"fieldPath":{"pattern":"^/evidence/[a-z][a-z0-9_-]{0,63}$","type":"string"},"status":{"const":503}}}},{"if":{"properties":{"code":{"const":"action.handler_failed"}}},"then":{"properties":{"status":{"const":500}}}},{"if":{"anyOf":[{"required":["atField"]},{"required":["notAfterField"]}]},"then":{"properties":{"code":{"const":"request.invalid"},"status":{"const":400}},"required":["atField","notAfterField"]}},{"if":{"anyOf":[{"required":["recordType"]},{"required":["fieldId"]},{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"then":{"oneOf":[{"not":{"anyOf":[{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"required":["fieldId"]},{"not":{"required":["fieldId"]},"oneOf":[{"not":{"required":["field"]},"properties":{"constraintKind":{"const":"compare"}},"required":["left","right"]},{"not":{"anyOf":[{"required":["left"]},{"required":["right"]}]},"properties":{"constraintKind":{"enum":["int-range","vocabulary"]}},"required":["field"]}],"required":["constraintId","constraintKind"]}],"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409}},"required":["recordType"]}}],"properties":{"atField":{"maxLength":128,"minLength":1,"type":"string"},"code":{"enum":["action.evidence_failed","action.guard_failed","action.handler_failed","action.refused","attachment.content-type","attachment.digest-mismatch","attachment.limit-reached","attachment.required","attachment.slot-write-once","attachment.too-large","attachment.verification-pending","attachment.verification-rejected","authentication.refused","idempotency.expired","idempotency.key-reused","ingestion.chunk_mismatch","ingestion.profile_mismatch","ingestion.receipt_erased","ingestion.run_blocked","ingestion.run_not_open","lookup.unresolved","mutation.conflict","precondition.failed","precondition.required","proposal.rejected","proposal.review_result_mismatch","proposal.submission_expired","query.cursor_invalid","query.filter_required","query.invalid","request.access_reason_required","request.invalid","request.timeout","resource.not_found","runtime.field_encryption.unavailable","service.unavailable","source.unavailable","statistical_dataset.domain_violation","statistical_dataset.release_refused","statistical_dataset.version_conflict","statistical_dataset.version_withdrawn","unsupported.media_type","write.outside-boundary"],"type":"string"},"constraintId":{"maxLength":128,"minLength":1,"type":"string"},"constraintKind":{"enum":["compare","int-range","vocabulary"],"type":"string"},"detail":{"maxLength":256,"type":"string"},"field":{"maxLength":128,"minLength":1,"type":"string"},"fieldId":{"maxLength":128,"minLength":1,"type":"string"},"fieldPath":{"maxLength":256,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"left":{"maxLength":128,"minLength":1,"type":"string"},"notAfterField":{"maxLength":128,"minLength":1,"type":"string"},"reasonCode":{"enum":["computation-error","source-data-error","disclosure-risk"],"type":"string"},"recordType":{"maxLength":128,"minLength":1,"type":"string"},"refusalCode":{"maxLength":128,"minLength":1,"type":"string"},"requiredFilters":{"items":{"items":{"maxLength":64,"minLength":1,"type":"string"},"maxItems":32,"minItems":1,"type":"array","uniqueItems":true},"maxItems":8,"minItems":1,"type":"array"},"right":{"maxLength":128,"minLength":1,"type":"string"},"status":{"maximum":599,"minimum":400,"type":"integer"},"title":{"maxLength":128,"type":"string"},"traceId":{"maxLength":32,"minLength":32,"pattern":"^[0-9a-f]{32}$","type":"string"},"type":{"format":"uri","maxLength":256,"type":"string"}},"required":["type","title","status","detail","code","traceId"],"type":"object"},"ReviewCompletion":{"additionalProperties":false,"properties":{"completedAt":{"format":"date-time","type":"string"},"eventId":{"format":"uuid","type":"string"},"requestId":{"format":"uuid","type":"string"},"resultId":{"format":"uuid","type":"string"},"type":{"const":"review.completed"}},"required":["type","eventId","requestId","resultId","completedAt"],"type":"object"},"action-correct-address-invoke-input":{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},"action-correct-address-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-deactivate-facility-invoke-input":{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},"action-deactivate-facility-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-register-facility-availability-input":{"$id":"urn:breg:action:register-facility:availability-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"oneOf":[{"properties":{"input":{"properties":{"operatorId":{"format":"uuid","type":"string"}},"required":["operatorId"]},"targetInput":{"const":"operatorId"}}}],"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"},"targetInput":{"enum":["operatorId"],"type":"string"}},"required":["targetInput","input"],"type":"object","x-registry-action":"register-facility"},"action-register-facility-availability-response":{"$id":"urn:breg:action:register-facility:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardLabel":{"maxLength":256,"minLength":1,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"register-facility"},"action-register-facility-invoke-input":{"$id":"urn:breg:action:register-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-facility","x-registry-requiredConditionKeys":[]},"action-register-facility-invoke-response":{"$id":"urn:breg:action:register-facility:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"register-facility"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"assignment":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility-assignment"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"facility":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["assignment","facility"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"directory-entry":{"$id":"urn:breg:record-type:directory-entry","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"directory-entry-create-input":{"$id":"urn:breg:record-type:directory-entry:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"facility":{"$id":"urn:breg:record-type:facility","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"required":["facilityCode","name","addressLine","city","postalCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable","x-registry-mutationPolicy":{"patch":"proposal-required"}},"facility-assignment":{"$id":"urn:breg:record-type:facility-assignment","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"required":["facility","operator","jurisdiction"],"type":"object","x-registry-mutationMode":"create-only"},"operator":{"$id":"urn:breg:record-type:operator","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"required":["operatorCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"operator-create-input":{"$id":"urn:breg:record-type:operator:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"required":["operatorCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"}},"securitySchemes":{"bearerAuth":{"bearerFormat":"JWT","scheme":"bearer","type":"http"},"reviewCompletion":{"description":"The review authority's configured completion key verifies the Standard Webhooks signature.","in":"header","name":"webhook-signature","type":"apiKey"}}},"info":{"title":"facility-registry","version":"0.1.0"},"openapi":"3.1.0","paths":{"/v1/actions/correct-address/proposals":{"post":{"operationId":"actions.correct-address.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-address-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-address-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-correction-author"],"x-registry-action":{"access":{"accessProfiles":["facility-correction-author"]},"apiName":"correctAddress","attachments":[{"contentTypes":["application/pdf"],"id":"supporting-document","maximumBytes":1048576,"required":false}],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Submit a frozen address correction for independent review and later application.","label":"Correct facility address"},"execution":{"application":"automatic","mode":"proposal","review":"required"},"id":"correct-address","inputMode":"handler","inputs":[{"apiName":"facilityId","classification":"internal","fieldType":{"onDelete":"restrict","target":"facility","type":"reference"},"id":"facility","label":"facilityId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}}],"maximumInputStringBytes":16384,"referenceInputs":[{"apiName":"facilityId","input":"facility","targetRecordType":"facility"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility-address","operation":"patch","recordType":"facility"}],"revision":"sha256:efb20d40704ae6c133b660f2fe3d556b4a00ee5478a5871cf1fd026e7d7b6b7a","route":"/v1/actions/correct-address/proposals","routes":{"availability":null,"start":{"inputSchema":"action-correct-address-invoke-input","method":"POST","operationId":"actions.correct-address.start","path":"/v1/actions/correct-address/proposals","requiresIdempotencyKey":true,"responseSchema":"action-correct-address-invoke-response"}}},"x-registry-defaultAccessProfile":"facility-correction-author","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/deactivate-facility/proposals":{"post":{"operationId":"actions.deactivate-facility.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-deactivate-facility-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-deactivate-facility-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-correction-author"],"x-registry-action":{"access":{"accessProfiles":["facility-correction-author"]},"apiName":"deactivateFacility","attachments":[],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Submit a durable deactivation that requires no external review.","label":"Deactivate facility"},"execution":{"application":"manual","mode":"proposal","review":"none"},"id":"deactivate-facility","inputMode":"fixed","inputs":[{"apiName":"facilityId","classification":"internal","fieldType":{"onDelete":"restrict","target":"facility","type":"reference"},"id":"facility","label":"facilityId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"facilityId","input":"facility","targetRecordType":"facility"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility-status","operation":"patch","recordType":"facility"}],"revision":"sha256:9237300ee419a0014c3b123cc7ac90eb9623cb4c45bba4a65c03936083299f1d","route":"/v1/actions/deactivate-facility/proposals","routes":{"availability":null,"start":{"inputSchema":"action-deactivate-facility-invoke-input","method":"POST","operationId":"actions.deactivate-facility.start","path":"/v1/actions/deactivate-facility/proposals","requiresIdempotencyKey":true,"responseSchema":"action-deactivate-facility-invoke-response"}}},"x-registry-defaultAccessProfile":"facility-correction-author","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/register-facility":{"post":{"operationId":"actions.register-facility.invoke","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-invoke-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-invoke-response"}}},"description":"Immediate action committed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard_failed":{"value":{"code":"action.guard_failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard_failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-registrar"],"x-registry-action":{"access":{"accessProfiles":["facility-registrar"]},"apiName":"registerFacility","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":null,"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"execution":{"mode":"immediate"},"id":"register-facility","inputMode":"fixed","inputs":[{"apiName":"facilityCode","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":1,"type":"string"},"id":"facility-code","label":"facilityCode","nullable":false,"required":true,"schema":{"maxLength":64,"minLength":1,"type":"string"}},{"apiName":"name","classification":"internal","fieldType":{"maximumLength":200,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":200,"minLength":1,"type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}},{"apiName":"operatorId","classification":"internal","fieldType":{"onDelete":"restrict","target":"operator","type":"reference"},"id":"operator","label":"operatorId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"operatorId","input":"operator","targetRecordType":"operator"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility","operation":"create","recordType":"facility"},{"effect":"assignment","operation":"create","recordType":"facility-assignment"}],"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6","route":"/v1/actions/register-facility","routes":{"availability":{"inputSchema":"action-register-facility-availability-input","method":"POST","operationId":"actions.register-facility.availability","path":"/v1/actions/register-facility/availability","requiresIdempotencyKey":false,"responseSchema":"action-register-facility-availability-response"},"invoke":{"inputSchema":"action-register-facility-invoke-input","method":"POST","operationId":"actions.register-facility.invoke","path":"/v1/actions/register-facility","requiresIdempotencyKey":true,"responseSchema":"action-register-facility-invoke-response"},"targetConditions":null}},"x-registry-defaultAccessProfile":"facility-registrar","x-registry-operation":"invoke","x-registry-routeKind":"invoke"}},"/v1/actions/register-facility/availability":{"post":{"operationId":"actions.register-facility.availability","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-availability-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-availability-response"}}},"description":"Action availability returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-registrar"],"x-registry-action":{"access":{"accessProfiles":["facility-registrar"]},"apiName":"registerFacility","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":null,"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"execution":{"mode":"immediate"},"id":"register-facility","inputMode":"fixed","inputs":[{"apiName":"facilityCode","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":1,"type":"string"},"id":"facility-code","label":"facilityCode","nullable":false,"required":true,"schema":{"maxLength":64,"minLength":1,"type":"string"}},{"apiName":"name","classification":"internal","fieldType":{"maximumLength":200,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":200,"minLength":1,"type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}},{"apiName":"operatorId","classification":"internal","fieldType":{"onDelete":"restrict","target":"operator","type":"reference"},"id":"operator","label":"operatorId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"operatorId","input":"operator","targetRecordType":"operator"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility","operation":"create","recordType":"facility"},{"effect":"assignment","operation":"create","recordType":"facility-assignment"}],"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6","route":"/v1/actions/register-facility","routes":{"availability":{"inputSchema":"action-register-facility-availability-input","method":"POST","operationId":"actions.register-facility.availability","path":"/v1/actions/register-facility/availability","requiresIdempotencyKey":false,"responseSchema":"action-register-facility-availability-response"},"invoke":{"inputSchema":"action-register-facility-invoke-input","method":"POST","operationId":"actions.register-facility.invoke","path":"/v1/actions/register-facility","requiresIdempotencyKey":true,"responseSchema":"action-register-facility-invoke-response"},"targetConditions":null}},"x-registry-defaultAccessProfile":"facility-registrar","x-registry-operation":"invoke","x-registry-routeKind":"availability"}},"/v1/proposals":{"get":{"operationId":"proposals.list","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"type":"string"}},{"in":"query","name":"action","schema":{"type":"string"}},{"in":"query","name":"owner","schema":{"const":"caller"}},{"in":"query","name":"target","schema":{"format":"uuid","type":"string"}},{"in":"query","name":"state","schema":{"enum":["draft","submitted","applied","cancelled","rejected"]}},{"in":"query","name":"turn","schema":{"enum":["party","official","nobody"]}},{"in":"query","name":"cursor","schema":{"type":"string"}},{"description":"The most items a page holds. A page may hold fewer than `limit` items, so keep paging while `nextCursor` is present.","in":"query","name":"limit","schema":{"default":50,"maximum":100,"minimum":1,"type":"integer"}},{"in":"query","name":"pendingManualApplication","schema":{"default":false,"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"maxItems":100,"type":"array"},"nextCursor":{"type":"string"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["query.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/review-context":{"get":{"description":"One bounded transport exchange under each item's current get-review-context authority. Ordered visible or concealed results; operational failures refuse the whole batch. Maximum response is 8 MiB.","operationId":"proposals.get-review-context-batch","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["proposal-reviewer"],"type":"string"}},{"description":"One to 100 distinct canonical Proposal UUIDs, in response order.","explode":false,"in":"query","name":"ids","required":true,"schema":{"items":{"format":"uuid","type":"string"},"maxItems":100,"minItems":1,"type":"array","uniqueItems":true},"style":"form"}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"context":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"fields":{"type":"object"},"reference":{"type":"string"}},"required":["reference","contract","fields"],"type":"object"},"effectDigest":{"type":"string"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"},"id":{"format":"uuid","type":"string"},"status":{"const":"visible"}},"required":["id","status","context"],"type":"object"},{"additionalProperties":false,"properties":{"id":{"format":"uuid","type":"string"},"status":{"const":"concealed"}},"required":["id","status"],"type":"object"}]},"maxItems":100,"minItems":1,"type":"array"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["proposal-reviewer"]}},"/v1/proposals/{proposal_id}":{"get":{"operationId":"proposals.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/{proposal_id}/apply":{"post":{"operationId":"proposals.apply","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"reason":{"description":"Optional application explanation, preserved unchanged. At most 4096 Unicode characters; NUL is refused.","maxLength":4096,"pattern":"^[^\\u0000]*$","type":"string"},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["submissionVersion","effectDigest"],"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard_failed":{"value":{"code":"action.guard_failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard_failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}},"proposal.review_result_mismatch":{"value":{"code":"proposal.review_result_mismatch","detail":"The current review result does not match the retained approval.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/review_result_mismatch"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["action.guard_failed","precondition.failed","proposal.review_result_mismatch"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-applier"]}},"/v1/proposals/{proposal_id}/attachments/supporting-document":{"delete":{"operationId":"proposals.attachments.supporting-document.delete","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]},"get":{"operationId":"proposals.attachments.supporting-document.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author","proposal-reviewer"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"query","name":"submissionVersion","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"reviewContextField","required":false,"schema":{"pattern":"^[a-z][a-zA-Z0-9]{0,63}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"effectDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"contextSchemaDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}}],"responses":{"200":{"content":{"*/*":{"schema":{"contentMediaType":"application/octet-stream","maxLength":16777216,"type":"string"}}},"description":"Authorized Proposal operation"},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author","proposal-reviewer"]},"patch":{"operationId":"proposals.attachments.supporting-document.patch","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/pdf":{"schema":{"format":"binary","maxLength":1048576,"type":"string"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"413":{"content":{"application/problem+json":{"examples":{"attachment.too-large":{"value":{"code":"attachment.too-large","detail":"The file is larger than the attachment slot accepts.","status":413,"title":"Content Too Large","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/too-large"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["attachment.too-large"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"attachment.content-type":{"value":{"code":"attachment.content-type","detail":"The file media type is not one the attachment slot accepts.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/content-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["attachment.content-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/cancel":{"post":{"operationId":"proposals.cancel","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/edit":{"post":{"operationId":"proposals.edit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/rebase":{"post":{"operationId":"proposals.rebase","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/retry":{"post":{"operationId":"proposals.retry","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/review-context":{"get":{"operationId":"proposals.get-review-context","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["proposal-reviewer"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Request live applicant answers for a displayed human review context. Admission and preflight reads omit this option and receive no intrinsic asks.","in":"query","name":"include","required":false,"schema":{"const":"answers"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"answeredAt":{"format":"date-time","type":"string"},"documents":{"items":{"additionalProperties":false,"properties":{"byteSize":{"maximum":16777216,"minimum":1,"type":"integer"},"contentType":{"maxLength":255,"type":"string"},"download":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"method":{"const":"GET"},"operation":{"const":"get-review-context"},"path":{"type":"string"}},"required":["method","operation","accessProfile","path"],"type":"object"},"id":{"format":"uuid","type":"string"},"sha256":{"pattern":"^[0-9a-f]{64}$","type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["id","sha256","contentType","byteSize","verificationStatus"],"type":"object"},"maxItems":32,"type":"array"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["documents","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state"],"type":"object"},"maxItems":50,"type":"array"},"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"fields":{"type":"object"},"reference":{"type":"string"}},"required":["reference","contract","fields"],"type":"object"},"effectDigest":{"type":"string"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"}}},"description":"Authorized Proposal operation"},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["proposal-reviewer"]}},"/v1/proposals/{proposal_id}/review-status":{"get":{"operationId":"proposals.get-review-status","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["casework-review-status","facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Request the institution's optional applicant-visible progress code. The code is returned only when the selected caller-owned grant enables readableReviewProgress.","in":"query","name":"include","required":false,"schema":{"const":"progress"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"reference":{"type":"string"}},"required":["reference"],"type":"object"},"effectDigest":{"type":"string"},"handoff":{"additionalProperties":false,"properties":{"reason":{"enum":["remote-refused","producer-identity-mismatch","review-acceptance-changed","review-policy-changed","submission-recovery-expired","operator-closed","unspecified"]},"state":{"enum":["pending","accepted","failed","withdrawn"]}},"required":["state"],"type":"object"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"progressCode":{"description":"Institution-defined applicant-visible progress. Absent when the institution conceals the current stage, progress was not requested or granted, the provider is unavailable, or the accepted review round is no longer live.","maxLength":64,"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"requestId":{"format":"uuid","type":"string"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"}}},"description":"Authorized Proposal operation"},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["casework-review-status","facility-correction-author"]}},"/v1/proposals/{proposal_id}/revise":{"post":{"operationId":"proposals.revise","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},{"additionalProperties":false,"type":"object"}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/submissions/{submission_version}":{"get":{"operationId":"proposals.get-submission","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"path","name":"submission_version","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"application":{"anyOf":[{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"state":{"const":"applied"}},"required":["state","applicationId"],"type":"object"},{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},{"type":"null"}]},"current":{"type":"boolean"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"review":{"anyOf":[{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},{"type":"null"}]},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["id","actionId","submissionVersion","current","effectDigest","review","application"],"type":"object"}}},"description":"Authorized Proposal operation"},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"proposal.submission_expired":{"value":{"code":"proposal.submission_expired","detail":"The review result and application receipt of the submission are no longer retained.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/submission_expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["proposal.submission_expired"]}},"type":"object"}]}}},"description":"The submission's review result and application receipt are no longer retained","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/{proposal_id}/submit":{"post":{"operationId":"proposals.submit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["facility-correction-author"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"attachment.verification-pending":{"value":{"code":"attachment.verification-pending","detail":"The attachment is awaiting verification. Refresh the Proposal before submitting.","fieldPath":"/attachments/supporting-document","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/verification-pending"}},"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["attachment.verification-pending","idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard_failed":{"value":{"code":"action.guard_failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard_failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["action.guard_failed","precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"422":{"content":{"application/problem+json":{"examples":{"action.refused/invalid-postal-code":{"value":{"code":"action.refused","detail":"Postal code is invalid","refusalCode":"invalid-postal-code","status":422,"title":"Unprocessable Entity","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/refused"}},"attachment.verification-rejected":{"value":{"code":"attachment.verification-rejected","detail":"The attachment was rejected by verification. Replace or remove the file before submitting.","fieldPath":"/attachments/supporting-document","status":422,"title":"Unprocessable Entity","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["action.refused","attachment.verification-rejected"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"500":{"content":{"application/problem+json":{"examples":{"action.handler_failed":{"value":{"code":"action.handler_failed","detail":"The action handler could not produce an accepted result.","status":500,"title":"Internal Server Error","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/handler_failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["action.handler_failed"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/records/directory-entries":{"get":{"operationId":"records.directory-entry.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"directory-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"directory-editor","selectableProperties":["email","jurisdiction","name"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.directory-entry.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/directory-entry-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"create","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/directory-entries/{record_id}":{"get":{"operationId":"records.directory-entry.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"get","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.directory-entry.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"directory-entry"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"patch","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/facilities":{"get":{"operationId":"records.facility.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["addressLine","city","facilityCode","jurisdiction","name","postalCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facilities/{record_id}":{"get":{"operationId":"records.facility.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":true,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","proposal-reviewer"],"x-registry-operation":"get","x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/facilities/{record_id}/operators":{"get":{"operationId":"records.facility.path.operators","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facility-assignments":{"get":{"operationId":"records.facility-assignment.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[{"operators":["equals","in","is-null","is-not-null"],"property":"facility"},{"operators":["equals","in","is-null","is-not-null"],"property":"operator"}],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["facility","jurisdiction","operator"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility-assignment","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility-assignment","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facility-assignments/{record_id}":{"get":{"operationId":"records.facility-assignment.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"facility-assignment"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"get","x-registry-recordType":"facility-assignment","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility-assignment","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/operators":{"get":{"operationId":"records.operator.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":true,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","operator-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null},"operator-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"operator-editor","selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.operator.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/operator-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["operator-editor"],"x-registry-operation":"create","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/operators/{record_id}":{"get":{"operationId":"records.operator.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":true,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","operator-editor"],"x-registry-operation":"get","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.operator.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"facility-registry"},"recordTypeIdentifier":{"const":"operator"},"registryIdentifier":{"const":"facility-registry"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["operator-editor"],"x-registry-operation":"patch","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/review-completions":{"post":{"description":"Available when a review authority configures a completion block.","operationId":"receiveReviewCompletion","parameters":[{"in":"header","name":"Registry-Recipient-Binding","required":true,"schema":{"maxLength":256,"minLength":1,"type":"string"}},{"description":"Must equal eventId.","in":"header","name":"webhook-id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"webhook-timestamp","required":true,"schema":{"pattern":"^(0|[1-9][0-9]{0,19})$","type":"string"}},{"in":"header","name":"webhook-signature","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewCompletion"}}},"required":true},"responses":{"204":{"description":"Completion accepted or already recorded."},"400":{"description":"The completion is invalid or eventId differs from webhook-id."},"401":{"description":"The completion authority could not be authenticated.","headers":{"WWW-Authenticate":{"schema":{"const":"Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"","type":"string"}}}},"413":{"description":"The completion body exceeds 2048 bytes. The response body is empty."},"415":{"description":"The request is not application/json."},"503":{"description":"The completion could not be durably recorded."}},"security":[{"reviewCompletion":[]}],"summary":"Receive a Casework review completion"}}}} \ No newline at end of file diff --git a/products/breg/generated/facility/generated/sdk/project.py b/products/breg/generated/facility/generated/sdk/project.py index 4f200efc9d..65fe465fde 100644 --- a/products/breg/generated/facility/generated/sdk/project.py +++ b/products/breg/generated/facility/generated/sdk/project.py @@ -4,7 +4,7 @@ from dataclasses import dataclass -EngineReason = Literal['pending-review', 'review-rejected', 'review-changes-requested', 'review-ended', 'stale-revision', 'package-changed', 'dependency-outage', 'invalid-input', 'already-applied'] +EngineReason = Literal['pending-review', 'review-rejected', 'review-changes-requested', 'review-ended', 'stale-revision', 'package-changed', 'dependency-outage', 'invalid-input', 'already-applied', 'limit-reached', 'application-pending', 'attachment-required', 'attachment-pending', 'ask-answered', 'ask-closed', 'ask-due-passed'] RecoveryHint = Literal['refresh', 'revise', 'retry', 'rebase', 'correct-input', 'receipt-only'] class Availability(TypedDict): available: bool diff --git a/products/breg/generated/facility/generated/sdk/project.ts b/products/breg/generated/facility/generated/sdk/project.ts index 8c4aa0bc36..433615d6cb 100644 --- a/products/breg/generated/facility/generated/sdk/project.ts +++ b/products/breg/generated/facility/generated/sdk/project.ts @@ -1,7 +1,7 @@ // Generated by BReg. Edit the project, then regenerate. import type { breg } from '@registrystack/client'; -export type EngineReason = 'pending-review' | 'review-rejected' | 'review-changes-requested' | 'review-ended' | 'stale-revision' | 'package-changed' | 'dependency-outage' | 'invalid-input' | 'already-applied'; +export type EngineReason = 'pending-review' | 'review-rejected' | 'review-changes-requested' | 'review-ended' | 'stale-revision' | 'package-changed' | 'dependency-outage' | 'invalid-input' | 'already-applied' | 'limit-reached' | 'application-pending' | 'attachment-required' | 'attachment-pending' | 'ask-answered' | 'ask-closed' | 'ask-due-passed'; export type RecoveryHint = 'refresh' | 'revise' | 'retry' | 'rebase' | 'correct-input' | 'receipt-only'; export type Availability = | { readonly available: true; readonly observedRevision: number } diff --git a/products/breg/generated/minimal/generated/action-contracts.json b/products/breg/generated/minimal/generated/action-contracts.json index 52e20d6c34..67bb4af4d2 100644 --- a/products/breg/generated/minimal/generated/action-contracts.json +++ b/products/breg/generated/minimal/generated/action-contracts.json @@ -1 +1 @@ -{"actions":[{"application":{"maximumAttempts":3,"mode":"automatic"},"display":{"description":"Create one contact through a Proposal that applies on submit without external review.","label":"Register contact"},"id":"register-contact","input":{"$id":"urn:breg:action:register-contact:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-contact","x-registry-requiredConditionKeys":[]},"mode":"proposal","output":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"review":{"type":"none"},"revision":"sha256:2a81cd7c0637d4bfd3043ca4643134bde20a92d9e14ba15cd966a8e00d3e40da"},{"display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"id":"update-contact-email","input":{"$id":"urn:breg:action:update-contact-email:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"},"email":{"maxLength":254,"minLength":1,"type":"string"}},"required":["contactId","email"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{"contactId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["contactId"],"type":"object"}},"required":["input","preconditions"],"type":"object","x-registry-action":"update-contact-email","x-registry-requiredConditionKeys":["contactId"]},"mode":"immediate","output":{"$id":"urn:breg:action:update-contact-email:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"update-contact-email"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"contact-email":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"contact"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["contact-email"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066"}],"apiVersion":"id.registrystack.org/formats/breg/action-contracts/v1","kind":"BRegActionContracts"} \ No newline at end of file +{"actions":[{"application":{"maximumAttempts":3,"mode":"automatic"},"display":{"description":"Create one contact through a Proposal that applies on submit without external review.","label":"Register contact"},"id":"register-contact","input":{"$id":"urn:breg:action:register-contact:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-contact","x-registry-requiredConditionKeys":[]},"mode":"proposal","output":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"review":{"type":"none"},"revision":"sha256:2a81cd7c0637d4bfd3043ca4643134bde20a92d9e14ba15cd966a8e00d3e40da"},{"display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"id":"update-contact-email","input":{"$id":"urn:breg:action:update-contact-email:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"},"email":{"maxLength":254,"minLength":1,"type":"string"}},"required":["contactId","email"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{"contactId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["contactId"],"type":"object"}},"required":["input","preconditions"],"type":"object","x-registry-action":"update-contact-email","x-registry-requiredConditionKeys":["contactId"]},"mode":"immediate","output":{"$id":"urn:breg:action:update-contact-email:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"update-contact-email"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"contact-email":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"contact"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["contact-email"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066"}],"apiVersion":"id.registrystack.org/formats/breg/action-contracts/v1","kind":"BRegActionContracts"} \ No newline at end of file diff --git a/products/breg/generated/minimal/generated/action-schemas/register-contact.invoke.response.schema.json b/products/breg/generated/minimal/generated/action-schemas/register-contact.invoke.response.schema.json index 5599f4c48a..fbfdbff5d7 100644 --- a/products/breg/generated/minimal/generated/action-schemas/register-contact.invoke.response.schema.json +++ b/products/breg/generated/minimal/generated/action-schemas/register-contact.invoke.response.schema.json @@ -1 +1 @@ -{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"} \ No newline at end of file +{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"} \ No newline at end of file diff --git a/products/breg/generated/minimal/generated/openapi.json b/products/breg/generated/minimal/generated/openapi.json index f879b71d6a..a31796d7db 100644 --- a/products/breg/generated/minimal/generated/openapi.json +++ b/products/breg/generated/minimal/generated/openapi.json @@ -1 +1 @@ -{"components":{"schemas":{"ImmediateActionPrecondition":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"},"ImmediateActionResultReference":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"Problem":{"additionalProperties":false,"allOf":[{"if":{"properties":{"code":{"const":"write.outside-boundary"}}},"then":{"properties":{"code":{"const":"write.outside-boundary"},"detail":{"const":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."},"status":{"const":403},"title":{"const":"Forbidden"},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId"]}}},{"if":{"properties":{"code":{"not":{"const":"action.guard_failed"}}}},"then":{"not":{"required":["guardReason"]}}},{"if":{"properties":{"code":{"const":"action.refused"}}},"then":{"properties":{"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"const":"statistical_dataset.release_refused"}}},"then":{"properties":{"refusalCode":{"enum":["period-not-ended","before-first-period","provisional-after-final","already-withdrawn","negative-value"]},"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"not":{"enum":["action.refused","statistical_dataset.release_refused"]}}}},"then":{"not":{"required":["refusalCode"]}}},{"if":{"properties":{"code":{"const":"statistical_dataset.version_withdrawn"}}},"then":{"properties":{"status":{"const":410}},"required":["reasonCode"]}},{"if":{"properties":{"code":{"not":{"const":"statistical_dataset.version_withdrawn"}}}},"then":{"not":{"required":["reasonCode"]}}},{"if":{"properties":{"code":{"const":"action.evidence_failed"}}},"then":{"properties":{"detail":{"const":"The declared Evidence dependency could not be accepted."},"fieldPath":{"pattern":"^/evidence/[a-z][a-z0-9_-]{0,63}$","type":"string"},"status":{"const":503}}}},{"if":{"properties":{"code":{"const":"action.handler_failed"}}},"then":{"properties":{"status":{"const":500}}}},{"if":{"anyOf":[{"required":["atField"]},{"required":["notAfterField"]}]},"then":{"properties":{"code":{"const":"request.invalid"},"status":{"const":400}},"required":["atField","notAfterField"]}},{"if":{"anyOf":[{"required":["recordType"]},{"required":["fieldId"]},{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"then":{"oneOf":[{"not":{"anyOf":[{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"required":["fieldId"]},{"not":{"required":["fieldId"]},"oneOf":[{"not":{"required":["field"]},"properties":{"constraintKind":{"const":"compare"}},"required":["left","right"]},{"not":{"anyOf":[{"required":["left"]},{"required":["right"]}]},"properties":{"constraintKind":{"enum":["int-range","vocabulary"]}},"required":["field"]}],"required":["constraintId","constraintKind"]}],"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409}},"required":["recordType"]}}],"properties":{"atField":{"maxLength":128,"minLength":1,"type":"string"},"code":{"enum":["action.evidence_failed","action.guard_failed","action.handler_failed","action.refused","attachment.content-type","attachment.digest-mismatch","attachment.slot-write-once","attachment.too-large","authentication.refused","idempotency.expired","idempotency.key-reused","ingestion.chunk_mismatch","ingestion.profile_mismatch","ingestion.receipt_erased","ingestion.run_blocked","ingestion.run_not_open","lookup.unresolved","mutation.conflict","precondition.failed","precondition.required","proposal.rejected","proposal.review_result_mismatch","proposal.submission_expired","query.cursor_invalid","query.filter_required","query.invalid","request.access_reason_required","request.invalid","request.timeout","resource.not_found","runtime.field_encryption.unavailable","service.unavailable","source.unavailable","statistical_dataset.domain_violation","statistical_dataset.release_refused","statistical_dataset.version_conflict","statistical_dataset.version_withdrawn","unsupported.media_type","write.outside-boundary"],"type":"string"},"constraintId":{"maxLength":128,"minLength":1,"type":"string"},"constraintKind":{"enum":["compare","int-range","vocabulary"],"type":"string"},"detail":{"maxLength":256,"type":"string"},"field":{"maxLength":128,"minLength":1,"type":"string"},"fieldId":{"maxLength":128,"minLength":1,"type":"string"},"fieldPath":{"maxLength":256,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"left":{"maxLength":128,"minLength":1,"type":"string"},"notAfterField":{"maxLength":128,"minLength":1,"type":"string"},"reasonCode":{"enum":["computation-error","source-data-error","disclosure-risk"],"type":"string"},"recordType":{"maxLength":128,"minLength":1,"type":"string"},"refusalCode":{"maxLength":128,"minLength":1,"type":"string"},"requiredFilters":{"items":{"items":{"maxLength":64,"minLength":1,"type":"string"},"maxItems":32,"minItems":1,"type":"array","uniqueItems":true},"maxItems":8,"minItems":1,"type":"array"},"right":{"maxLength":128,"minLength":1,"type":"string"},"status":{"maximum":599,"minimum":400,"type":"integer"},"title":{"maxLength":128,"type":"string"},"traceId":{"maxLength":32,"minLength":32,"pattern":"^[0-9a-f]{32}$","type":"string"},"type":{"format":"uri","maxLength":256,"type":"string"}},"required":["type","title","status","detail","code","traceId"],"type":"object"},"ReviewCompletion":{"additionalProperties":false,"properties":{"completedAt":{"format":"date-time","type":"string"},"eventId":{"format":"uuid","type":"string"},"requestId":{"format":"uuid","type":"string"},"resultId":{"format":"uuid","type":"string"},"type":{"const":"review.completed"}},"required":["type","eventId","requestId","resultId","completedAt"],"type":"object"},"action-register-contact-invoke-input":{"$id":"urn:breg:action:register-contact:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-contact","x-registry-requiredConditionKeys":[]},"action-register-contact-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-update-contact-email-availability-input":{"$id":"urn:breg:action:update-contact-email:availability-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"oneOf":[{"properties":{"input":{"properties":{"contactId":{"format":"uuid","type":"string"}},"required":["contactId"]},"targetInput":{"const":"contactId"}}}],"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"},"email":{"maxLength":254,"minLength":1,"type":"string"}},"required":[],"type":"object"},"targetInput":{"enum":["contactId"],"type":"string"}},"required":["targetInput","input"],"type":"object","x-registry-action":"update-contact-email"},"action-update-contact-email-availability-response":{"$id":"urn:breg:action:update-contact-email:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardLabel":{"maxLength":256,"minLength":1,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["contactId","email"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"update-contact-email"},"action-update-contact-email-invoke-input":{"$id":"urn:breg:action:update-contact-email:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"},"email":{"maxLength":254,"minLength":1,"type":"string"}},"required":["contactId","email"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{"contactId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["contactId"],"type":"object"}},"required":["input","preconditions"],"type":"object","x-registry-action":"update-contact-email","x-registry-requiredConditionKeys":["contactId"]},"action-update-contact-email-invoke-response":{"$id":"urn:breg:action:update-contact-email:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"update-contact-email"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"contact-email":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"contact"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["contact-email"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"action-update-contact-email-target-conditions-input":{"$id":"urn:breg:action:update-contact-email:target-conditions-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"}},"required":["contactId"],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"update-contact-email","x-registry-requiredConditionKeys":["contactId"]},"action-update-contact-email-target-conditions-response":{"$id":"urn:breg:action:update-contact-email:target-conditions-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"preconditions":{"additionalProperties":false,"properties":{"contactId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["contactId"],"type":"object"}},"required":["preconditions"],"type":"object","x-registry-action":"update-contact-email"},"contact":{"$id":"urn:breg:record-type:contact","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"contact-create-input":{"$id":"urn:breg:record-type:contact:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"}},"securitySchemes":{"bearerAuth":{"bearerFormat":"JWT","scheme":"bearer","type":"http"},"reviewCompletion":{"description":"The review authority's configured completion key verifies the Standard Webhooks signature.","in":"header","name":"webhook-signature","type":"apiKey"}}},"info":{"title":"local-directory","version":"0.1.0"},"openapi":"3.1.0","paths":{"/v1/actions/register-contact/proposals":{"post":{"operationId":"actions.register-contact.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-contact-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-contact-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"registerContact","attachments":[],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Create one contact through a Proposal that applies on submit without external review.","label":"Register contact"},"execution":{"application":"automatic","mode":"proposal","review":"none"},"id":"register-contact","inputMode":"fixed","inputs":[{"apiName":"name","classification":"internal","fieldType":{"maximumLength":160,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":160,"minLength":1,"type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[],"requiredConditionKeys":[],"resultEffects":[{"effect":"contact","operation":"create","recordType":"contact"}],"revision":"sha256:2a81cd7c0637d4bfd3043ca4643134bde20a92d9e14ba15cd966a8e00d3e40da","route":"/v1/actions/register-contact/proposals","routes":{"availability":null,"start":{"inputSchema":"action-register-contact-invoke-input","method":"POST","operationId":"actions.register-contact.start","path":"/v1/actions/register-contact/proposals","requiresIdempotencyKey":true,"responseSchema":"action-register-contact-invoke-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/update-contact-email":{"post":{"operationId":"actions.update-contact-email.invoke","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-invoke-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-invoke-response"}}},"description":"Immediate action committed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard_failed":{"value":{"code":"action.guard_failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard_failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"updateContactEmail","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":"/v1/actions/update-contact-email/target-conditions","display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"execution":{"mode":"immediate"},"id":"update-contact-email","inputMode":"fixed","inputs":[{"apiName":"contactId","classification":"internal","fieldType":{"onDelete":"restrict","target":"contact","type":"reference"},"id":"contact","label":"contactId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"contactId","input":"contact","targetRecordType":"contact"}],"requiredConditionKeys":["contactId"],"resultEffects":[{"effect":"contact-email","operation":"patch","recordType":"contact"}],"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066","route":"/v1/actions/update-contact-email","routes":{"availability":{"inputSchema":"action-update-contact-email-availability-input","method":"POST","operationId":"actions.update-contact-email.availability","path":"/v1/actions/update-contact-email/availability","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-availability-response"},"invoke":{"inputSchema":"action-update-contact-email-invoke-input","method":"POST","operationId":"actions.update-contact-email.invoke","path":"/v1/actions/update-contact-email","requiresIdempotencyKey":true,"responseSchema":"action-update-contact-email-invoke-response"},"targetConditions":{"inputSchema":"action-update-contact-email-target-conditions-input","method":"POST","operationId":"actions.update-contact-email.target-conditions","path":"/v1/actions/update-contact-email/target-conditions","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-target-conditions-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"invoke","x-registry-routeKind":"invoke"}},"/v1/actions/update-contact-email/availability":{"post":{"operationId":"actions.update-contact-email.availability","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-availability-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-availability-response"}}},"description":"Action availability returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"updateContactEmail","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":"/v1/actions/update-contact-email/target-conditions","display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"execution":{"mode":"immediate"},"id":"update-contact-email","inputMode":"fixed","inputs":[{"apiName":"contactId","classification":"internal","fieldType":{"onDelete":"restrict","target":"contact","type":"reference"},"id":"contact","label":"contactId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"contactId","input":"contact","targetRecordType":"contact"}],"requiredConditionKeys":["contactId"],"resultEffects":[{"effect":"contact-email","operation":"patch","recordType":"contact"}],"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066","route":"/v1/actions/update-contact-email","routes":{"availability":{"inputSchema":"action-update-contact-email-availability-input","method":"POST","operationId":"actions.update-contact-email.availability","path":"/v1/actions/update-contact-email/availability","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-availability-response"},"invoke":{"inputSchema":"action-update-contact-email-invoke-input","method":"POST","operationId":"actions.update-contact-email.invoke","path":"/v1/actions/update-contact-email","requiresIdempotencyKey":true,"responseSchema":"action-update-contact-email-invoke-response"},"targetConditions":{"inputSchema":"action-update-contact-email-target-conditions-input","method":"POST","operationId":"actions.update-contact-email.target-conditions","path":"/v1/actions/update-contact-email/target-conditions","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-target-conditions-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"invoke","x-registry-routeKind":"availability"}},"/v1/actions/update-contact-email/target-conditions":{"post":{"operationId":"actions.update-contact-email.target-conditions","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-target-conditions-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-target-conditions-response"}}},"description":"Action target conditions returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"updateContactEmail","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":"/v1/actions/update-contact-email/target-conditions","display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"execution":{"mode":"immediate"},"id":"update-contact-email","inputMode":"fixed","inputs":[{"apiName":"contactId","classification":"internal","fieldType":{"onDelete":"restrict","target":"contact","type":"reference"},"id":"contact","label":"contactId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"contactId","input":"contact","targetRecordType":"contact"}],"requiredConditionKeys":["contactId"],"resultEffects":[{"effect":"contact-email","operation":"patch","recordType":"contact"}],"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066","route":"/v1/actions/update-contact-email","routes":{"availability":{"inputSchema":"action-update-contact-email-availability-input","method":"POST","operationId":"actions.update-contact-email.availability","path":"/v1/actions/update-contact-email/availability","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-availability-response"},"invoke":{"inputSchema":"action-update-contact-email-invoke-input","method":"POST","operationId":"actions.update-contact-email.invoke","path":"/v1/actions/update-contact-email","requiresIdempotencyKey":true,"responseSchema":"action-update-contact-email-invoke-response"},"targetConditions":{"inputSchema":"action-update-contact-email-target-conditions-input","method":"POST","operationId":"actions.update-contact-email.target-conditions","path":"/v1/actions/update-contact-email/target-conditions","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-target-conditions-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"invoke","x-registry-routeKind":"target-conditions"}},"/v1/proposals":{"get":{"operationId":"proposals.list","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"query","name":"action","schema":{"type":"string"}},{"in":"query","name":"owner","schema":{"const":"caller"}},{"in":"query","name":"target","schema":{"format":"uuid","type":"string"}},{"in":"query","name":"state","schema":{"enum":["draft","submitted","applied","cancelled","rejected"]}},{"in":"query","name":"turn","schema":{"enum":["party","official","nobody"]}},{"in":"query","name":"cursor","schema":{"type":"string"}},{"description":"The most items a page holds. A page may hold fewer than `limit` items, so keep paging while `nextCursor` is present.","in":"query","name":"limit","schema":{"default":50,"maximum":100,"minimum":1,"type":"integer"}},{"in":"query","name":"pendingManualApplication","schema":{"default":false,"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"maxItems":100,"type":"array"},"nextCursor":{"type":"string"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}":{"get":{"operationId":"proposals.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/cancel":{"post":{"operationId":"proposals.cancel","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/edit":{"post":{"operationId":"proposals.edit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:register-contact:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-contact","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/submissions/{submission_version}":{"get":{"operationId":"proposals.get-submission","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"path","name":"submission_version","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"application":{"anyOf":[{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"state":{"const":"applied"}},"required":["state","applicationId"],"type":"object"},{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},{"type":"null"}]},"current":{"type":"boolean"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"review":{"anyOf":[{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},{"type":"null"}]},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["id","actionId","submissionVersion","current","effectDigest","review","application"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"410":{"description":"The submission's review result and application receipt are no longer retained"},"412":{"description":"Observed authority or lifecycle condition changed"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/submit":{"post":{"operationId":"proposals.submit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"404":{"description":"Resource unavailable to this caller"},"409":{"description":"The Proposal was rejected, or the idempotency key was reused with a different request"},"412":{"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it"}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/records/contacts":{"get":{"operationId":"records.contact.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"directory-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"directory-editor","selectableProperties":["email","jurisdiction","name"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.contact.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/contact-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"create","x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/contacts/{record_id}":{"get":{"operationId":"records.contact.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"get","x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.contact.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"patch","x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/review-completions":{"post":{"description":"Available when a review authority configures a completion block.","operationId":"receiveReviewCompletion","parameters":[{"in":"header","name":"Registry-Recipient-Binding","required":true,"schema":{"maxLength":256,"minLength":1,"type":"string"}},{"description":"Must equal eventId.","in":"header","name":"webhook-id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"webhook-timestamp","required":true,"schema":{"pattern":"^(0|[1-9][0-9]{0,19})$","type":"string"}},{"in":"header","name":"webhook-signature","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewCompletion"}}},"required":true},"responses":{"204":{"description":"Completion accepted or already recorded."},"400":{"description":"The completion is invalid or eventId differs from webhook-id."},"401":{"description":"The completion authority could not be authenticated.","headers":{"WWW-Authenticate":{"schema":{"const":"Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"","type":"string"}}}},"413":{"description":"The completion body exceeds 2048 bytes. The response body is empty."},"415":{"description":"The request is not application/json."},"503":{"description":"The completion could not be durably recorded."}},"security":[{"reviewCompletion":[]}],"summary":"Receive a Casework review completion"}}}} \ No newline at end of file +{"components":{"schemas":{"ImmediateActionPrecondition":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"},"ImmediateActionResultReference":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"Problem":{"additionalProperties":false,"allOf":[{"if":{"properties":{"code":{"enum":["attachment.required","attachment.verification-pending","attachment.verification-rejected"]}}},"then":{"allOf":[{"else":{"properties":{"status":{"const":422}}},"if":{"properties":{"code":{"const":"attachment.verification-pending"}}},"then":{"properties":{"status":{"const":409}}}}],"properties":{"fieldPath":{"pattern":"^/attachments/[a-z][a-z0-9_-]{0,63}$","type":"string"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId","fieldPath"]},"required":["fieldPath"]}},{"if":{"properties":{"code":{"const":"write.outside-boundary"}}},"then":{"properties":{"code":{"const":"write.outside-boundary"},"detail":{"const":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."},"status":{"const":403},"title":{"const":"Forbidden"},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId"]}}},{"if":{"properties":{"code":{"not":{"const":"action.guard_failed"}}}},"then":{"not":{"required":["guardReason"]}}},{"if":{"properties":{"code":{"const":"action.refused"}}},"then":{"properties":{"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"const":"statistical_dataset.release_refused"}}},"then":{"properties":{"refusalCode":{"enum":["period-not-ended","before-first-period","provisional-after-final","already-withdrawn","negative-value"]},"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"not":{"enum":["action.refused","statistical_dataset.release_refused"]}}}},"then":{"not":{"required":["refusalCode"]}}},{"if":{"properties":{"code":{"const":"statistical_dataset.version_withdrawn"}}},"then":{"properties":{"status":{"const":410}},"required":["reasonCode"]}},{"if":{"properties":{"code":{"not":{"const":"statistical_dataset.version_withdrawn"}}}},"then":{"not":{"required":["reasonCode"]}}},{"if":{"properties":{"code":{"const":"action.evidence_failed"}}},"then":{"properties":{"detail":{"const":"The declared Evidence dependency could not be accepted."},"fieldPath":{"pattern":"^/evidence/[a-z][a-z0-9_-]{0,63}$","type":"string"},"status":{"const":503}}}},{"if":{"properties":{"code":{"const":"action.handler_failed"}}},"then":{"properties":{"status":{"const":500}}}},{"if":{"anyOf":[{"required":["atField"]},{"required":["notAfterField"]}]},"then":{"properties":{"code":{"const":"request.invalid"},"status":{"const":400}},"required":["atField","notAfterField"]}},{"if":{"anyOf":[{"required":["recordType"]},{"required":["fieldId"]},{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"then":{"oneOf":[{"not":{"anyOf":[{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"required":["fieldId"]},{"not":{"required":["fieldId"]},"oneOf":[{"not":{"required":["field"]},"properties":{"constraintKind":{"const":"compare"}},"required":["left","right"]},{"not":{"anyOf":[{"required":["left"]},{"required":["right"]}]},"properties":{"constraintKind":{"enum":["int-range","vocabulary"]}},"required":["field"]}],"required":["constraintId","constraintKind"]}],"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409}},"required":["recordType"]}}],"properties":{"atField":{"maxLength":128,"minLength":1,"type":"string"},"code":{"enum":["action.evidence_failed","action.guard_failed","action.handler_failed","action.refused","attachment.content-type","attachment.digest-mismatch","attachment.limit-reached","attachment.required","attachment.slot-write-once","attachment.too-large","attachment.verification-pending","attachment.verification-rejected","authentication.refused","idempotency.expired","idempotency.key-reused","ingestion.chunk_mismatch","ingestion.profile_mismatch","ingestion.receipt_erased","ingestion.run_blocked","ingestion.run_not_open","lookup.unresolved","mutation.conflict","precondition.failed","precondition.required","proposal.rejected","proposal.review_result_mismatch","proposal.submission_expired","query.cursor_invalid","query.filter_required","query.invalid","request.access_reason_required","request.invalid","request.timeout","resource.not_found","runtime.field_encryption.unavailable","service.unavailable","source.unavailable","statistical_dataset.domain_violation","statistical_dataset.release_refused","statistical_dataset.version_conflict","statistical_dataset.version_withdrawn","unsupported.media_type","write.outside-boundary"],"type":"string"},"constraintId":{"maxLength":128,"minLength":1,"type":"string"},"constraintKind":{"enum":["compare","int-range","vocabulary"],"type":"string"},"detail":{"maxLength":256,"type":"string"},"field":{"maxLength":128,"minLength":1,"type":"string"},"fieldId":{"maxLength":128,"minLength":1,"type":"string"},"fieldPath":{"maxLength":256,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"left":{"maxLength":128,"minLength":1,"type":"string"},"notAfterField":{"maxLength":128,"minLength":1,"type":"string"},"reasonCode":{"enum":["computation-error","source-data-error","disclosure-risk"],"type":"string"},"recordType":{"maxLength":128,"minLength":1,"type":"string"},"refusalCode":{"maxLength":128,"minLength":1,"type":"string"},"requiredFilters":{"items":{"items":{"maxLength":64,"minLength":1,"type":"string"},"maxItems":32,"minItems":1,"type":"array","uniqueItems":true},"maxItems":8,"minItems":1,"type":"array"},"right":{"maxLength":128,"minLength":1,"type":"string"},"status":{"maximum":599,"minimum":400,"type":"integer"},"title":{"maxLength":128,"type":"string"},"traceId":{"maxLength":32,"minLength":32,"pattern":"^[0-9a-f]{32}$","type":"string"},"type":{"format":"uri","maxLength":256,"type":"string"}},"required":["type","title","status","detail","code","traceId"],"type":"object"},"ReviewCompletion":{"additionalProperties":false,"properties":{"completedAt":{"format":"date-time","type":"string"},"eventId":{"format":"uuid","type":"string"},"requestId":{"format":"uuid","type":"string"},"resultId":{"format":"uuid","type":"string"},"type":{"const":"review.completed"}},"required":["type","eventId","requestId","resultId","completedAt"],"type":"object"},"action-register-contact-invoke-input":{"$id":"urn:breg:action:register-contact:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-contact","x-registry-requiredConditionKeys":[]},"action-register-contact-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-update-contact-email-availability-input":{"$id":"urn:breg:action:update-contact-email:availability-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"oneOf":[{"properties":{"input":{"properties":{"contactId":{"format":"uuid","type":"string"}},"required":["contactId"]},"targetInput":{"const":"contactId"}}}],"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"},"email":{"maxLength":254,"minLength":1,"type":"string"}},"required":[],"type":"object"},"targetInput":{"enum":["contactId"],"type":"string"}},"required":["targetInput","input"],"type":"object","x-registry-action":"update-contact-email"},"action-update-contact-email-availability-response":{"$id":"urn:breg:action:update-contact-email:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardLabel":{"maxLength":256,"minLength":1,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["contactId","email"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"update-contact-email"},"action-update-contact-email-invoke-input":{"$id":"urn:breg:action:update-contact-email:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"},"email":{"maxLength":254,"minLength":1,"type":"string"}},"required":["contactId","email"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{"contactId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["contactId"],"type":"object"}},"required":["input","preconditions"],"type":"object","x-registry-action":"update-contact-email","x-registry-requiredConditionKeys":["contactId"]},"action-update-contact-email-invoke-response":{"$id":"urn:breg:action:update-contact-email:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"update-contact-email"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"contact-email":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"contact"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["contact-email"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"action-update-contact-email-target-conditions-input":{"$id":"urn:breg:action:update-contact-email:target-conditions-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"contactId":{"format":"uuid","type":"string"}},"required":["contactId"],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"update-contact-email","x-registry-requiredConditionKeys":["contactId"]},"action-update-contact-email-target-conditions-response":{"$id":"urn:breg:action:update-contact-email:target-conditions-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"preconditions":{"additionalProperties":false,"properties":{"contactId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["contactId"],"type":"object"}},"required":["preconditions"],"type":"object","x-registry-action":"update-contact-email"},"contact":{"$id":"urn:breg:record-type:contact","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"contact-create-input":{"$id":"urn:breg:record-type:contact:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"}},"securitySchemes":{"bearerAuth":{"bearerFormat":"JWT","scheme":"bearer","type":"http"},"reviewCompletion":{"description":"The review authority's configured completion key verifies the Standard Webhooks signature.","in":"header","name":"webhook-signature","type":"apiKey"}}},"info":{"title":"local-directory","version":"0.1.0"},"openapi":"3.1.0","paths":{"/v1/actions/register-contact/proposals":{"post":{"operationId":"actions.register-contact.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-contact-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-contact-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"registerContact","attachments":[],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Create one contact through a Proposal that applies on submit without external review.","label":"Register contact"},"execution":{"application":"automatic","mode":"proposal","review":"none"},"id":"register-contact","inputMode":"fixed","inputs":[{"apiName":"name","classification":"internal","fieldType":{"maximumLength":160,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":160,"minLength":1,"type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[],"requiredConditionKeys":[],"resultEffects":[{"effect":"contact","operation":"create","recordType":"contact"}],"revision":"sha256:2a81cd7c0637d4bfd3043ca4643134bde20a92d9e14ba15cd966a8e00d3e40da","route":"/v1/actions/register-contact/proposals","routes":{"availability":null,"start":{"inputSchema":"action-register-contact-invoke-input","method":"POST","operationId":"actions.register-contact.start","path":"/v1/actions/register-contact/proposals","requiresIdempotencyKey":true,"responseSchema":"action-register-contact-invoke-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/update-contact-email":{"post":{"operationId":"actions.update-contact-email.invoke","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-invoke-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-invoke-response"}}},"description":"Immediate action committed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard_failed":{"value":{"code":"action.guard_failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard_failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"updateContactEmail","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":"/v1/actions/update-contact-email/target-conditions","display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"execution":{"mode":"immediate"},"id":"update-contact-email","inputMode":"fixed","inputs":[{"apiName":"contactId","classification":"internal","fieldType":{"onDelete":"restrict","target":"contact","type":"reference"},"id":"contact","label":"contactId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"contactId","input":"contact","targetRecordType":"contact"}],"requiredConditionKeys":["contactId"],"resultEffects":[{"effect":"contact-email","operation":"patch","recordType":"contact"}],"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066","route":"/v1/actions/update-contact-email","routes":{"availability":{"inputSchema":"action-update-contact-email-availability-input","method":"POST","operationId":"actions.update-contact-email.availability","path":"/v1/actions/update-contact-email/availability","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-availability-response"},"invoke":{"inputSchema":"action-update-contact-email-invoke-input","method":"POST","operationId":"actions.update-contact-email.invoke","path":"/v1/actions/update-contact-email","requiresIdempotencyKey":true,"responseSchema":"action-update-contact-email-invoke-response"},"targetConditions":{"inputSchema":"action-update-contact-email-target-conditions-input","method":"POST","operationId":"actions.update-contact-email.target-conditions","path":"/v1/actions/update-contact-email/target-conditions","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-target-conditions-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"invoke","x-registry-routeKind":"invoke"}},"/v1/actions/update-contact-email/availability":{"post":{"operationId":"actions.update-contact-email.availability","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-availability-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-availability-response"}}},"description":"Action availability returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field_encryption.unavailable":{"value":{"code":"runtime.field_encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field_encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"updateContactEmail","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":"/v1/actions/update-contact-email/target-conditions","display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"execution":{"mode":"immediate"},"id":"update-contact-email","inputMode":"fixed","inputs":[{"apiName":"contactId","classification":"internal","fieldType":{"onDelete":"restrict","target":"contact","type":"reference"},"id":"contact","label":"contactId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"contactId","input":"contact","targetRecordType":"contact"}],"requiredConditionKeys":["contactId"],"resultEffects":[{"effect":"contact-email","operation":"patch","recordType":"contact"}],"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066","route":"/v1/actions/update-contact-email","routes":{"availability":{"inputSchema":"action-update-contact-email-availability-input","method":"POST","operationId":"actions.update-contact-email.availability","path":"/v1/actions/update-contact-email/availability","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-availability-response"},"invoke":{"inputSchema":"action-update-contact-email-invoke-input","method":"POST","operationId":"actions.update-contact-email.invoke","path":"/v1/actions/update-contact-email","requiresIdempotencyKey":true,"responseSchema":"action-update-contact-email-invoke-response"},"targetConditions":{"inputSchema":"action-update-contact-email-target-conditions-input","method":"POST","operationId":"actions.update-contact-email.target-conditions","path":"/v1/actions/update-contact-email/target-conditions","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-target-conditions-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"invoke","x-registry-routeKind":"availability"}},"/v1/actions/update-contact-email/target-conditions":{"post":{"operationId":"actions.update-contact-email.target-conditions","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-target-conditions-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-update-contact-email-target-conditions-response"}}},"description":"Action target conditions returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-action":{"access":{"accessProfiles":["directory-editor"]},"apiName":"updateContactEmail","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":"/v1/actions/update-contact-email/target-conditions","display":{"description":"Replace one contact's email address as soon as the Action is invoked.","label":"Update contact email"},"execution":{"mode":"immediate"},"id":"update-contact-email","inputMode":"fixed","inputs":[{"apiName":"contactId","classification":"internal","fieldType":{"onDelete":"restrict","target":"contact","type":"reference"},"id":"contact","label":"contactId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"email","classification":"internal","fieldType":{"maximumLength":254,"minimumLength":1,"type":"string"},"id":"email","label":"email","nullable":false,"required":true,"schema":{"maxLength":254,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"contactId","input":"contact","targetRecordType":"contact"}],"requiredConditionKeys":["contactId"],"resultEffects":[{"effect":"contact-email","operation":"patch","recordType":"contact"}],"revision":"sha256:ca1bd47281413d63288eb89a49143a8e56fcee9320d904db1219ee1ec89f1066","route":"/v1/actions/update-contact-email","routes":{"availability":{"inputSchema":"action-update-contact-email-availability-input","method":"POST","operationId":"actions.update-contact-email.availability","path":"/v1/actions/update-contact-email/availability","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-availability-response"},"invoke":{"inputSchema":"action-update-contact-email-invoke-input","method":"POST","operationId":"actions.update-contact-email.invoke","path":"/v1/actions/update-contact-email","requiresIdempotencyKey":true,"responseSchema":"action-update-contact-email-invoke-response"},"targetConditions":{"inputSchema":"action-update-contact-email-target-conditions-input","method":"POST","operationId":"actions.update-contact-email.target-conditions","path":"/v1/actions/update-contact-email/target-conditions","requiresIdempotencyKey":false,"responseSchema":"action-update-contact-email-target-conditions-response"}}},"x-registry-defaultAccessProfile":"directory-editor","x-registry-operation":"invoke","x-registry-routeKind":"target-conditions"}},"/v1/proposals":{"get":{"operationId":"proposals.list","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"query","name":"action","schema":{"type":"string"}},{"in":"query","name":"owner","schema":{"const":"caller"}},{"in":"query","name":"target","schema":{"format":"uuid","type":"string"}},{"in":"query","name":"state","schema":{"enum":["draft","submitted","applied","cancelled","rejected"]}},{"in":"query","name":"turn","schema":{"enum":["party","official","nobody"]}},{"in":"query","name":"cursor","schema":{"type":"string"}},{"description":"The most items a page holds. A page may hold fewer than `limit` items, so keep paging while `nextCursor` is present.","in":"query","name":"limit","schema":{"default":50,"maximum":100,"minimum":1,"type":"integer"}},{"in":"query","name":"pendingManualApplication","schema":{"default":false,"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"maxItems":100,"type":"array"},"nextCursor":{"type":"string"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["query.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}":{"get":{"operationId":"proposals.get","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/cancel":{"post":{"operationId":"proposals.cancel","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/edit":{"post":{"operationId":"proposals.edit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:register-contact:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-contact","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/submissions/{submission_version}":{"get":{"operationId":"proposals.get-submission","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"path","name":"submission_version","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"application":{"anyOf":[{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"state":{"const":"applied"}},"required":["state","applicationId"],"type":"object"},{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},{"type":"null"}]},"current":{"type":"boolean"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"review":{"anyOf":[{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},{"type":"null"}]},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["id","actionId","submissionVersion","current","effectDigest","review","application"],"type":"object"}}},"description":"Authorized Proposal operation"},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"proposal.submission_expired":{"value":{"code":"proposal.submission_expired","detail":"The review result and application receipt of the submission are no longer retained.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/submission_expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["proposal.submission_expired"]}},"type":"object"}]}}},"description":"The submission's review result and application receipt are no longer retained","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/proposals/{proposal_id}/submit":{"post":{"operationId":"proposals.submit","parameters":[{"in":"query","name":"accessProfile","required":true,"schema":{"enum":["directory-editor"],"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not_found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard_failed` when the selected profile can read it","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media_type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["directory-editor"]}},"/v1/records/contacts":{"get":{"operationId":"records.contact.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"$top","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"$skiptoken","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"query.cursor_invalid":{"value":{"code":"query.cursor_invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor_invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"directory-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"directory-editor","selectableProperties":["email","jurisdiction","name"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.contact.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/contact-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"create","x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/contacts/{record_id}":{"get":{"operationId":"records.contact.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"get","x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.contact.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. Required when the route has no default; otherwise omission uses its default.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/contact"},"recordIdentifier":{"format":"uuid","type":"string"},"revisionIdentifier":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordIdentifier","revisionIdentifier","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetIdentifier":{"const":"directory"},"recordTypeIdentifier":{"const":"contact"},"registryIdentifier":{"const":"local-directory"}},"required":["registryIdentifier","datasetIdentifier","recordTypeIdentifier"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not_found":{"value":{"code":"resource.not_found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not_found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media_type":{"value":{"code":"unsupported.media_type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media_type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"patch","x-registry-recordType":"contact","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"contact","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/review-completions":{"post":{"description":"Available when a review authority configures a completion block.","operationId":"receiveReviewCompletion","parameters":[{"in":"header","name":"Registry-Recipient-Binding","required":true,"schema":{"maxLength":256,"minLength":1,"type":"string"}},{"description":"Must equal eventId.","in":"header","name":"webhook-id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"webhook-timestamp","required":true,"schema":{"pattern":"^(0|[1-9][0-9]{0,19})$","type":"string"}},{"in":"header","name":"webhook-signature","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewCompletion"}}},"required":true},"responses":{"204":{"description":"Completion accepted or already recorded."},"400":{"description":"The completion is invalid or eventId differs from webhook-id."},"401":{"description":"The completion authority could not be authenticated.","headers":{"WWW-Authenticate":{"schema":{"const":"Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"","type":"string"}}}},"413":{"description":"The completion body exceeds 2048 bytes. The response body is empty."},"415":{"description":"The request is not application/json."},"503":{"description":"The completion could not be durably recorded."}},"security":[{"reviewCompletion":[]}],"summary":"Receive a Casework review completion"}}}} \ No newline at end of file diff --git a/products/breg/generated/minimal/generated/sdk/project.py b/products/breg/generated/minimal/generated/sdk/project.py index 2671d44bf2..8b970fe270 100644 --- a/products/breg/generated/minimal/generated/sdk/project.py +++ b/products/breg/generated/minimal/generated/sdk/project.py @@ -4,7 +4,7 @@ from dataclasses import dataclass -EngineReason = Literal['pending-review', 'review-rejected', 'review-changes-requested', 'review-ended', 'stale-revision', 'package-changed', 'dependency-outage', 'invalid-input', 'already-applied'] +EngineReason = Literal['pending-review', 'review-rejected', 'review-changes-requested', 'review-ended', 'stale-revision', 'package-changed', 'dependency-outage', 'invalid-input', 'already-applied', 'limit-reached', 'application-pending', 'attachment-required', 'attachment-pending', 'ask-answered', 'ask-closed', 'ask-due-passed'] RecoveryHint = Literal['refresh', 'revise', 'retry', 'rebase', 'correct-input', 'receipt-only'] class Availability(TypedDict): available: bool diff --git a/products/breg/generated/minimal/generated/sdk/project.ts b/products/breg/generated/minimal/generated/sdk/project.ts index d60f5a0a97..05f8023b2f 100644 --- a/products/breg/generated/minimal/generated/sdk/project.ts +++ b/products/breg/generated/minimal/generated/sdk/project.ts @@ -1,7 +1,7 @@ // Generated by BReg. Edit the project, then regenerate. import type { breg } from '@registrystack/client'; -export type EngineReason = 'pending-review' | 'review-rejected' | 'review-changes-requested' | 'review-ended' | 'stale-revision' | 'package-changed' | 'dependency-outage' | 'invalid-input' | 'already-applied'; +export type EngineReason = 'pending-review' | 'review-rejected' | 'review-changes-requested' | 'review-ended' | 'stale-revision' | 'package-changed' | 'dependency-outage' | 'invalid-input' | 'already-applied' | 'limit-reached' | 'application-pending' | 'attachment-required' | 'attachment-pending' | 'ask-answered' | 'ask-closed' | 'ask-due-passed'; export type RecoveryHint = 'refresh' | 'revise' | 'retry' | 'rebase' | 'correct-input' | 'receipt-only'; export type Availability = | { readonly available: true; readonly observedRevision: number } diff --git a/products/breg/scripts/test_validate_product.py b/products/breg/scripts/test_validate_product.py index 987bfc2df8..379eef4695 100644 --- a/products/breg/scripts/test_validate_product.py +++ b/products/breg/scripts/test_validate_product.py @@ -64,7 +64,7 @@ def test_every_pre_w5_security_invariant_is_enforced_with_an_executable_negative self.assertIn("path", invariant["negativeTest"]) self.assertIn("name", invariant["negativeTest"]) - def test_security_range_is_closed_through_derived_sql_invariants(self) -> None: + def test_security_range_is_closed_through_proposal_ask_invariants(self) -> None: matrix = VALIDATOR.load_yaml( VALIDATOR.CONTRACTS / "security-invariant-matrix.yaml" ) @@ -74,7 +74,7 @@ def test_security_range_is_closed_through_derived_sql_invariants(self) -> None: ) extension_rows = matrix["invariants"][24:] self.assertEqual( - [f"BREG-NEG-{index:02d}" for index in range(25, 225) if index not in {61, 62}], + [f"BREG-NEG-{index:02d}" for index in range(25, 244) if index not in {61, 62}], [invariant["negativeId"] for invariant in extension_rows], ) for invariant in extension_rows: diff --git a/products/breg/scripts/validate_product.py b/products/breg/scripts/validate_product.py index adec946934..7f47b29939 100644 --- a/products/breg/scripts/validate_product.py +++ b/products/breg/scripts/validate_product.py @@ -31,7 +31,7 @@ CONTRACT_STATES = {"enforced", "partial", "planned"} V1_REQUIREMENT_IDS = tuple(f"BREG-V1-{index:02d}" for index in range(1, 45)) ACCEPTANCE_JOURNEY_IDS = tuple(f"BREG-J{index:02d}" for index in range(1, 25)) -SECURITY_INVARIANT_IDS = tuple(f"BREG-SEC-{index:02d}" for index in range(1, 225) if index not in {61, 62}) +SECURITY_INVARIANT_IDS = tuple(f"BREG-SEC-{index:02d}" for index in range(1, 244) if index not in {61, 62}) ACCEPTANCE_FIXTURES = { "BREG-J01": ("asset-site-placement", "acceptance/asset-site-placement"), "BREG-J02": ("asset-site-placement", "acceptance/asset-site-placement"), diff --git a/products/casework/CHANGELOG.md b/products/casework/CHANGELOG.md index 476f2a2ea4..1632956ef8 100644 --- a/products/casework/CHANGELOG.md +++ b/products/casework/CHANGELOG.md @@ -2,6 +2,49 @@ ## Unreleased +- Fix a pre-existing application/database clock mismatch that could delay + immediately due review completion deliveries when the host clock ran ahead. + +- Resubmission considers only the latest matching round and records only + `stageId` in its resume history, without a link to the earlier request. +- Clock recomputation preserves accumulated ask pauses. Pausing requires + `answerWithin` on the same stage. +- An older ask's answer preserves a newer ask's waiting marker. Closing + preserves already expired asks. Task contexts expose each ask's `dueAt`. + +- Stages can set `asks.answerWithin` and `asks.onDue: return-to-reviewer`. + Casework expires overdue asks and marks their tasks `expired`. Answers are + judged by `answeredAt`, including on-time answers delivered after expiry. +- Stages can set `asks.pauseClocks: true`. Clocks read as `paused` until the + ask is answered, expires, or closes. Pending instants move by the wall-clock + pause duration for both elapsed-time and working-day clocks. History and + audit record pause and resume. +- Policies can set `resubmission: resume-at-returning-stage`. New requests + start at the latest returning stage for the same producer, subject, and + policy, using the settling decision within result retention, with fresh + clocks and no carried approvals. Later resubmissions start at the first + stage. Omission keeps the + first-stage default and the policy digest. Earlier-round reviewers, up to and + including the returning stage, stay excluded from the stages above the one + they decided where a stage sets `excludePreviousStageReviewers`, also after + the earlier request is erased. A later round erased first stops an older + round from resuming. Resumption also needs the same stage ids, in the same + order, up to and including the returning stage. + +- A reviewer who holds a task can ask the applicant. A stage opts in with + `asks: {}` (approval policies only), and a producer declares + `readsAsks: true`. `POST /v1/review-tasks/{task_id}/asks` opens the ask. The + producer reads `GET /v1/review-asks` and + `GET /v1/review-requests/{request_id}/asks/{ask_id}`, and reports the answer + with `POST /v1/review-requests/{request_id}/asks/{ask_id}/answer`, which + carries no text. Tasks carry a `marker` (`waiting` or `answered`), the task + context lists the request's `asks`, and `GET /v1/review-tasks` takes a + `marker` filter. A migration adds the ask tables and the task marker. New + problem codes: `review.ask-already-open`, `review.ask-answer-time-invalid`, + `review.ask-not-offered`, `review.ask-not-open`, + `review.ask-producer-unsupported` and `review.ask-task-inactive`. A policy + without `asks` keeps its bytes and digest. + - BREAKING: review completion wakes use Standard Webhooks. Casework signs `webhook-id`, `webhook-timestamp` and the exact JSON bytes with HMAC-SHA-256. `webhook-id` is the `eventId` and stays the same on every diff --git a/products/casework/README.md b/products/casework/README.md index 9f71055f32..b5325bca19 100644 --- a/products/casework/README.md +++ b/products/casework/README.md @@ -155,8 +155,14 @@ outcome whose settlement is `approved` (`answered` for an answer policy). `caseworkctl explain` always reports the effective outcomes for each stage, including the all-policy default. A `changes-requested` result ends that review version. A resubmission is a new -version that starts at the policy's first stage; it does not resume the earlier -review in place. +request at the first stage by default. With +`resubmission: resume-at-returning-stage`, Casework starts at the stage that +returned the same producer's latest round for that subject and policy, only if +that round settled changes-requested. A later approved, rejected, cancelled or +still-open round starts at the first stage. Casework reads the stage of the settling decision. Casework resumes +within the earlier request's result retention, and starts later resubmissions +at the first stage. A removed stage also falls back to the first stage. Earlier approvals +are not carried over, and the subject clock starts fresh. The same producer reads `GET /v1/review-requests/{requestId}/result` or its resumable result feed. A `ReviewResult` repeats the subject, policy, and diff --git a/products/casework/contracts/cli/report.schema.json b/products/casework/contracts/cli/report.schema.json index cfacbf04ea..a153800dfb 100644 --- a/products/casework/contracts/cli/report.schema.json +++ b/products/casework/contracts/cli/report.schema.json @@ -911,6 +911,9 @@ "ExplainStage": { "additionalProperties": false, "properties": { + "asks": { + "type": "boolean" + }, "decidingProfiles": { "items": { "type": "string" @@ -1747,6 +1750,11 @@ "profile": { "type": "string" }, + "readsAsks": { + "default": false, + "description": "Whether this producer reads reviewer asks through the ask feed and\nanswers them. A review policy whose stage declares `asks` needs it\non every producer that submits to the policy.", + "type": "boolean" + }, "retention": { "$ref": "#/$defs/ProducerRetention" }, diff --git a/products/casework/contracts/security-invariant-matrix.yaml b/products/casework/contracts/security-invariant-matrix.yaml index 6bbfd83897..5ce46957f9 100644 --- a/products/casework/contracts/security-invariant-matrix.yaml +++ b/products/casework/contracts/security-invariant-matrix.yaml @@ -43,3 +43,12 @@ invariants: - {id: CASEWORK-SEC-37, invariants: [1, 3, 9, 14], state: enforced, targetWave: beta, threat: "A separate source bearer substitutes another human or leaks through inbox filtering or retained recovery.", enforcementPoint: "Independent provider-bound cryptographic same-human authentication before output, explicit source profile and invocation-local source credential.", refusal: "Refuse invalid or ambiguous pairs before source I/O; BReg still owns source client/profile admission.", negativeId: CASEWORK-NEG-37, negativeTest: {path: crates/registry-casework/tests/review_http.rs, name: separate_human_source_credentials_bind_before_empty_inbox_and_guard_mutations}} - {id: CASEWORK-SEC-38, invariants: [9, 17], state: enforced, targetWave: beta, threat: "The operator metrics listener becomes a second disclosure channel: a reachable address, a socket shared with the API listener, or a sampled value carrying record content lets a reader learn review state or record values without authentication.", enforcementPoint: "Metrics are absent unless the runtime file configures metricsListener. The bind is read through the shared platform rule: public, link-local, multicast and IPv4-mapped addresses and port 0 are refused, the unspecified address is permitted only under metricsListener.networkExposure container-private, and a bind that shares the API listener's socket, wildcard included, is refused. The listener has no authentication, so it must stay on a private network. Sampled series carry counts and ages only, never record content.", refusal: "Refuse the runtime file with casework.runtime.invalid-metrics-listener, never echoing the configured address. Serve no metrics route on the API listener.", negativeId: CASEWORK-NEG-38, negativeTest: {path: crates/registry-casework/src/config.rs, name: metrics_listener_wildcard_needs_container_private_exposure}} - {id: CASEWORK-SEC-39, invariants: [7, 8], state: enforced, targetWave: beta, threat: "A forged completion wake is accepted or a substituted recipient binding selects the same signing key.", enforcementPoint: "Standard Webhooks verification over the exact request bytes and distinct current and previous signing keys across completion destinations.", refusal: "Refuse unauthenticated wakes at the receiver and refuse completion destinations that share signing key bytes.", negativeId: CASEWORK-NEG-39, negativeTest: {path: crates/registry-casework/src/runtime.rs, name: completion_destinations_cannot_share_a_current_or_previous_signing_key}} + - {id: CASEWORK-SEC-40, invariants: [3, 9, 17], state: enforced, targetWave: beta, threat: "A producer answers another producer's ask, replays or reopens an ask, carries applicant text to Casework, or backdates the answer.", enforcementPoint: "The answer call loads the request under the calling producer's identity, requires the request's own subject binding, and locks the request and ask. Only open asks or expired asks with an on-time answeredAt become answered. The body type admits a subject and an answer time and no other member. The answer time must lie between the ask time and a short skew ahead of Casework's clock.", refusal: "Answer an unknown, another producer's or mismatched ask with an empty 404, an answered or closed ask with review.ask-not-open, a time outside the window with review.ask-answer-time-invalid, and an extra member with 422. Replay the stored response for the same idempotency key.", negativeId: CASEWORK-NEG-40, negativeTest: {path: crates/registry-casework/tests/review_postgres.rs, name: the_producer_answer_marks_the_task_answered_and_obeys_its_rules}} + - {id: CASEWORK-SEC-41, invariants: [3, 9, 17], state: enforced, targetWave: beta, threat: "A reviewer asks the applicant without holding the task, from a stage or producer that does not offer asks, or leaves ask text beyond the review's retention.", enforcementPoint: "The ask command runs in one transaction under the task revision: the caller must hold the task at the active stage of a reviewing request, the stage must declare asks, the producer must read asks, and no ask may be open. The history row and audit record carry the ask id and never its text, and the ask rows and feed events are erased with the request's history.", refusal: "Refuse a caller who does not hold the task with review.task-not-held, a stale revision with precondition-failed, and each other missing condition with its own review.ask-* problem.", negativeId: CASEWORK-NEG-41, negativeTest: {path: crates/registry-casework/tests/review_postgres.rs, name: an_ask_is_refused_unless_every_condition_holds}} + - {id: CASEWORK-SEC-42, invariants: [3, 9, 17], state: enforced, targetWave: beta, threat: "Delivery lag or the clock runner's ordering admits an answer given after the ask deadline, or rejects an on-time answer.", enforcementPoint: "The producer answer transaction compares answeredAt with the stored absolute dueAt under the same request lock as expiry. An expired ask can become answered only at or before dueAt while its task and request remain active. Closing preserves expired state and time.", refusal: "Return 409 review.ask-not-open for answeredAt after dueAt or an inactive task or request without changing the ask, task revision, history or feed.", negativeId: CASEWORK-NEG-42, negativeTest: {path: crates/registry-casework/tests/review_postgres.rs, name: c2_a_late_answer_is_refused_before_the_expiry_runner_runs}} + - {id: CASEWORK-SEC-43, invariants: [9, 17], state: enforced, targetWave: beta, threat: "An ask without a due date pauses all request clocks indefinitely.", enforcementPoint: "Review policy validation requires answerWithin wherever pauseClocks is true.", refusal: "Refuse the policy with casework.review-policy.ask-pause-requires-answer-within at the stage's asks/answerWithin pointer.", negativeId: CASEWORK-NEG-43, negativeTest: {path: crates/registry-casework-core/src/review.rs, name: pausing_asks_require_a_due_date}} + - {id: CASEWORK-SEC-44, invariants: [1, 3, 17, 18], state: enforced, targetWave: beta, threat: "A reviewer who decided a stage of an earlier round decides a later stage of the resumed round, or the exclusion lapses when the earlier round is erased.", enforcementPoint: "A request that resumes at the returning stage stores each earlier-round reviewer up to and including that stage with the stage index they decided, carried into later rounds. Decision, claim, assignment and absence-cover eligibility, the staffing shortfall and advisory accountability reads exclude them from every stage above that index that sets excludePreviousStageReviewers. A later round erased first stops an older round from resuming.", refusal: "Refuse the claim, assignment or decision with the separation-of-duties check, report insufficient-distinct-approvers when only excluded staff remain, and withhold advisory accountability.", negativeId: CASEWORK-NEG-44, negativeTest: {path: crates/registry-casework/tests/review_postgres.rs, name: c2_sod2_returning_stage_reviewers_stay_out_of_later_stages_across_rounds}} + - {id: CASEWORK-SEC-45, invariants: [1, 18], state: enforced, targetWave: beta, threat: "A policy relies on every stage seeing the final content, but a resubmission resumed at the returning stage carries content the earlier stages never reviewed, so one later stage decides changed content alone.", enforcementPoint: "A resubmission starts at the first stage unless the policy opts in with resubmission: resume-at-returning-stage. With that option the resumed request opens tasks only from the returning stage on, and the documentation states that earlier stages do not see content the resubmission changed, so a two-person control that needs every stage to see the final content must keep the first-stage default.", refusal: "Start the resubmission at the first stage by default; with the option, open no task for a stage below the returning stage.", negativeId: CASEWORK-NEG-45, negativeTest: {path: crates/registry-casework/tests/review_postgres.rs, name: c2_resubmission_resumes_at_the_returning_stage_with_a_fresh_clock}} + - {id: CASEWORK-SEC-46, invariants: [1, 3, 18], state: enforced, targetWave: beta, threat: "A delegated institutional caller receives questions, source answers or task markers, or an inbox hydrates applicant answer content.", enforcementPoint: "Delegated context projection strips asks and markers. Inbox hydration omits intrinsic answers and clears any source answer map.", refusal: "Return no asks, answers or markers to delegated reads; normal inboxes retain their permitted marker but no question or answer content.", negativeId: CASEWORK-NEG-46, negativeTest: {path: crates/registry-casework/tests/review_http.rs, name: delegated_institutional_reads_carry_neither_asks_nor_markers}} + - {id: CASEWORK-SEC-47, invariants: [1, 3, 18], state: enforced, targetWave: beta, threat: "A producer reads another producer ask feed or observes a cursor order that can skip a concurrent ask.", enforcementPoint: "Feed selection is scoped to the authenticated producer and ask creation serializes under its producer feed lock.", refusal: "Conceal other producers asks and wait for the feed lock before publishing ordered events.", negativeId: CASEWORK-NEG-47, negativeTest: {path: crates/registry-casework/tests/review_postgres.rs, name: the_holder_asks_the_applicant_and_the_producer_reads_the_ask}} + - {id: CASEWORK-SEC-48, invariants: [1, 3, 18], state: enforced, targetWave: beta, threat: "Preflight claim, ask or decide source reads request live answers intended only for display.", enforcementPoint: "Neutral human display request opts into source answers only for actual task context display; BReg provider preserves that option under the same human bearer.", refusal: "Preflight omits include=answers; actual display opts in without changing human authentication.", negativeId: CASEWORK-NEG-48, negativeTest: {path: crates/registry-casework/tests/support/source_ask_answers.rs, name: source_answers_join_known_asks_live_without_entering_the_display_schema_or_store}} diff --git a/products/casework/contracts/security-test-traceability.yaml b/products/casework/contracts/security-test-traceability.yaml index f2cbdfface..6380ebce96 100644 --- a/products/casework/contracts/security-test-traceability.yaml +++ b/products/casework/contracts/security-test-traceability.yaml @@ -41,3 +41,12 @@ entries: - {id: CASEWORK-SEC-37, tests: [{file: crates/registry-casework/src/auth.rs, name: separate_human_source_pair_uses_raw_subject_and_independent_source_client}, {file: crates/registry-casework/tests/review_http.rs, name: separate_human_source_credentials_bind_before_empty_inbox_and_guard_mutations}, {file: crates/registry-casework/src/http/source_credentials.rs, name: verified_provider_handles_do_not_forward_casework_or_mix_invocations}, {file: crates/registry-casework-client/tests/http_boundary.rs, name: separate_human_source_credential_is_explicit_per_call_and_never_retained}]} - {id: CASEWORK-SEC-38, tests: [{file: crates/registry-casework/src/config.rs, name: metrics_listener_wildcard_needs_container_private_exposure}, {file: crates/registry-casework/src/config.rs, name: a_deferred_listener_bind_defers_only_the_metrics_socket_comparison}, {file: crates/registry-casework/src/runtime.rs, name: the_metrics_listener_serves_beside_the_api_and_stops_with_it}, {file: crates/registry-casework/src/metrics.rs, name: the_scrape_is_byte_stable}, {file: crates/registry-platform-config/src/metrics_bind.rs, name: each_refused_class_names_its_rule}, {file: crates/registry-platform-config/src/metrics_bind.rs, name: ipv4_mapped_forms_of_refused_addresses_are_refused}, {file: crates/registry-platform-config/src/metrics_bind.rs, name: container_private_permits_the_unspecified_address}, {file: crates/registry-platform-config/src/metrics_bind.rs, name: private_address_refuses_the_unspecified_address}, {file: crates/registry-platform-config/src/metrics_bind.rs, name: a_wildcard_serving_bind_on_the_same_port_overlaps}]} - {id: CASEWORK-SEC-39, tests: [{file: crates/registry-casework/src/runtime.rs, name: review_completion_signs_the_exact_bytes_it_sends}, {file: crates/registry-casework/src/runtime.rs, name: completion_destinations_cannot_share_a_current_or_previous_signing_key}]} + - {id: CASEWORK-SEC-40, tests: [{file: crates/registry-casework/tests/review_postgres.rs, name: the_producer_answer_marks_the_task_answered_and_obeys_its_rules}, {file: crates/registry-casework/tests/review_http.rs, name: the_ask_command_and_the_producer_ask_routes_follow_the_contract_over_http}]} + - {id: CASEWORK-SEC-41, tests: [{file: crates/registry-casework/tests/review_postgres.rs, name: an_ask_is_refused_unless_every_condition_holds}, {file: crates/registry-casework/tests/review_postgres.rs, name: an_ask_needs_a_stage_that_offers_it_and_a_producer_that_reads_it}, {file: crates/registry-casework/tests/review_postgres.rs, name: ask_rows_and_events_leave_with_the_expired_review}]} + - {id: CASEWORK-SEC-42, tests: [{file: crates/registry-casework/tests/review_postgres.rs, name: c2_a_late_answer_is_refused_before_the_expiry_runner_runs}, {file: crates/registry-casework/tests/review_postgres.rs, name: c2_ask_due_date_is_absolute_and_delivery_lag_does_not_make_an_answer_late}, {file: crates/registry-casework/tests/review_postgres.rs, name: c2_expiry_and_an_on_time_answer_can_race_without_losing_the_answer}, {file: crates/registry-casework/tests/review_postgres.rs, name: c2_expiry_and_close_resume_clocks_and_a_closed_expired_ask_cannot_be_answered}]} + - {id: CASEWORK-SEC-43, tests: [{file: crates/registry-casework-core/src/review.rs, name: pausing_asks_require_a_due_date}]} + - {id: CASEWORK-SEC-44, tests: [{file: crates/registry-casework/tests/review_postgres.rs, name: c2_sod2_returning_stage_reviewers_stay_out_of_later_stages_across_rounds}, {file: crates/registry-casework/tests/review_postgres.rs, name: c2_sod_resumed_round_keeps_earlier_stage_reviewers_out_of_the_returning_stage}, {file: crates/registry-casework/tests/review_postgres.rs, name: c2_sod2_staffing_shortfall_counts_earlier_round_reviewers_out}, {file: crates/registry-casework/tests/review_postgres.rs, name: c2_sod2_advisory_reasons_stay_hidden_from_earlier_round_reviewers}, {file: crates/registry-casework/tests/review_postgres.rs, name: c2_sod2_an_erased_later_round_stops_an_older_round_resuming}, {file: crates/registry-casework-core/src/review.rs, name: a_resumed_request_excludes_reviewers_of_the_earlier_rounds_prior_stages}]} + - {id: CASEWORK-SEC-45, tests: [{file: crates/registry-casework/tests/review_postgres.rs, name: c2_resubmission_resumes_at_the_returning_stage_with_a_fresh_clock}, {file: crates/registry-casework/tests/review_postgres.rs, name: c2_fix_latest_approved_round_starts_at_first_stage}]} + - {id: CASEWORK-SEC-46, tests: [{file: crates/registry-casework/tests/review_http.rs, name: delegated_institutional_reads_carry_neither_asks_nor_markers}, {file: crates/registry-casework/src/review/source_answers.rs, name: delegated_reads_discard_questions_and_source_answers}, {file: crates/registry-casework/tests/support/source_ask_answers.rs, name: source_answers_join_known_asks_live_without_entering_the_display_schema_or_store}]} + - {id: CASEWORK-SEC-47, tests: [{file: crates/registry-casework/tests/review_postgres.rs, name: the_holder_asks_the_applicant_and_the_producer_reads_the_ask}, {file: crates/registry-casework/tests/review_postgres.rs, name: an_ask_event_waits_for_the_producers_feed_lock}]} + - {id: CASEWORK-SEC-48, tests: [{file: crates/registry-casework/tests/support/source_ask_answers.rs, name: source_answers_join_known_asks_live_without_entering_the_display_schema_or_store}, {file: crates/registry-casework-breg/tests/context_provider.rs, name: preflight_omits_answers_and_only_display_opts_in_under_the_same_human_bearer}]} diff --git a/products/casework/generated/project/project.schema.json b/products/casework/generated/project/project.schema.json index e820e4ee58..1495c9143c 100644 --- a/products/casework/generated/project/project.schema.json +++ b/products/casework/generated/project/project.schema.json @@ -247,6 +247,12 @@ ], "type": "object" }, + "ReviewAskOnDue": { + "enum": [ + "return-to-reviewer" + ], + "type": "string" + }, "ReviewCompletionDestinationPolicy": { "additionalProperties": false, "properties": { @@ -379,6 +385,13 @@ ], "type": "string" }, + "ReviewResubmissionPolicy": { + "enum": [ + "first-stage", + "resume-at-returning-stage" + ], + "type": "string" + }, "ReviewRetentionPolicy": { "additionalProperties": false, "properties": { @@ -401,9 +414,48 @@ ], "type": "object" }, + "ReviewStageAsksPolicy": { + "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { + "pauseClocks": { + "const": true + } + }, + "required": [ + "pauseClocks" + ] + }, + "then": { + "required": [ + "answerWithin" + ] + } + } + ], + "description": "`asks: {}` offers an ask without a deadline or clock pause.", + "properties": { + "answerWithin": { + "$ref": "#/$defs/ElapsedDuration" + }, + "onDue": { + "$ref": "#/$defs/ReviewAskOnDue" + }, + "pauseClocks": { + "type": "boolean" + } + }, + "type": "object" + }, "ReviewStagePolicy": { "additionalProperties": false, "properties": { + "asks": { + "$ref": "#/$defs/ReviewStageAsksPolicy", + "description": "Lets the reviewer who holds a task at this stage ask the subject's\nowner for more. Omission offers no ask and keeps the policy bytes\nunchanged. Only an approval policy may declare it." + }, "decidingProfiles": { "items": { "type": "string" @@ -1070,6 +1122,9 @@ "purpose": { "$ref": "#/$defs/ReviewPurpose" }, + "resubmission": { + "$ref": "#/$defs/ReviewResubmissionPolicy" + }, "resultSchema": { "x-registry-foreign": "json-schema-2020-12" }, @@ -1319,6 +1374,11 @@ "profile": { "type": "string" }, + "readsAsks": { + "default": false, + "description": "Whether this producer reads reviewer asks through the ask feed and\nanswers them. A review policy whose stage declares `asks` needs it\non every producer that submits to the policy.", + "type": "boolean" + }, "retention": { "$ref": "#/$defs/ProducerRetention" }, diff --git a/products/casework/generated/registry-casework.openapi.json b/products/casework/generated/registry-casework.openapi.json index 9445320943..4dce1d71d3 100644 --- a/products/casework/generated/registry-casework.openapi.json +++ b/products/casework/generated/registry-casework.openapi.json @@ -1253,6 +1253,37 @@ ], "type": "object" }, + "InputReviewAskWant": { + "description": "What a reviewer's ask requests from the subject's owner.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "kind": { + "const": "answer", + "type": "string" + } + }, + "required": [ + "kind" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "const": "document", + "type": "string" + } + }, + "required": [ + "kind" + ], + "type": "object" + } + ] + }, "InputReviewContext": { "oneOf": [ { @@ -1308,6 +1339,15 @@ ], "type": "string" }, + "InputReviewTaskMarker": { + "description": "What an ask of the applicant means for the task that made it.", + "enum": [ + "waiting", + "answered", + "expired" + ], + "type": "string" + }, "InputReviewTaskOwnership": { "description": "Select active review tasks by their current holder. Selection never grants\nreviewer eligibility or source authority.", "enum": [ @@ -2085,6 +2125,188 @@ } ] }, + "ProblemReviewAskAlreadyOpen": { + "allOf": [ + { + "$ref": "#/components/schemas/Problem" + }, + { + "properties": { + "code": { + "const": "review.ask-already-open" + }, + "detail": { + "const": "Wait for the open ask on this request to be answered or closed before asking again." + }, + "status": { + "const": 409 + }, + "title": { + "const": "Review ask already open" + }, + "type": { + "const": "https://id.registrystack.org/problems/registry-casework/review/ask-already-open" + } + } + } + ] + }, + "ProblemReviewAskAnswerTimeInvalid": { + "allOf": [ + { + "$ref": "#/components/schemas/Problem" + }, + { + "properties": { + "code": { + "const": "review.ask-answer-time-invalid" + }, + "detail": { + "const": "Report the time the applicant's answer was committed: not before the ask was made and no more than five minutes ahead of Casework's clock." + }, + "status": { + "const": 422 + }, + "title": { + "const": "Review ask answer time invalid" + }, + "type": { + "const": "https://id.registrystack.org/problems/registry-casework/review/ask-answer-time-invalid" + } + } + } + ] + }, + "ProblemReviewAskLimitReached": { + "allOf": [ + { + "$ref": "#/components/schemas/Problem" + }, + { + "properties": { + "code": { + "const": "review.ask-limit-reached" + }, + "detail": { + "const": "This review request has reached its limit of 50 asks. Continue the review without opening another ask." + }, + "status": { + "const": 409 + }, + "title": { + "const": "Review ask limit reached" + }, + "type": { + "const": "https://id.registrystack.org/problems/registry-casework/review/ask-limit-reached" + } + } + } + ] + }, + "ProblemReviewAskNotOffered": { + "allOf": [ + { + "$ref": "#/components/schemas/Problem" + }, + { + "properties": { + "code": { + "const": "review.ask-not-offered" + }, + "detail": { + "const": "The active stage of this review policy does not let a reviewer ask the applicant." + }, + "status": { + "const": 409 + }, + "title": { + "const": "Review ask not offered" + }, + "type": { + "const": "https://id.registrystack.org/problems/registry-casework/review/ask-not-offered" + } + } + } + ] + }, + "ProblemReviewAskNotOpen": { + "allOf": [ + { + "$ref": "#/components/schemas/Problem" + }, + { + "properties": { + "code": { + "const": "review.ask-not-open" + }, + "detail": { + "const": "This ask was already answered or closed, or the applicant answered after its due date." + }, + "status": { + "const": 409 + }, + "title": { + "const": "Review ask not open" + }, + "type": { + "const": "https://id.registrystack.org/problems/registry-casework/review/ask-not-open" + } + } + } + ] + }, + "ProblemReviewAskProducerUnsupported": { + "allOf": [ + { + "$ref": "#/components/schemas/Problem" + }, + { + "properties": { + "code": { + "const": "review.ask-producer-unsupported" + }, + "detail": { + "const": "The producer of this request does not read asks, so the reviewer cannot ask the applicant." + }, + "status": { + "const": 409 + }, + "title": { + "const": "Review ask producer unsupported" + }, + "type": { + "const": "https://id.registrystack.org/problems/registry-casework/review/ask-producer-unsupported" + } + } + } + ] + }, + "ProblemReviewAskTaskInactive": { + "allOf": [ + { + "$ref": "#/components/schemas/Problem" + }, + { + "properties": { + "code": { + "const": "review.ask-task-inactive" + }, + "detail": { + "const": "Ask from a task at the active stage of a request that is still under review." + }, + "status": { + "const": 409 + }, + "title": { + "const": "Review ask task inactive" + }, + "type": { + "const": "https://id.registrystack.org/problems/registry-casework/review/ask-task-inactive" + } + } + } + ] + }, "ProblemReviewDistinctApproverRequired": { "allOf": [ { @@ -2611,79 +2833,331 @@ ], "type": "object" }, - "ReviewCancelRequest": { + "ReviewAnswerDocument": { "additionalProperties": false, "properties": { - "reason": { + "byteSize": { + "format": "uint64", + "minimum": 0, + "type": "integer" + }, + "contentType": { "type": "string" }, - "subject": { - "$ref": "#/components/schemas/InputSubjectBinding" + "download": { + "anyOf": [ + { + "$ref": "#/components/schemas/ReviewAnswerDownload" + }, + { + "type": "null" + } + ] + }, + "id": { + "type": "string" + }, + "sha256": { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + "verificationStatus": { + "type": [ + "string", + "null" + ] } }, "required": [ - "subject", - "reason" + "id", + "sha256", + "contentType", + "byteSize" ], "type": "object" }, - "ReviewCancelResponse": { - "oneOf": [ - { - "additionalProperties": false, - "properties": { - "outcome": { - "const": "cancelled", - "type": "string" - }, - "result": { - "$ref": "#/components/schemas/ReviewResult" - } - }, - "required": [ - "outcome", - "result" - ], - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "outcome": { - "const": "already-terminal", - "type": "string" - }, - "result": { - "$ref": "#/components/schemas/ReviewResult" - } - }, - "required": [ - "outcome", - "result" - ], - "type": "object" - } - ] - }, - "ReviewCaseloadApplyRequest": { + "ReviewAnswerDownload": { "additionalProperties": false, "properties": { - "previewId": { - "format": "uuid", + "accessProfile": { + "type": "string" + }, + "method": { + "pattern": "^GET$", + "type": "string" + }, + "operation": { + "type": "string" + }, + "path": { "type": "string" } }, "required": [ - "previewId" + "method", + "operation", + "accessProfile", + "path" ], "type": "object" }, - "ReviewCaseloadMoveRequest": { + "ReviewAsk": { "additionalProperties": false, + "description": "A reviewer's request for more from the subject's owner. The provider owns\nthe ask; the producer reads it and reports only that it was answered.", "properties": { - "from": { - "$ref": "#/components/schemas/InputIssuerPrincipal" - }, + "answeredAt": { + "format": "date-time", + "type": [ + "string", + "null" + ] + }, + "askId": { + "format": "uuid", + "type": "string" + }, + "askedAt": { + "format": "date-time", + "type": "string" + }, + "closedAt": { + "format": "date-time", + "type": [ + "string", + "null" + ] + }, + "dueAt": { + "format": "date-time", + "type": [ + "string", + "null" + ] + }, + "requestId": { + "format": "uuid", + "type": "string" + }, + "state": { + "$ref": "#/components/schemas/ReviewAskState" + }, + "subject": { + "$ref": "#/components/schemas/SubjectBinding" + }, + "text": { + "maxLength": 2000, + "minLength": 1, + "type": "string", + "x-maximum-utf8-bytes": 2000 + }, + "wants": { + "items": { + "$ref": "#/components/schemas/ReviewAskWant" + }, + "maxItems": 8, + "type": "array", + "uniqueItems": true + } + }, + "required": [ + "askId", + "requestId", + "subject", + "text", + "wants", + "askedAt", + "state" + ], + "type": "object" + }, + "ReviewAskAnswer": { + "additionalProperties": false, + "description": "The producer's report that the subject's owner answered an ask. It carries\nthe subject binding and the time the answer was committed, so it cannot\ncarry the answer itself. The provider judges the answer by that time, at\nmicrosecond precision.", + "properties": { + "answeredAt": { + "format": "date-time", + "type": "string" + }, + "subject": { + "$ref": "#/components/schemas/InputSubjectBinding" + } + }, + "required": [ + "subject", + "answeredAt" + ], + "type": "object" + }, + "ReviewAskFeedEntry": { + "additionalProperties": false, + "description": "Announces that an ask was opened, answered, expired or closed. The\nproducer reads the ask next.", + "properties": { + "askId": { + "format": "uuid", + "type": "string" + }, + "changedAt": { + "format": "date-time", + "type": "string" + }, + "eventId": { + "format": "uuid", + "type": "string" + }, + "requestId": { + "format": "uuid", + "type": "string" + } + }, + "required": [ + "eventId", + "requestId", + "askId", + "changedAt" + ], + "type": "object" + }, + "ReviewAskFeedPage": { + "additionalProperties": false, + "properties": { + "items": { + "items": { + "$ref": "#/components/schemas/ReviewAskFeedEntry" + }, + "type": "array" + }, + "nextCursor": { + "format": "uuid", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "items" + ], + "type": "object" + }, + "ReviewAskOnDue": { + "enum": [ + "return-to-reviewer" + ], + "type": "string" + }, + "ReviewAskState": { + "enum": [ + "open", + "answered", + "expired", + "closed" + ], + "type": "string" + }, + "ReviewAskWant": { + "description": "What a reviewer's ask requests from the subject's owner.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "kind": { + "const": "answer", + "type": "string" + } + }, + "required": [ + "kind" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "const": "document", + "type": "string" + } + }, + "required": [ + "kind" + ], + "type": "object" + } + ] + }, + "ReviewCancelRequest": { + "additionalProperties": false, + "properties": { + "reason": { + "type": "string" + }, + "subject": { + "$ref": "#/components/schemas/InputSubjectBinding" + } + }, + "required": [ + "subject", + "reason" + ], + "type": "object" + }, + "ReviewCancelResponse": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "outcome": { + "const": "cancelled", + "type": "string" + }, + "result": { + "$ref": "#/components/schemas/ReviewResult" + } + }, + "required": [ + "outcome", + "result" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "outcome": { + "const": "already-terminal", + "type": "string" + }, + "result": { + "$ref": "#/components/schemas/ReviewResult" + } + }, + "required": [ + "outcome", + "result" + ], + "type": "object" + } + ] + }, + "ReviewCaseloadApplyRequest": { + "additionalProperties": false, + "properties": { + "previewId": { + "format": "uuid", + "type": "string" + } + }, + "required": [ + "previewId" + ], + "type": "object" + }, + "ReviewCaseloadMoveRequest": { + "additionalProperties": false, + "properties": { + "from": { + "$ref": "#/components/schemas/InputIssuerPrincipal" + }, "queue": { "type": [ "string", @@ -2988,6 +3462,7 @@ "ReviewClockState": { "enum": [ "running", + "paused", "completed", "cancelled", "source-facts-missing" @@ -3048,46 +3523,140 @@ ], "type": "string" }, - "ReviewContextCapability": { - "enum": [ - "human-display", - "service-status", - "task-grant-context", - "routing-context" - ], - "type": "string" - }, - "ReviewContextContract": { + "ReviewContextAnswer": { "additionalProperties": false, "properties": { - "id": { - "$ref": "#/components/schemas/ExternalId", - "description": "The producer-issued contract id, kept exactly as written: nonblank, no control characters, and at most 256 UTF-8 bytes. The byte ceiling is enforced by the Casework reader.", - "maxLength": 256, - "pattern": "\\S", - "x-registry-maxBytes": 256 + "answeredAt": { + "format": "date-time", + "type": "string" }, - "revision": { - "$ref": "#/components/schemas/ContentDigest" + "documents": { + "items": { + "$ref": "#/components/schemas/ReviewAnswerDocument" + }, + "maxItems": 32, + "type": "array" }, - "schemaDigest": { - "$ref": "#/components/schemas/Digest" + "text": { + "maxLength": 2000, + "type": [ + "string", + "null" + ], + "x-maximum-utf8-bytes": 2000 } }, "required": [ - "id", - "revision", - "schemaDigest" + "documents", + "answeredAt" ], "type": "object" }, - "ReviewContextPolicy": { - "oneOf": [ - { - "additionalProperties": false, - "properties": { - "mode": { - "const": "submitted", + "ReviewContextAsk": { + "additionalProperties": false, + "description": "An ask as a reviewer reads it in the task context.", + "properties": { + "answer": { + "anyOf": [ + { + "$ref": "#/components/schemas/ReviewContextAnswer" + }, + { + "type": "null" + } + ], + "description": "Live source content. Casework retains only its own answer notification time." + }, + "answeredAt": { + "format": "date-time", + "type": [ + "string", + "null" + ] + }, + "askId": { + "format": "uuid", + "type": "string" + }, + "askedAt": { + "format": "date-time", + "type": "string" + }, + "dueAt": { + "format": "date-time", + "type": [ + "string", + "null" + ] + }, + "state": { + "$ref": "#/components/schemas/ReviewAskState" + }, + "taskId": { + "description": "The task that asked.", + "format": "uuid", + "type": "string" + }, + "text": { + "type": "string" + }, + "wants": { + "items": { + "$ref": "#/components/schemas/ReviewAskWant" + }, + "type": "array" + } + }, + "required": [ + "askId", + "taskId", + "text", + "wants", + "askedAt", + "state" + ], + "type": "object" + }, + "ReviewContextCapability": { + "enum": [ + "human-display", + "service-status", + "task-grant-context", + "routing-context" + ], + "type": "string" + }, + "ReviewContextContract": { + "additionalProperties": false, + "properties": { + "id": { + "$ref": "#/components/schemas/ExternalId", + "description": "The producer-issued contract id, kept exactly as written: nonblank, no control characters, and at most 256 UTF-8 bytes. The byte ceiling is enforced by the Casework reader.", + "maxLength": 256, + "pattern": "\\S", + "x-registry-maxBytes": 256 + }, + "revision": { + "$ref": "#/components/schemas/ContentDigest" + }, + "schemaDigest": { + "$ref": "#/components/schemas/Digest" + } + }, + "required": [ + "id", + "revision", + "schemaDigest" + ], + "type": "object" + }, + "ReviewContextPolicy": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "mode": { + "const": "submitted", "type": "string" } }, @@ -3434,6 +4003,9 @@ "purpose": { "$ref": "#/components/schemas/ReviewPurpose" }, + "resubmission": { + "$ref": "#/components/schemas/ReviewResubmissionPolicy" + }, "resultSchema": { "x-registry-foreign": "json-schema-2020-12" }, @@ -3501,6 +4073,9 @@ "purpose": { "$ref": "#/components/schemas/ReviewPurpose" }, + "resubmission": { + "$ref": "#/components/schemas/ReviewResubmissionPolicy" + }, "resultSchema": true, "retention": { "$ref": "#/components/schemas/ReviewRetentionPolicy" @@ -3657,6 +4232,11 @@ "profile": { "type": "string" }, + "readsAsks": { + "default": false, + "description": "Whether this producer reads reviewer asks through the ask feed and\nanswers them. A review policy whose stage declares `asks` needs it\non every producer that submits to the policy.", + "type": "boolean" + }, "retention": { "$ref": "#/components/schemas/ProducerRetention" }, @@ -3824,6 +4404,13 @@ ], "type": "object" }, + "ReviewResubmissionPolicy": { + "enum": [ + "first-stage", + "resume-at-returning-stage" + ], + "type": "string" + }, "ReviewResult": { "additionalProperties": false, "properties": { @@ -4022,6 +4609,17 @@ "null" ] }, + "marker": { + "anyOf": [ + { + "$ref": "#/components/schemas/InputReviewTaskMarker" + }, + { + "type": "null" + } + ], + "description": "Lists tasks by their ask marker: waiting, answered, or expired." + }, "ownership": { "anyOf": [ { @@ -4085,9 +4683,62 @@ }, "type": "object" }, + "ReviewStageAsksPolicy": { + "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { + "pauseClocks": { + "const": true + } + }, + "required": [ + "pauseClocks" + ] + }, + "then": { + "required": [ + "answerWithin" + ] + } + } + ], + "description": "`asks: {}` offers an ask without a deadline or clock pause.", + "properties": { + "answerWithin": { + "anyOf": [ + { + "$ref": "#/components/schemas/ElapsedDuration" + }, + { + "type": "null" + } + ] + }, + "onDue": { + "$ref": "#/components/schemas/ReviewAskOnDue" + }, + "pauseClocks": { + "type": "boolean" + } + }, + "type": "object" + }, "ReviewStagePolicy": { "additionalProperties": false, "properties": { + "asks": { + "anyOf": [ + { + "$ref": "#/components/schemas/ReviewStageAsksPolicy" + }, + { + "type": "null" + } + ], + "description": "Lets the reviewer who holds a task at this stage ask the subject's\nowner for more. Omission offers no ask and keeps the policy bytes\nunchanged. Only an approval policy may declare it." + }, "decidingProfiles": { "items": { "type": "string" @@ -4208,6 +4859,17 @@ }, "type": "array" }, + "marker": { + "anyOf": [ + { + "$ref": "#/components/schemas/ReviewTaskMarker" + }, + { + "type": "null" + } + ], + "description": "An ask is waiting for the applicant, answered, or expired. The marker stays with the task\nthrough release and reassignment and clears when the task is decided." + }, "queue": { "type": "string" }, @@ -4262,9 +4924,57 @@ ], "type": "object" }, + "ReviewTaskAskRequest": { + "additionalProperties": false, + "description": "A reviewer's ask of the applicant, sent by the task holder.", + "properties": { + "text": { + "maxLength": 2000, + "minLength": 1, + "type": "string", + "x-maximum-utf8-bytes": 2000 + }, + "wants": { + "items": { + "$ref": "#/components/schemas/InputReviewAskWant" + }, + "maxItems": 8, + "type": "array" + } + }, + "required": [ + "text", + "wants" + ], + "type": "object" + }, + "ReviewTaskAsked": { + "additionalProperties": false, + "description": "The ask a holder opened and the task as it now stands.", + "properties": { + "ask": { + "$ref": "#/components/schemas/ReviewAsk" + }, + "task": { + "$ref": "#/components/schemas/ReviewTask" + } + }, + "required": [ + "task", + "ask" + ], + "type": "object" + }, "ReviewTaskContext": { "additionalProperties": false, "properties": { + "asks": { + "description": "The asks of the applicant on this request, oldest first.", + "items": { + "$ref": "#/components/schemas/ReviewContextAsk" + }, + "type": "array" + }, "context": { "$ref": "#/components/schemas/ReviewTaskContextData" }, @@ -4402,6 +5112,15 @@ ], "type": "object" }, + "ReviewTaskMarker": { + "description": "What an ask of the applicant means for the task that made it.", + "enum": [ + "waiting", + "answered", + "expired" + ], + "type": "string" + }, "ReviewTaskPage": { "additionalProperties": false, "properties": { @@ -12129,9 +12848,9 @@ "summary": "Get review accountability" } }, - "/v1/review-policies": { + "/v1/review-asks": { "get": { - "operationId": "listReviewPolicies", + "operationId": "listReviewAsks", "parameters": [ { "description": "", @@ -12145,7 +12864,7 @@ { "description": "The caller's exact governed access profile for this protocol.", "in": "header", - "name": "registry-casework-profile", + "name": "registry-review-profile", "required": true, "schema": { "maxLength": 128, @@ -12154,6 +12873,27 @@ "type": "string", "x-maximum-utf8-bytes": 128 } + }, + { + "description": "", + "in": "query", + "name": "cursor", + "required": false, + "schema": { + "format": "uuid", + "type": "string" + } + }, + { + "description": "", + "in": "query", + "name": "limit", + "required": false, + "schema": { + "maximum": 100, + "minimum": 1, + "type": "integer" + } } ], "responses": { @@ -12161,7 +12901,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ReviewPolicyClosureList" + "$ref": "#/components/schemas/ReviewAskFeedPage" } } }, @@ -12397,12 +13137,12 @@ "bearerAuth": [] } ], - "summary": "List review policies" + "summary": "List review asks" } }, - "/v1/review-policies/{policy_id}": { + "/v1/review-policies": { "get": { - "operationId": "getReviewPolicy", + "operationId": "listReviewPolicies", "parameters": [ { "description": "", @@ -12425,19 +13165,6 @@ "type": "string", "x-maximum-utf8-bytes": 128 } - }, - { - "description": "", - "in": "path", - "name": "policy_id", - "required": true, - "schema": { - "maxLength": 128, - "minLength": 1, - "pattern": "^[A-Za-z0-9._:-]+$", - "type": "string", - "x-maximum-utf8-bytes": 128 - } } ], "responses": { @@ -12445,7 +13172,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ReviewPolicyClosure" + "$ref": "#/components/schemas/ReviewPolicyClosureList" } } }, @@ -12681,13 +13408,12 @@ "bearerAuth": [] } ], - "summary": "Get review policy" + "summary": "List review policies" } }, - "/v1/review-requests": { - "post": { - "description": "Recovery repeats the exact request and caller-supplied idempotency key. Clients do not retry mutations implicitly.", - "operationId": "createOrRecoverReviewRequest", + "/v1/review-policies/{policy_id}": { + "get": { + "operationId": "getReviewPolicy", "parameters": [ { "description": "", @@ -12701,7 +13427,7 @@ { "description": "The caller's exact governed access profile for this protocol.", "in": "header", - "name": "registry-review-profile", + "name": "registry-casework-profile", "required": true, "schema": { "maxLength": 128, @@ -12712,72 +13438,30 @@ } }, { - "description": "Retain this exact key and request bytes for explicit recovery.", - "in": "header", - "name": "Idempotency-Key", + "description": "", + "in": "path", + "name": "policy_id", "required": true, "schema": { "maxLength": 128, "minLength": 1, - "pattern": "^[!-~]+$", - "type": "string" + "pattern": "^[A-Za-z0-9._:-]+$", + "type": "string", + "x-maximum-utf8-bytes": 128 } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ReviewCreateRequest" - } - } - }, - "required": true - }, "responses": { "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ReviewRequestAccepted" - } - } - }, - "description": "Success", - "headers": { - "Registry-Review-Producer": { - "description": "Authenticated trusted producer identity for this acceptance or exact recovery. Optional for compatibility with older providers; never a substitute for the submission digest.", - "schema": { - "maxLength": 128, - "minLength": 1, - "pattern": "^[A-Za-z0-9_.:-]+$", - "type": "string" - } - }, - "traceparent": { - "$ref": "#/components/headers/TraceparentHeader" - } - } - }, - "201": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ReviewRequestAccepted" + "$ref": "#/components/schemas/ReviewPolicyClosure" } } }, "description": "Success", "headers": { - "Registry-Review-Producer": { - "description": "Authenticated trusted producer identity for this acceptance or exact recovery. Optional for compatibility with older providers; never a substitute for the submission digest.", - "schema": { - "maxLength": 128, - "minLength": 1, - "pattern": "^[A-Za-z0-9_.:-]+$", - "type": "string" - } - }, "traceparent": { "$ref": "#/components/headers/TraceparentHeader" } @@ -12788,9 +13472,15 @@ "application/problem+json": { "schema": { "oneOf": [ + { + "$ref": "#/components/schemas/ProblemCursorInvalid" + }, { "$ref": "#/components/schemas/ProblemRequestInvalid" }, + { + "$ref": "#/components/schemas/ProblemRequestLimitOutOfRange" + }, { "$ref": "#/components/schemas/ProblemSourceProfileNotApplicable" }, @@ -12801,21 +13491,8 @@ } } }, - "description": "Problem: request.invalid, source-profile.not-applicable, source-profile.required", + "description": "Problem: cursor.invalid, request.invalid, request.limit-out-of-range, source-profile.not-applicable, source-profile.required", "headers": { - "Registry-Review-Validation-Path": { - "description": "Bounded value-free JSON path; present together with the validation reason.", - "schema": { - "maxLength": 256, - "type": "string" - } - }, - "Registry-Review-Validation-Reason": { - "description": "Closed value-free validation category; present together with the validation path.", - "schema": { - "$ref": "#/components/schemas/ReviewValidationReason" - } - }, "traceparent": { "$ref": "#/components/headers/TraceparentHeader" } @@ -12854,18 +13531,12 @@ }, { "$ref": "#/components/schemas/ProblemProfileNotHuman" - }, - { - "$ref": "#/components/schemas/ProblemReviewDistinctApproverRequired" - }, - { - "$ref": "#/components/schemas/ProblemReviewInitiatorExcluded" } ] } } }, - "description": "Problem: operation.not-authorized, profile.not-authorized, profile.not-human, review.distinct-approver-required, review.initiator-excluded", + "description": "Problem: operation.not-authorized, profile.not-authorized, profile.not-human", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -12887,41 +13558,13 @@ } } }, - "409": { - "content": { - "application/problem+json": { - "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/ProblemIdempotencyKeyReused" - }, - { - "$ref": "#/components/schemas/ProblemReviewPolicyMismatch" - }, - { - "$ref": "#/components/schemas/ProblemReviewSubmissionConflict" - }, - { - "$ref": "#/components/schemas/ProblemReviewTaskNotHeld" - } - ] - } - } - }, - "description": "Problem: idempotency.key-reused, review.policy-mismatch, review.submission-conflict, review.task-not-held", - "headers": { - "traceparent": { - "$ref": "#/components/headers/TraceparentHeader" - } - } - }, "410": { "content": { "application/problem+json": { "schema": { "oneOf": [ { - "$ref": "#/components/schemas/ProblemIdempotencyExpired" + "$ref": "#/components/schemas/ProblemCursorExpired" }, { "$ref": "#/components/schemas/ProblemReviewResultExpired" @@ -12930,22 +13573,7 @@ } } }, - "description": "Problem: idempotency.expired, review.result-expired", - "headers": { - "traceparent": { - "$ref": "#/components/headers/TraceparentHeader" - } - } - }, - "412": { - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/ProblemPreconditionFailed" - } - } - }, - "description": "Problem: precondition.failed", + "description": "Problem: cursor.expired, review.result-expired", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -12986,58 +13614,11 @@ "content": { "application/problem+json": { "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/ProblemAbsenceCoverCycle" - }, - { - "$ref": "#/components/schemas/ProblemAbsenceInvalidPeriod" - }, - { - "$ref": "#/components/schemas/ProblemAbsenceOverlap" - }, - { - "$ref": "#/components/schemas/ProblemAbsenceSelfCover" - }, - { - "$ref": "#/components/schemas/ProblemRequestUnprocessable" - }, - { - "$ref": "#/components/schemas/ProblemReviewInitiatorRequired" - } - ] - } - } - }, - "description": "Problem: absence.cover-cycle, absence.invalid-period, absence.overlap, absence.self-cover, request.unprocessable, review.initiator-required", - "headers": { - "Registry-Review-Validation-Path": { - "description": "Bounded value-free JSON path of the member the request type refused; present together with the validation reason.", - "schema": { - "maxLength": 256, - "type": "string" - } - }, - "Registry-Review-Validation-Reason": { - "description": "Closed value-free validation category, always schema-mismatch for a request shape refusal; present together with the validation path.", - "schema": { - "$ref": "#/components/schemas/ReviewValidationReason" - } - }, - "traceparent": { - "$ref": "#/components/headers/TraceparentHeader" - } - } - }, - "428": { - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/ProblemPreconditionRequired" + "$ref": "#/components/schemas/ProblemRequestUnprocessable" } } }, - "description": "Problem: precondition.required", + "description": "Problem: request.unprocessable", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -13111,12 +13692,13 @@ "bearerAuth": [] } ], - "summary": "Create or recover review request" + "summary": "Get review policy" } }, - "/v1/review-requests/{request_id}": { - "get": { - "operationId": "getReviewRequest", + "/v1/review-requests": { + "post": { + "description": "Recovery repeats the exact request and caller-supplied idempotency key. Clients do not retry mutations implicitly.", + "operationId": "createOrRecoverReviewRequest", "parameters": [ { "description": "", @@ -13141,43 +13723,72 @@ } }, { - "description": "", - "in": "path", - "name": "request_id", + "description": "Retain this exact key and request bytes for explicit recovery.", + "in": "header", + "name": "Idempotency-Key", "required": true, "schema": { - "format": "uuid", + "maxLength": 128, + "minLength": 1, + "pattern": "^[!-~]+$", "type": "string" } - }, - { - "description": "", - "in": "query", - "name": "include", - "required": false, - "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/InputReviewRequestInclude" - }, - { - "type": "null" - } - ] - } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReviewCreateRequest" + } + } + }, + "required": true + }, "responses": { "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ReviewRequestView" + "$ref": "#/components/schemas/ReviewRequestAccepted" + } + } + }, + "description": "Success", + "headers": { + "Registry-Review-Producer": { + "description": "Authenticated trusted producer identity for this acceptance or exact recovery. Optional for compatibility with older providers; never a substitute for the submission digest.", + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9_.:-]+$", + "type": "string" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReviewRequestAccepted" } } }, "description": "Success", "headers": { + "Registry-Review-Producer": { + "description": "Authenticated trusted producer identity for this acceptance or exact recovery. Optional for compatibility with older providers; never a substitute for the submission digest.", + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9_.:-]+$", + "type": "string" + } + }, "traceparent": { "$ref": "#/components/headers/TraceparentHeader" } @@ -13188,17 +13799,11 @@ "application/problem+json": { "schema": { "oneOf": [ - { - "$ref": "#/components/schemas/ProblemCursorInvalid" - }, { "$ref": "#/components/schemas/ProblemRequestInvalid" }, { - "$ref": "#/components/schemas/ProblemRequestLimitOutOfRange" - }, - { - "$ref": "#/components/schemas/ProblemSourceProfileNotApplicable" + "$ref": "#/components/schemas/ProblemSourceProfileNotApplicable" }, { "$ref": "#/components/schemas/ProblemSourceProfileRequired" @@ -13207,8 +13812,21 @@ } } }, - "description": "Problem: cursor.invalid, request.invalid, request.limit-out-of-range, source-profile.not-applicable, source-profile.required", + "description": "Problem: request.invalid, source-profile.not-applicable, source-profile.required", "headers": { + "Registry-Review-Validation-Path": { + "description": "Bounded value-free JSON path; present together with the validation reason.", + "schema": { + "maxLength": 256, + "type": "string" + } + }, + "Registry-Review-Validation-Reason": { + "description": "Closed value-free validation category; present together with the validation path.", + "schema": { + "$ref": "#/components/schemas/ReviewValidationReason" + } + }, "traceparent": { "$ref": "#/components/headers/TraceparentHeader" } @@ -13247,12 +13865,18 @@ }, { "$ref": "#/components/schemas/ProblemProfileNotHuman" + }, + { + "$ref": "#/components/schemas/ProblemReviewDistinctApproverRequired" + }, + { + "$ref": "#/components/schemas/ProblemReviewInitiatorExcluded" } ] } } }, - "description": "Problem: operation.not-authorized, profile.not-authorized, profile.not-human", + "description": "Problem: operation.not-authorized, profile.not-authorized, profile.not-human, review.distinct-approver-required, review.initiator-excluded", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -13274,13 +13898,41 @@ } } }, + "409": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemIdempotencyKeyReused" + }, + { + "$ref": "#/components/schemas/ProblemReviewPolicyMismatch" + }, + { + "$ref": "#/components/schemas/ProblemReviewSubmissionConflict" + }, + { + "$ref": "#/components/schemas/ProblemReviewTaskNotHeld" + } + ] + } + } + }, + "description": "Problem: idempotency.key-reused, review.policy-mismatch, review.submission-conflict, review.task-not-held", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, "410": { "content": { "application/problem+json": { "schema": { "oneOf": [ { - "$ref": "#/components/schemas/ProblemCursorExpired" + "$ref": "#/components/schemas/ProblemIdempotencyExpired" }, { "$ref": "#/components/schemas/ProblemReviewResultExpired" @@ -13289,7 +13941,22 @@ } } }, - "description": "Problem: cursor.expired, review.result-expired", + "description": "Problem: idempotency.expired, review.result-expired", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "412": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemPreconditionFailed" + } + } + }, + "description": "Problem: precondition.failed", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -13330,11 +13997,58 @@ "content": { "application/problem+json": { "schema": { - "$ref": "#/components/schemas/ProblemRequestUnprocessable" + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemAbsenceCoverCycle" + }, + { + "$ref": "#/components/schemas/ProblemAbsenceInvalidPeriod" + }, + { + "$ref": "#/components/schemas/ProblemAbsenceOverlap" + }, + { + "$ref": "#/components/schemas/ProblemAbsenceSelfCover" + }, + { + "$ref": "#/components/schemas/ProblemRequestUnprocessable" + }, + { + "$ref": "#/components/schemas/ProblemReviewInitiatorRequired" + } + ] } } }, - "description": "Problem: request.unprocessable", + "description": "Problem: absence.cover-cycle, absence.invalid-period, absence.overlap, absence.self-cover, request.unprocessable, review.initiator-required", + "headers": { + "Registry-Review-Validation-Path": { + "description": "Bounded value-free JSON path of the member the request type refused; present together with the validation reason.", + "schema": { + "maxLength": 256, + "type": "string" + } + }, + "Registry-Review-Validation-Reason": { + "description": "Closed value-free validation category, always schema-mismatch for a request shape refusal; present together with the validation path.", + "schema": { + "$ref": "#/components/schemas/ReviewValidationReason" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "428": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemPreconditionRequired" + } + } + }, + "description": "Problem: precondition.required", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -13408,13 +14122,12 @@ "bearerAuth": [] } ], - "summary": "Get review request" + "summary": "Create or recover review request" } }, - "/v1/review-requests/{request_id}/cancel": { - "post": { - "description": "Recovery repeats the exact request and caller-supplied idempotency key. Clients do not retry mutations implicitly.", - "operationId": "cancelReviewRequest", + "/v1/review-requests/{request_id}": { + "get": { + "operationId": "getReviewRequest", "parameters": [ { "description": "", @@ -13449,34 +14162,28 @@ } }, { - "description": "Retain this exact key and request bytes for explicit recovery.", - "in": "header", - "name": "Idempotency-Key", - "required": true, + "description": "", + "in": "query", + "name": "include", + "required": false, "schema": { - "maxLength": 128, - "minLength": 1, - "pattern": "^[!-~]+$", - "type": "string" + "anyOf": [ + { + "$ref": "#/components/schemas/InputReviewRequestInclude" + }, + { + "type": "null" + } + ] } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ReviewCancelRequest" - } - } - }, - "required": true - }, "responses": { "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ReviewCancelResponse" + "$ref": "#/components/schemas/ReviewRequestView" } } }, @@ -13492,9 +14199,15 @@ "application/problem+json": { "schema": { "oneOf": [ + { + "$ref": "#/components/schemas/ProblemCursorInvalid" + }, { "$ref": "#/components/schemas/ProblemRequestInvalid" }, + { + "$ref": "#/components/schemas/ProblemRequestLimitOutOfRange" + }, { "$ref": "#/components/schemas/ProblemSourceProfileNotApplicable" }, @@ -13505,7 +14218,7 @@ } } }, - "description": "Problem: request.invalid, source-profile.not-applicable, source-profile.required", + "description": "Problem: cursor.invalid, request.invalid, request.limit-out-of-range, source-profile.not-applicable, source-profile.required", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -13545,18 +14258,12 @@ }, { "$ref": "#/components/schemas/ProblemProfileNotHuman" - }, - { - "$ref": "#/components/schemas/ProblemReviewDistinctApproverRequired" - }, - { - "$ref": "#/components/schemas/ProblemReviewInitiatorExcluded" } ] } } }, - "description": "Problem: operation.not-authorized, profile.not-authorized, profile.not-human, review.distinct-approver-required, review.initiator-excluded", + "description": "Problem: operation.not-authorized, profile.not-authorized, profile.not-human", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -13578,206 +14285,116 @@ } } }, - "409": { + "410": { "content": { "application/problem+json": { "schema": { "oneOf": [ { - "$ref": "#/components/schemas/ProblemIdempotencyKeyReused" - }, - { - "$ref": "#/components/schemas/ProblemReviewPolicyMismatch" - }, - { - "$ref": "#/components/schemas/ProblemReviewSubmissionConflict" + "$ref": "#/components/schemas/ProblemCursorExpired" }, { - "$ref": "#/components/schemas/ProblemReviewTaskNotHeld" + "$ref": "#/components/schemas/ProblemReviewResultExpired" } ] } } }, - "description": "Problem: idempotency.key-reused, review.policy-mismatch, review.submission-conflict, review.task-not-held", + "description": "Problem: cursor.expired, review.result-expired", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" } } }, - "410": { + "413": { "content": { "application/problem+json": { "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/ProblemIdempotencyExpired" - }, - { - "$ref": "#/components/schemas/ProblemReviewResultExpired" - } - ] + "$ref": "#/components/schemas/ProblemRequestBodyTooLarge" } } }, - "description": "Problem: idempotency.expired, review.result-expired", + "description": "Problem: request.body-too-large", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" } } }, - "412": { + "415": { "content": { "application/problem+json": { "schema": { - "$ref": "#/components/schemas/ProblemPreconditionFailed" + "$ref": "#/components/schemas/ProblemRequestUnsupportedMediaType" } } }, - "description": "Problem: precondition.failed", + "description": "Problem: request.unsupported-media-type", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" } } }, - "413": { + "422": { "content": { "application/problem+json": { "schema": { - "$ref": "#/components/schemas/ProblemRequestBodyTooLarge" + "$ref": "#/components/schemas/ProblemRequestUnprocessable" } } }, - "description": "Problem: request.body-too-large", + "description": "Problem: request.unprocessable", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" } } }, - "415": { + "500": { "content": { "application/problem+json": { "schema": { - "$ref": "#/components/schemas/ProblemRequestUnsupportedMediaType" + "$ref": "#/components/schemas/ProblemRuntimeFailure" } } }, - "description": "Problem: request.unsupported-media-type", + "description": "Problem: runtime.failure", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" } } }, - "422": { + "502": { "content": { "application/problem+json": { "schema": { "oneOf": [ { - "$ref": "#/components/schemas/ProblemAbsenceCoverCycle" - }, - { - "$ref": "#/components/schemas/ProblemAbsenceInvalidPeriod" - }, - { - "$ref": "#/components/schemas/ProblemAbsenceOverlap" - }, - { - "$ref": "#/components/schemas/ProblemAbsenceSelfCover" + "$ref": "#/components/schemas/ProblemSourceBadGateway" }, { - "$ref": "#/components/schemas/ProblemRequestUnprocessable" + "$ref": "#/components/schemas/ProblemSourceVersionMismatch" }, { - "$ref": "#/components/schemas/ProblemReviewInitiatorRequired" + "$ref": "#/components/schemas/ProblemSourceVersionUnavailable" } ] } } }, - "description": "Problem: absence.cover-cycle, absence.invalid-period, absence.overlap, absence.self-cover, request.unprocessable, review.initiator-required", + "description": "Problem: source.bad-gateway, source.version-mismatch, source.version-unavailable", "headers": { - "Registry-Review-Validation-Path": { - "description": "Bounded value-free JSON path of the member the request type refused; present together with the validation reason.", - "schema": { - "maxLength": 256, - "type": "string" - } - }, - "Registry-Review-Validation-Reason": { - "description": "Closed value-free validation category, always schema-mismatch for a request shape refusal; present together with the validation path.", - "schema": { - "$ref": "#/components/schemas/ReviewValidationReason" - } - }, - "traceparent": { - "$ref": "#/components/headers/TraceparentHeader" - } - } - }, - "428": { - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/ProblemPreconditionRequired" - } - } - }, - "description": "Problem: precondition.required", - "headers": { - "traceparent": { - "$ref": "#/components/headers/TraceparentHeader" - } - } - }, - "500": { - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/ProblemRuntimeFailure" - } - } - }, - "description": "Problem: runtime.failure", - "headers": { - "traceparent": { - "$ref": "#/components/headers/TraceparentHeader" - } - } - }, - "502": { - "content": { - "application/problem+json": { - "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/ProblemSourceBadGateway" - }, - { - "$ref": "#/components/schemas/ProblemSourceVersionMismatch" - }, - { - "$ref": "#/components/schemas/ProblemSourceVersionUnavailable" - } - ] - } - } - }, - "description": "Problem: source.bad-gateway, source.version-mismatch, source.version-unavailable", - "headers": { - "traceparent": { - "$ref": "#/components/headers/TraceparentHeader" - } - } - }, - "503": { - "content": { - "application/problem+json": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "503": { + "content": { + "application/problem+json": { "schema": { "$ref": "#/components/schemas/ProblemServiceUnavailable" } @@ -13802,12 +14419,12 @@ "bearerAuth": [] } ], - "summary": "Cancel review request" + "summary": "Get review request" } }, - "/v1/review-requests/{request_id}/clocks": { + "/v1/review-requests/{request_id}/asks/{ask_id}": { "get": { - "operationId": "getReviewClocks", + "operationId": "getReviewAsk", "parameters": [ { "description": "", @@ -13821,7 +14438,7 @@ { "description": "The caller's exact governed access profile for this protocol.", "in": "header", - "name": "registry-casework-profile", + "name": "registry-review-profile", "required": true, "schema": { "maxLength": 128, @@ -13832,34 +14449,19 @@ } }, { - "description": "Current-source lists, open work, source context, task mutations and new notes require the human caller's source-valid profile and credential. Retained terminal task and history reads use Casework authority. Submitted context requires no provider.", - "in": "header", - "name": "registry-source-profile", - "required": false, - "schema": { - "maxLength": 128, - "minLength": 1, - "pattern": "^[A-Za-z0-9._:-]+$", - "type": "string", - "x-maximum-utf8-bytes": 128 - } - }, - { - "description": "Optional separate human source bearer. Requires explicit source profile and provider-bound configuration; both credentials must independently verify as the same direct human. Never persisted or used as Casework authority; absent preserves legacy single-bearer forwarding.", - "in": "header", - "name": "registry-source-authorization", - "required": false, + "description": "", + "in": "path", + "name": "request_id", + "required": true, "schema": { - "maxLength": 131079, - "minLength": 1, - "type": "string", - "writeOnly": true + "format": "uuid", + "type": "string" } }, { "description": "", "in": "path", - "name": "request_id", + "name": "ask_id", "required": true, "schema": { "format": "uuid", @@ -13872,7 +14474,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ReviewClockOccurrenceList" + "$ref": "#/components/schemas/ReviewAsk" } } }, @@ -13960,14 +14562,7 @@ } }, "404": { - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/ProblemRequestNotFound" - } - } - }, - "description": "Problem: request.not-found", + "description": "Success", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -14108,12 +14703,13 @@ "bearerAuth": [] } ], - "summary": "Get review clocks" + "summary": "Get review ask" } }, - "/v1/review-requests/{request_id}/history": { - "get": { - "operationId": "getReviewHistory", + "/v1/review-requests/{request_id}/asks/{ask_id}/answer": { + "post": { + "description": "Recovery repeats the exact request and caller-supplied idempotency key. Clients do not retry mutations implicitly.", + "operationId": "answerReviewAsk", "parameters": [ { "description": "", @@ -14127,7 +14723,7 @@ { "description": "The caller's exact governed access profile for this protocol.", "in": "header", - "name": "registry-casework-profile", + "name": "registry-review-profile", "required": true, "schema": { "maxLength": 128, @@ -14137,31 +14733,6 @@ "x-maximum-utf8-bytes": 128 } }, - { - "description": "Current-source lists, open work, source context, task mutations and new notes require the human caller's source-valid profile and credential. Retained terminal task and history reads use Casework authority. Submitted context requires no provider.", - "in": "header", - "name": "registry-source-profile", - "required": false, - "schema": { - "maxLength": 128, - "minLength": 1, - "pattern": "^[A-Za-z0-9._:-]+$", - "type": "string", - "x-maximum-utf8-bytes": 128 - } - }, - { - "description": "Optional separate human source bearer. Requires explicit source profile and provider-bound configuration; both credentials must independently verify as the same direct human. Never persisted or used as Casework authority; absent preserves legacy single-bearer forwarding.", - "in": "header", - "name": "registry-source-authorization", - "required": false, - "schema": { - "maxLength": 131079, - "minLength": 1, - "type": "string", - "writeOnly": true - } - }, { "description": "", "in": "path", @@ -14174,32 +14745,43 @@ }, { "description": "", - "in": "query", - "name": "cursor", - "required": false, + "in": "path", + "name": "ask_id", + "required": true, "schema": { "format": "uuid", "type": "string" } }, { - "description": "", - "in": "query", - "name": "limit", - "required": false, + "description": "Retain this exact key and request bytes for explicit recovery.", + "in": "header", + "name": "Idempotency-Key", + "required": true, "schema": { - "maximum": 100, - "minimum": 1, - "type": "integer" + "maxLength": 128, + "minLength": 1, + "pattern": "^[!-~]+$", + "type": "string" } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReviewAskAnswer" + } + } + }, + "required": true + }, "responses": { "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ReviewHistoryPage" + "$ref": "#/components/schemas/ReviewAsk" } } }, @@ -14214,27 +14796,11 @@ "content": { "application/problem+json": { "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/ProblemCursorInvalid" - }, - { - "$ref": "#/components/schemas/ProblemRequestInvalid" - }, - { - "$ref": "#/components/schemas/ProblemRequestLimitOutOfRange" - }, - { - "$ref": "#/components/schemas/ProblemSourceProfileNotApplicable" - }, - { - "$ref": "#/components/schemas/ProblemSourceProfileRequired" - } - ] + "$ref": "#/components/schemas/ProblemRequestInvalid" } } }, - "description": "Problem: cursor.invalid, request.invalid, request.limit-out-of-range, source-profile.not-applicable, source-profile.required", + "description": "Problem: request.invalid", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -14271,15 +14837,12 @@ }, { "$ref": "#/components/schemas/ProblemProfileNotAuthorized" - }, - { - "$ref": "#/components/schemas/ProblemProfileNotHuman" } ] } } }, - "description": "Problem: operation.not-authorized, profile.not-authorized, profile.not-human", + "description": "Problem: operation.not-authorized, profile.not-authorized", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -14287,14 +14850,29 @@ } }, "404": { + "description": "Success", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "409": { "content": { "application/problem+json": { "schema": { - "$ref": "#/components/schemas/ProblemRequestNotFound" + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemIdempotencyKeyReused" + }, + { + "$ref": "#/components/schemas/ProblemReviewAskNotOpen" + } + ] } } }, - "description": "Problem: request.not-found", + "description": "Problem: idempotency.key-reused, review.ask-not-open", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -14305,18 +14883,11 @@ "content": { "application/problem+json": { "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/ProblemCursorExpired" - }, - { - "$ref": "#/components/schemas/ProblemReviewResultExpired" - } - ] + "$ref": "#/components/schemas/ProblemIdempotencyExpired" } } }, - "description": "Problem: cursor.expired, review.result-expired", + "description": "Problem: idempotency.expired", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -14357,12 +14928,32 @@ "content": { "application/problem+json": { "schema": { - "$ref": "#/components/schemas/ProblemRequestUnprocessable" + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemRequestUnprocessable" + }, + { + "$ref": "#/components/schemas/ProblemReviewAskAnswerTimeInvalid" + } + ] } } }, - "description": "Problem: request.unprocessable", + "description": "Problem: request.unprocessable, review.ask-answer-time-invalid", "headers": { + "Registry-Review-Validation-Path": { + "description": "Bounded value-free JSON path of the member the request type refused; present together with the validation reason.", + "schema": { + "maxLength": 256, + "type": "string" + } + }, + "Registry-Review-Validation-Reason": { + "description": "Closed value-free validation category, always schema-mismatch for a request shape refusal; present together with the validation path.", + "schema": { + "$ref": "#/components/schemas/ReviewValidationReason" + } + }, "traceparent": { "$ref": "#/components/headers/TraceparentHeader" } @@ -14383,32 +14974,7 @@ } } }, - "502": { - "content": { - "application/problem+json": { - "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/ProblemSourceBadGateway" - }, - { - "$ref": "#/components/schemas/ProblemSourceVersionMismatch" - }, - { - "$ref": "#/components/schemas/ProblemSourceVersionUnavailable" - } - ] - } - } - }, - "description": "Problem: source.bad-gateway, source.version-mismatch, source.version-unavailable", - "headers": { - "traceparent": { - "$ref": "#/components/headers/TraceparentHeader" - } - } - }, - "503": { + "503": { "content": { "application/problem+json": { "schema": { @@ -14435,13 +15001,13 @@ "bearerAuth": [] } ], - "summary": "Get review history" + "summary": "Answer review ask" } }, - "/v1/review-requests/{request_id}/notes": { + "/v1/review-requests/{request_id}/cancel": { "post": { "description": "Recovery repeats the exact request and caller-supplied idempotency key. Clients do not retry mutations implicitly.", - "operationId": "addReviewNote", + "operationId": "cancelReviewRequest", "parameters": [ { "description": "", @@ -14455,7 +15021,7 @@ { "description": "The caller's exact governed access profile for this protocol.", "in": "header", - "name": "registry-casework-profile", + "name": "registry-review-profile", "required": true, "schema": { "maxLength": 128, @@ -14465,31 +15031,6 @@ "x-maximum-utf8-bytes": 128 } }, - { - "description": "Current-source lists, open work, source context, task mutations and new notes require the human caller's source-valid profile and credential. Retained terminal task and history reads use Casework authority. Submitted context requires no provider.", - "in": "header", - "name": "registry-source-profile", - "required": false, - "schema": { - "maxLength": 128, - "minLength": 1, - "pattern": "^[A-Za-z0-9._:-]+$", - "type": "string", - "x-maximum-utf8-bytes": 128 - } - }, - { - "description": "Optional separate human source bearer. Requires explicit source profile and provider-bound configuration; both credentials must independently verify as the same direct human. Never persisted or used as Casework authority; absent preserves legacy single-bearer forwarding.", - "in": "header", - "name": "registry-source-authorization", - "required": false, - "schema": { - "maxLength": 131079, - "minLength": 1, - "type": "string", - "writeOnly": true - } - }, { "description": "", "in": "path", @@ -14517,7 +15058,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ReviewNoteRequest" + "$ref": "#/components/schemas/ReviewCancelRequest" } } }, @@ -14528,7 +15069,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ReviewHistoryEntry" + "$ref": "#/components/schemas/ReviewCancelResponse" } } }, @@ -14752,35 +15293,1355 @@ } } }, - "description": "Problem: absence.cover-cycle, absence.invalid-period, absence.overlap, absence.self-cover, request.unprocessable, review.initiator-required", + "description": "Problem: absence.cover-cycle, absence.invalid-period, absence.overlap, absence.self-cover, request.unprocessable, review.initiator-required", + "headers": { + "Registry-Review-Validation-Path": { + "description": "Bounded value-free JSON path of the member the request type refused; present together with the validation reason.", + "schema": { + "maxLength": 256, + "type": "string" + } + }, + "Registry-Review-Validation-Reason": { + "description": "Closed value-free validation category, always schema-mismatch for a request shape refusal; present together with the validation path.", + "schema": { + "$ref": "#/components/schemas/ReviewValidationReason" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "428": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemPreconditionRequired" + } + } + }, + "description": "Problem: precondition.required", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRuntimeFailure" + } + } + }, + "description": "Problem: runtime.failure", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "502": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemSourceBadGateway" + }, + { + "$ref": "#/components/schemas/ProblemSourceVersionMismatch" + }, + { + "$ref": "#/components/schemas/ProblemSourceVersionUnavailable" + } + ] + } + } + }, + "description": "Problem: source.bad-gateway, source.version-mismatch, source.version-unavailable", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "503": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemServiceUnavailable" + } + } + }, + "description": "Problem: service.unavailable", + "headers": { + "Retry-After": { + "schema": { + "minimum": 0, + "type": "integer" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Cancel review request" + } + }, + "/v1/review-requests/{request_id}/clocks": { + "get": { + "operationId": "getReviewClocks", + "parameters": [ + { + "description": "", + "in": "header", + "name": "traceparent", + "required": false, + "schema": { + "type": "string" + } + }, + { + "description": "The caller's exact governed access profile for this protocol.", + "in": "header", + "name": "registry-casework-profile", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9._:-]+$", + "type": "string", + "x-maximum-utf8-bytes": 128 + } + }, + { + "description": "Current-source lists, open work, source context, task mutations and new notes require the human caller's source-valid profile and credential. Retained terminal task and history reads use Casework authority. Submitted context requires no provider.", + "in": "header", + "name": "registry-source-profile", + "required": false, + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9._:-]+$", + "type": "string", + "x-maximum-utf8-bytes": 128 + } + }, + { + "description": "Optional separate human source bearer. Requires explicit source profile and provider-bound configuration; both credentials must independently verify as the same direct human. Never persisted or used as Casework authority; absent preserves legacy single-bearer forwarding.", + "in": "header", + "name": "registry-source-authorization", + "required": false, + "schema": { + "maxLength": 131079, + "minLength": 1, + "type": "string", + "writeOnly": true + } + }, + { + "description": "", + "in": "path", + "name": "request_id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReviewClockOccurrenceList" + } + } + }, + "description": "Success", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemCursorInvalid" + }, + { + "$ref": "#/components/schemas/ProblemRequestInvalid" + }, + { + "$ref": "#/components/schemas/ProblemRequestLimitOutOfRange" + }, + { + "$ref": "#/components/schemas/ProblemSourceProfileNotApplicable" + }, + { + "$ref": "#/components/schemas/ProblemSourceProfileRequired" + } + ] + } + } + }, + "description": "Problem: cursor.invalid, request.invalid, request.limit-out-of-range, source-profile.not-applicable, source-profile.required", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "401": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemAuthenticationRefused" + } + } + }, + "description": "Problem: authentication.refused", + "headers": { + "WWW-Authenticate": { + "schema": { + "const": "Bearer" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "403": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemOperationNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemProfileNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemProfileNotHuman" + } + ] + } + } + }, + "description": "Problem: operation.not-authorized, profile.not-authorized, profile.not-human", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "404": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestNotFound" + } + } + }, + "description": "Problem: request.not-found", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "410": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemCursorExpired" + }, + { + "$ref": "#/components/schemas/ProblemReviewResultExpired" + } + ] + } + } + }, + "description": "Problem: cursor.expired, review.result-expired", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "413": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestBodyTooLarge" + } + } + }, + "description": "Problem: request.body-too-large", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "415": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestUnsupportedMediaType" + } + } + }, + "description": "Problem: request.unsupported-media-type", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "422": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestUnprocessable" + } + } + }, + "description": "Problem: request.unprocessable", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRuntimeFailure" + } + } + }, + "description": "Problem: runtime.failure", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "502": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemSourceBadGateway" + }, + { + "$ref": "#/components/schemas/ProblemSourceVersionMismatch" + }, + { + "$ref": "#/components/schemas/ProblemSourceVersionUnavailable" + } + ] + } + } + }, + "description": "Problem: source.bad-gateway, source.version-mismatch, source.version-unavailable", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "503": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemServiceUnavailable" + } + } + }, + "description": "Problem: service.unavailable", + "headers": { + "Retry-After": { + "schema": { + "minimum": 0, + "type": "integer" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Get review clocks" + } + }, + "/v1/review-requests/{request_id}/history": { + "get": { + "operationId": "getReviewHistory", + "parameters": [ + { + "description": "", + "in": "header", + "name": "traceparent", + "required": false, + "schema": { + "type": "string" + } + }, + { + "description": "The caller's exact governed access profile for this protocol.", + "in": "header", + "name": "registry-casework-profile", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9._:-]+$", + "type": "string", + "x-maximum-utf8-bytes": 128 + } + }, + { + "description": "Current-source lists, open work, source context, task mutations and new notes require the human caller's source-valid profile and credential. Retained terminal task and history reads use Casework authority. Submitted context requires no provider.", + "in": "header", + "name": "registry-source-profile", + "required": false, + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9._:-]+$", + "type": "string", + "x-maximum-utf8-bytes": 128 + } + }, + { + "description": "Optional separate human source bearer. Requires explicit source profile and provider-bound configuration; both credentials must independently verify as the same direct human. Never persisted or used as Casework authority; absent preserves legacy single-bearer forwarding.", + "in": "header", + "name": "registry-source-authorization", + "required": false, + "schema": { + "maxLength": 131079, + "minLength": 1, + "type": "string", + "writeOnly": true + } + }, + { + "description": "", + "in": "path", + "name": "request_id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + { + "description": "", + "in": "query", + "name": "cursor", + "required": false, + "schema": { + "format": "uuid", + "type": "string" + } + }, + { + "description": "", + "in": "query", + "name": "limit", + "required": false, + "schema": { + "maximum": 100, + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReviewHistoryPage" + } + } + }, + "description": "Success", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemCursorInvalid" + }, + { + "$ref": "#/components/schemas/ProblemRequestInvalid" + }, + { + "$ref": "#/components/schemas/ProblemRequestLimitOutOfRange" + }, + { + "$ref": "#/components/schemas/ProblemSourceProfileNotApplicable" + }, + { + "$ref": "#/components/schemas/ProblemSourceProfileRequired" + } + ] + } + } + }, + "description": "Problem: cursor.invalid, request.invalid, request.limit-out-of-range, source-profile.not-applicable, source-profile.required", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "401": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemAuthenticationRefused" + } + } + }, + "description": "Problem: authentication.refused", + "headers": { + "WWW-Authenticate": { + "schema": { + "const": "Bearer" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "403": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemOperationNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemProfileNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemProfileNotHuman" + } + ] + } + } + }, + "description": "Problem: operation.not-authorized, profile.not-authorized, profile.not-human", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "404": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestNotFound" + } + } + }, + "description": "Problem: request.not-found", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "410": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemCursorExpired" + }, + { + "$ref": "#/components/schemas/ProblemReviewResultExpired" + } + ] + } + } + }, + "description": "Problem: cursor.expired, review.result-expired", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "413": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestBodyTooLarge" + } + } + }, + "description": "Problem: request.body-too-large", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "415": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestUnsupportedMediaType" + } + } + }, + "description": "Problem: request.unsupported-media-type", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "422": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestUnprocessable" + } + } + }, + "description": "Problem: request.unprocessable", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRuntimeFailure" + } + } + }, + "description": "Problem: runtime.failure", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "502": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemSourceBadGateway" + }, + { + "$ref": "#/components/schemas/ProblemSourceVersionMismatch" + }, + { + "$ref": "#/components/schemas/ProblemSourceVersionUnavailable" + } + ] + } + } + }, + "description": "Problem: source.bad-gateway, source.version-mismatch, source.version-unavailable", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "503": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemServiceUnavailable" + } + } + }, + "description": "Problem: service.unavailable", + "headers": { + "Retry-After": { + "schema": { + "minimum": 0, + "type": "integer" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Get review history" + } + }, + "/v1/review-requests/{request_id}/notes": { + "post": { + "description": "Recovery repeats the exact request and caller-supplied idempotency key. Clients do not retry mutations implicitly.", + "operationId": "addReviewNote", + "parameters": [ + { + "description": "", + "in": "header", + "name": "traceparent", + "required": false, + "schema": { + "type": "string" + } + }, + { + "description": "The caller's exact governed access profile for this protocol.", + "in": "header", + "name": "registry-casework-profile", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9._:-]+$", + "type": "string", + "x-maximum-utf8-bytes": 128 + } + }, + { + "description": "Current-source lists, open work, source context, task mutations and new notes require the human caller's source-valid profile and credential. Retained terminal task and history reads use Casework authority. Submitted context requires no provider.", + "in": "header", + "name": "registry-source-profile", + "required": false, + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9._:-]+$", + "type": "string", + "x-maximum-utf8-bytes": 128 + } + }, + { + "description": "Optional separate human source bearer. Requires explicit source profile and provider-bound configuration; both credentials must independently verify as the same direct human. Never persisted or used as Casework authority; absent preserves legacy single-bearer forwarding.", + "in": "header", + "name": "registry-source-authorization", + "required": false, + "schema": { + "maxLength": 131079, + "minLength": 1, + "type": "string", + "writeOnly": true + } + }, + { + "description": "", + "in": "path", + "name": "request_id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + { + "description": "Retain this exact key and request bytes for explicit recovery.", + "in": "header", + "name": "Idempotency-Key", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[!-~]+$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReviewNoteRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReviewHistoryEntry" + } + } + }, + "description": "Success", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemRequestInvalid" + }, + { + "$ref": "#/components/schemas/ProblemSourceProfileNotApplicable" + }, + { + "$ref": "#/components/schemas/ProblemSourceProfileRequired" + } + ] + } + } + }, + "description": "Problem: request.invalid, source-profile.not-applicable, source-profile.required", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "401": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemAuthenticationRefused" + } + } + }, + "description": "Problem: authentication.refused", + "headers": { + "WWW-Authenticate": { + "schema": { + "const": "Bearer" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "403": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemOperationNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemProfileNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemProfileNotHuman" + }, + { + "$ref": "#/components/schemas/ProblemReviewDistinctApproverRequired" + }, + { + "$ref": "#/components/schemas/ProblemReviewInitiatorExcluded" + } + ] + } + } + }, + "description": "Problem: operation.not-authorized, profile.not-authorized, profile.not-human, review.distinct-approver-required, review.initiator-excluded", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "404": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestNotFound" + } + } + }, + "description": "Problem: request.not-found", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "409": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemIdempotencyKeyReused" + }, + { + "$ref": "#/components/schemas/ProblemReviewPolicyMismatch" + }, + { + "$ref": "#/components/schemas/ProblemReviewSubmissionConflict" + }, + { + "$ref": "#/components/schemas/ProblemReviewTaskNotHeld" + } + ] + } + } + }, + "description": "Problem: idempotency.key-reused, review.policy-mismatch, review.submission-conflict, review.task-not-held", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "410": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemIdempotencyExpired" + }, + { + "$ref": "#/components/schemas/ProblemReviewResultExpired" + } + ] + } + } + }, + "description": "Problem: idempotency.expired, review.result-expired", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "412": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemPreconditionFailed" + } + } + }, + "description": "Problem: precondition.failed", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "413": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestBodyTooLarge" + } + } + }, + "description": "Problem: request.body-too-large", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "415": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestUnsupportedMediaType" + } + } + }, + "description": "Problem: request.unsupported-media-type", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "422": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemAbsenceCoverCycle" + }, + { + "$ref": "#/components/schemas/ProblemAbsenceInvalidPeriod" + }, + { + "$ref": "#/components/schemas/ProblemAbsenceOverlap" + }, + { + "$ref": "#/components/schemas/ProblemAbsenceSelfCover" + }, + { + "$ref": "#/components/schemas/ProblemRequestUnprocessable" + }, + { + "$ref": "#/components/schemas/ProblemReviewInitiatorRequired" + } + ] + } + } + }, + "description": "Problem: absence.cover-cycle, absence.invalid-period, absence.overlap, absence.self-cover, request.unprocessable, review.initiator-required", + "headers": { + "Registry-Casework-Validation-Path": { + "description": "Bounded value-free JSON path of the member the request type refused; present together with the validation reason.", + "schema": { + "maxLength": 256, + "type": "string" + } + }, + "Registry-Casework-Validation-Reason": { + "description": "Closed value-free validation category, always schema-mismatch for a request shape refusal; present together with the validation path.", + "schema": { + "$ref": "#/components/schemas/ReviewValidationReason" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "428": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemPreconditionRequired" + } + } + }, + "description": "Problem: precondition.required", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRuntimeFailure" + } + } + }, + "description": "Problem: runtime.failure", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "502": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemSourceBadGateway" + }, + { + "$ref": "#/components/schemas/ProblemSourceVersionMismatch" + }, + { + "$ref": "#/components/schemas/ProblemSourceVersionUnavailable" + } + ] + } + } + }, + "description": "Problem: source.bad-gateway, source.version-mismatch, source.version-unavailable", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "503": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemServiceUnavailable" + } + } + }, + "description": "Problem: service.unavailable", + "headers": { + "Retry-After": { + "schema": { + "minimum": 0, + "type": "integer" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Add review note" + } + }, + "/v1/review-requests/{request_id}/result": { + "get": { + "operationId": "getReviewResult", + "parameters": [ + { + "description": "", + "in": "header", + "name": "traceparent", + "required": false, + "schema": { + "type": "string" + } + }, + { + "description": "The caller's exact governed access profile for this protocol.", + "in": "header", + "name": "registry-review-profile", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9._:-]+$", + "type": "string", + "x-maximum-utf8-bytes": 128 + } + }, + { + "description": "", + "in": "path", + "name": "request_id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReviewResult" + } + } + }, + "description": "Success", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "202": { + "description": "The review result is pending.", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemCursorInvalid" + }, + { + "$ref": "#/components/schemas/ProblemRequestInvalid" + }, + { + "$ref": "#/components/schemas/ProblemRequestLimitOutOfRange" + }, + { + "$ref": "#/components/schemas/ProblemSourceProfileNotApplicable" + }, + { + "$ref": "#/components/schemas/ProblemSourceProfileRequired" + } + ] + } + } + }, + "description": "Problem: cursor.invalid, request.invalid, request.limit-out-of-range, source-profile.not-applicable, source-profile.required", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "401": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemAuthenticationRefused" + } + } + }, + "description": "Problem: authentication.refused", + "headers": { + "WWW-Authenticate": { + "schema": { + "const": "Bearer" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "403": { + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemOperationNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemProfileNotAuthorized" + }, + { + "$ref": "#/components/schemas/ProblemProfileNotHuman" + } + ] + } + } + }, + "description": "Problem: operation.not-authorized, profile.not-authorized, profile.not-human", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "404": { + "description": "The review request is concealed or unknown.", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "410": { + "description": "The review result has expired.", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "413": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestBodyTooLarge" + } + } + }, + "description": "Problem: request.body-too-large", "headers": { - "Registry-Casework-Validation-Path": { - "description": "Bounded value-free JSON path of the member the request type refused; present together with the validation reason.", - "schema": { - "maxLength": 256, - "type": "string" - } - }, - "Registry-Casework-Validation-Reason": { - "description": "Closed value-free validation category, always schema-mismatch for a request shape refusal; present together with the validation path.", + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "415": { + "content": { + "application/problem+json": { "schema": { - "$ref": "#/components/schemas/ReviewValidationReason" + "$ref": "#/components/schemas/ProblemRequestUnsupportedMediaType" } - }, + } + }, + "description": "Problem: request.unsupported-media-type", + "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" } } }, - "428": { + "422": { "content": { "application/problem+json": { "schema": { - "$ref": "#/components/schemas/ProblemPreconditionRequired" + "$ref": "#/components/schemas/ProblemRequestUnprocessable" } } }, - "description": "Problem: precondition.required", + "description": "Problem: request.unprocessable", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -14854,12 +16715,12 @@ "bearerAuth": [] } ], - "summary": "Add review note" + "summary": "Get review result" } }, - "/v1/review-requests/{request_id}/result": { + "/v1/review-results": { "get": { - "operationId": "getReviewResult", + "operationId": "listReviewResults", "parameters": [ { "description": "", @@ -14885,13 +16746,24 @@ }, { "description": "", - "in": "path", - "name": "request_id", - "required": true, + "in": "query", + "name": "cursor", + "required": false, "schema": { "format": "uuid", "type": "string" } + }, + { + "description": "", + "in": "query", + "name": "limit", + "required": false, + "schema": { + "maximum": 100, + "minimum": 1, + "type": "integer" + } } ], "responses": { @@ -14899,7 +16771,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ReviewResult" + "$ref": "#/components/schemas/ReviewResultFeedPage" } } }, @@ -14910,14 +16782,6 @@ } } }, - "202": { - "description": "The review result is pending.", - "headers": { - "traceparent": { - "$ref": "#/components/headers/TraceparentHeader" - } - } - }, "400": { "content": { "application/problem+json": { @@ -14995,7 +16859,14 @@ } }, "404": { - "description": "The review request is concealed or unknown.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemRequestNotFound" + } + } + }, + "description": "Problem: request.not-found", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -15003,7 +16874,21 @@ } }, "410": { - "description": "The review result has expired.", + "content": { + "application/problem+json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/ProblemCursorExpired" + }, + { + "$ref": "#/components/schemas/ProblemReviewResultExpired" + } + ] + } + } + }, + "description": "Problem: cursor.expired, review.result-expired", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -15095,81 +16980,243 @@ } } }, - "503": { - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/ProblemServiceUnavailable" - } - } - }, - "description": "Problem: service.unavailable", - "headers": { - "Retry-After": { - "schema": { - "minimum": 0, - "type": "integer" - } - }, - "traceparent": { - "$ref": "#/components/headers/TraceparentHeader" - } + "503": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemServiceUnavailable" + } + } + }, + "description": "Problem: service.unavailable", + "headers": { + "Retry-After": { + "schema": { + "minimum": 0, + "type": "integer" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "List review results" + } + }, + "/v1/review-tasks": { + "get": { + "operationId": "listReviewTasks", + "parameters": [ + { + "description": "", + "in": "header", + "name": "traceparent", + "required": false, + "schema": { + "type": "string" + } + }, + { + "description": "The caller's exact governed access profile for this protocol.", + "in": "header", + "name": "registry-casework-profile", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9._:-]+$", + "type": "string", + "x-maximum-utf8-bytes": 128 + } + }, + { + "description": "Current-source lists, open work, source context, task mutations and new notes require the human caller's source-valid profile and credential. Retained terminal task and history reads use Casework authority. Submitted context requires no provider.", + "in": "header", + "name": "registry-source-profile", + "required": false, + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9._:-]+$", + "type": "string", + "x-maximum-utf8-bytes": 128 + } + }, + { + "description": "Optional separate human source bearer. Requires explicit source profile and provider-bound configuration; both credentials must independently verify as the same direct human. Never persisted or used as Casework authority; absent preserves legacy single-bearer forwarding.", + "in": "header", + "name": "registry-source-authorization", + "required": false, + "schema": { + "maxLength": 131079, + "minLength": 1, + "type": "string", + "writeOnly": true + } + }, + { + "description": "", + "in": "query", + "name": "cursor", + "required": false, + "schema": { + "format": "uuid", + "type": [ + "string", + "null" + ] + } + }, + { + "description": "", + "in": "query", + "name": "limit", + "required": false, + "schema": { + "format": "uint", + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + { + "description": "", + "in": "query", + "name": "marker", + "required": false, + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InputReviewTaskMarker" + }, + { + "type": "null" + } + ], + "description": "Lists tasks by their ask marker: waiting, answered, or expired." + } + }, + { + "description": "", + "in": "query", + "name": "ownership", + "required": false, + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InputReviewTaskOwnership" + }, + { + "type": "null" + } + ] + } + }, + { + "description": "", + "in": "query", + "name": "queue", + "required": false, + "schema": { + "type": [ + "string", + "null" + ] + } + }, + { + "description": "", + "in": "query", + "name": "reference", + "required": false, + "schema": { + "type": [ + "string", + "null" + ] + } + }, + { + "description": "", + "in": "query", + "name": "sort", + "required": false, + "schema": { + "$ref": "#/components/schemas/InputReviewTaskSort", + "default": "due" } - } - }, - "security": [ + }, { - "bearerAuth": [] - } - ], - "summary": "Get review result" - } - }, - "/v1/review-results": { - "get": { - "operationId": "listReviewResults", - "parameters": [ + "description": "", + "in": "query", + "name": "subjectDigest", + "required": false, + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InputContentDigest" + }, + { + "type": "null" + } + ] + } + }, { "description": "", - "in": "header", - "name": "traceparent", + "in": "query", + "name": "subjectId", "required": false, "schema": { - "type": "string" + "type": [ + "string", + "null" + ] } }, { - "description": "The caller's exact governed access profile for this protocol.", - "in": "header", - "name": "registry-review-profile", - "required": true, + "description": "", + "in": "query", + "name": "subjectSource", + "required": false, "schema": { - "maxLength": 128, - "minLength": 1, - "pattern": "^[A-Za-z0-9._:-]+$", - "type": "string", - "x-maximum-utf8-bytes": 128 + "type": [ + "string", + "null" + ] } }, { "description": "", "in": "query", - "name": "cursor", + "name": "subjectType", "required": false, "schema": { - "format": "uuid", - "type": "string" + "type": [ + "string", + "null" + ] } }, { "description": "", "in": "query", - "name": "limit", + "name": "subjectVersion", "required": false, "schema": { - "maximum": 100, - "minimum": 1, - "type": "integer" + "type": [ + "string", + "null" + ] } } ], @@ -15178,7 +17225,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ReviewResultFeedPage" + "$ref": "#/components/schemas/ReviewTaskPage" } } }, @@ -15414,12 +17461,12 @@ "bearerAuth": [] } ], - "summary": "List review results" + "summary": "List review tasks" } }, - "/v1/review-tasks": { + "/v1/review-tasks/holdings": { "get": { - "operationId": "listReviewTasks", + "operationId": "getReviewTaskHoldings", "parameters": [ { "description": "", @@ -15495,6 +17542,23 @@ ] } }, + { + "description": "", + "in": "query", + "name": "marker", + "required": false, + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InputReviewTaskMarker" + }, + { + "type": "null" + } + ], + "description": "Lists tasks by their ask marker: waiting, answered, or expired." + } + }, { "description": "", "in": "query", @@ -15851,12 +17915,12 @@ "bearerAuth": [] } ], - "summary": "List review tasks" + "summary": "Get review task holdings" } }, - "/v1/review-tasks/holdings": { + "/v1/review-tasks/next": { "get": { - "operationId": "getReviewTaskHoldings", + "operationId": "getNextReviewTask", "parameters": [ { "description": "", @@ -15932,6 +17996,23 @@ ] } }, + { + "description": "", + "in": "query", + "name": "marker", + "required": false, + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InputReviewTaskMarker" + }, + { + "type": "null" + } + ], + "description": "Lists tasks by their ask marker: waiting, answered, or expired." + } + }, { "description": "", "in": "query", @@ -16052,7 +18133,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ReviewTaskPage" + "$ref": "#/components/schemas/OptionalReviewTask" } } }, @@ -16288,12 +18369,12 @@ "bearerAuth": [] } ], - "summary": "Get review task holdings" + "summary": "Get next review task" } }, - "/v1/review-tasks/next": { + "/v1/review-tasks/own-decisions": { "get": { - "operationId": "getNextReviewTask", + "operationId": "listOwnReviewDecisions", "parameters": [ { "description": "", @@ -16309,178 +18390,71 @@ "in": "header", "name": "registry-casework-profile", "required": true, - "schema": { - "maxLength": 128, - "minLength": 1, - "pattern": "^[A-Za-z0-9._:-]+$", - "type": "string", - "x-maximum-utf8-bytes": 128 - } - }, - { - "description": "Current-source lists, open work, source context, task mutations and new notes require the human caller's source-valid profile and credential. Retained terminal task and history reads use Casework authority. Submitted context requires no provider.", - "in": "header", - "name": "registry-source-profile", - "required": false, - "schema": { - "maxLength": 128, - "minLength": 1, - "pattern": "^[A-Za-z0-9._:-]+$", - "type": "string", - "x-maximum-utf8-bytes": 128 - } - }, - { - "description": "Optional separate human source bearer. Requires explicit source profile and provider-bound configuration; both credentials must independently verify as the same direct human. Never persisted or used as Casework authority; absent preserves legacy single-bearer forwarding.", - "in": "header", - "name": "registry-source-authorization", - "required": false, - "schema": { - "maxLength": 131079, - "minLength": 1, - "type": "string", - "writeOnly": true - } - }, - { - "description": "", - "in": "query", - "name": "cursor", - "required": false, - "schema": { - "format": "uuid", - "type": [ - "string", - "null" - ] - } - }, - { - "description": "", - "in": "query", - "name": "limit", - "required": false, - "schema": { - "format": "uint", - "minimum": 0, - "type": [ - "integer", - "null" - ] - } - }, - { - "description": "", - "in": "query", - "name": "ownership", - "required": false, - "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/InputReviewTaskOwnership" - }, - { - "type": "null" - } - ] - } - }, - { - "description": "", - "in": "query", - "name": "queue", - "required": false, - "schema": { - "type": [ - "string", - "null" - ] - } - }, - { - "description": "", - "in": "query", - "name": "reference", - "required": false, - "schema": { - "type": [ - "string", - "null" - ] - } - }, - { - "description": "", - "in": "query", - "name": "sort", - "required": false, - "schema": { - "$ref": "#/components/schemas/InputReviewTaskSort", - "default": "due" + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9._:-]+$", + "type": "string", + "x-maximum-utf8-bytes": 128 } }, { - "description": "", - "in": "query", - "name": "subjectDigest", + "description": "Current-source lists, open work, source context, task mutations and new notes require the human caller's source-valid profile and credential. Retained terminal task and history reads use Casework authority. Submitted context requires no provider.", + "in": "header", + "name": "registry-source-profile", "required": false, "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/InputContentDigest" - }, - { - "type": "null" - } - ] + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9._:-]+$", + "type": "string", + "x-maximum-utf8-bytes": 128 } }, { - "description": "", - "in": "query", - "name": "subjectId", + "description": "Optional separate human source bearer. Requires explicit source profile and provider-bound configuration; both credentials must independently verify as the same direct human. Never persisted or used as Casework authority; absent preserves legacy single-bearer forwarding.", + "in": "header", + "name": "registry-source-authorization", "required": false, "schema": { - "type": [ - "string", - "null" - ] + "maxLength": 131079, + "minLength": 1, + "type": "string", + "writeOnly": true } }, { "description": "", "in": "query", - "name": "subjectSource", + "name": "cursor", "required": false, "schema": { - "type": [ - "string", - "null" - ] + "format": "uuid", + "type": "string" } }, { "description": "", "in": "query", - "name": "subjectType", + "name": "limit", "required": false, "schema": { - "type": [ - "string", - "null" - ] + "maximum": 100, + "minimum": 1, + "type": "integer" } }, { "description": "", "in": "query", - "name": "subjectVersion", + "name": "queue", "required": false, "schema": { - "type": [ - "string", - "null" - ] + "maxLength": 128, + "minLength": 1, + "pattern": "^[A-Za-z0-9._:-]+$", + "type": "string", + "x-maximum-utf8-bytes": 128 } } ], @@ -16489,7 +18463,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/OptionalReviewTask" + "$ref": "#/components/schemas/OwnReviewDecisionPage" } } }, @@ -16725,12 +18699,12 @@ "bearerAuth": [] } ], - "summary": "Get next review task" + "summary": "List own review decisions" } }, - "/v1/review-tasks/own-decisions": { + "/v1/review-tasks/supervision": { "get": { - "operationId": "listOwnReviewDecisions", + "operationId": "listSupervisoryReviewTasks", "parameters": [ { "description": "", @@ -16812,6 +18786,16 @@ "type": "string", "x-maximum-utf8-bytes": 128 } + }, + { + "description": "", + "in": "query", + "name": "requestId", + "required": false, + "schema": { + "format": "uuid", + "type": "string" + } } ], "responses": { @@ -16819,7 +18803,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/OwnReviewDecisionPage" + "$ref": "#/components/schemas/SupervisoryReviewTaskPage" } } }, @@ -17055,12 +19039,12 @@ "bearerAuth": [] } ], - "summary": "List own review decisions" + "summary": "List supervisory review tasks" } }, - "/v1/review-tasks/supervision": { + "/v1/review-tasks/{task_id}": { "get": { - "operationId": "listSupervisoryReviewTasks", + "operationId": "getReviewTask", "parameters": [ { "description": "", @@ -17111,43 +19095,9 @@ }, { "description": "", - "in": "query", - "name": "cursor", - "required": false, - "schema": { - "format": "uuid", - "type": "string" - } - }, - { - "description": "", - "in": "query", - "name": "limit", - "required": false, - "schema": { - "maximum": 100, - "minimum": 1, - "type": "integer" - } - }, - { - "description": "", - "in": "query", - "name": "queue", - "required": false, - "schema": { - "maxLength": 128, - "minLength": 1, - "pattern": "^[A-Za-z0-9._:-]+$", - "type": "string", - "x-maximum-utf8-bytes": 128 - } - }, - { - "description": "", - "in": "query", - "name": "requestId", - "required": false, + "in": "path", + "name": "task_id", + "required": true, "schema": { "format": "uuid", "type": "string" @@ -17159,7 +19109,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SupervisoryReviewTaskPage" + "$ref": "#/components/schemas/ReviewTask" } } }, @@ -17395,12 +19345,13 @@ "bearerAuth": [] } ], - "summary": "List supervisory review tasks" + "summary": "Get review task" } }, - "/v1/review-tasks/{task_id}": { - "get": { - "operationId": "getReviewTask", + "/v1/review-tasks/{task_id}/asks": { + "post": { + "description": "Recovery repeats the exact request and caller-supplied idempotency key. Clients do not retry mutations implicitly.", + "operationId": "askApplicant", "parameters": [ { "description": "", @@ -17458,14 +19409,46 @@ "format": "uuid", "type": "string" } + }, + { + "description": "Quoted current revision.", + "in": "header", + "name": "If-Match", + "required": true, + "schema": { + "pattern": "^\"[1-9][0-9]*\"$", + "type": "string" + } + }, + { + "description": "Retain this exact key and request bytes for explicit recovery.", + "in": "header", + "name": "Idempotency-Key", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[!-~]+$", + "type": "string" + } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReviewTaskAskRequest" + } + } + }, + "required": true + }, "responses": { "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ReviewTask" + "$ref": "#/components/schemas/ReviewTaskAsked" } } }, @@ -17481,15 +19464,9 @@ "application/problem+json": { "schema": { "oneOf": [ - { - "$ref": "#/components/schemas/ProblemCursorInvalid" - }, { "$ref": "#/components/schemas/ProblemRequestInvalid" }, - { - "$ref": "#/components/schemas/ProblemRequestLimitOutOfRange" - }, { "$ref": "#/components/schemas/ProblemSourceProfileNotApplicable" }, @@ -17500,7 +19477,7 @@ } } }, - "description": "Problem: cursor.invalid, request.invalid, request.limit-out-of-range, source-profile.not-applicable, source-profile.required", + "description": "Problem: request.invalid, source-profile.not-applicable, source-profile.required", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -17567,22 +19544,67 @@ } } }, - "410": { + "409": { "content": { "application/problem+json": { "schema": { "oneOf": [ { - "$ref": "#/components/schemas/ProblemCursorExpired" + "$ref": "#/components/schemas/ProblemIdempotencyKeyReused" }, { - "$ref": "#/components/schemas/ProblemReviewResultExpired" + "$ref": "#/components/schemas/ProblemReviewAskAlreadyOpen" + }, + { + "$ref": "#/components/schemas/ProblemReviewAskLimitReached" + }, + { + "$ref": "#/components/schemas/ProblemReviewAskNotOffered" + }, + { + "$ref": "#/components/schemas/ProblemReviewAskProducerUnsupported" + }, + { + "$ref": "#/components/schemas/ProblemReviewAskTaskInactive" + }, + { + "$ref": "#/components/schemas/ProblemReviewTaskNotHeld" } ] } } }, - "description": "Problem: cursor.expired, review.result-expired", + "description": "Problem: idempotency.key-reused, review.ask-already-open, review.ask-limit-reached, review.ask-not-offered, review.ask-producer-unsupported, review.ask-task-inactive, review.task-not-held", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "410": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemIdempotencyExpired" + } + } + }, + "description": "Problem: idempotency.expired", + "headers": { + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "412": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemPreconditionFailed" + } + } + }, + "description": "Problem: precondition.failed", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -17628,6 +19650,34 @@ } }, "description": "Problem: request.unprocessable", + "headers": { + "Registry-Casework-Validation-Path": { + "description": "Bounded value-free JSON path of the member the request type refused; present together with the validation reason.", + "schema": { + "maxLength": 256, + "type": "string" + } + }, + "Registry-Casework-Validation-Reason": { + "description": "Closed value-free validation category, always schema-mismatch for a request shape refusal; present together with the validation path.", + "schema": { + "$ref": "#/components/schemas/ReviewValidationReason" + } + }, + "traceparent": { + "$ref": "#/components/headers/TraceparentHeader" + } + } + }, + "428": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemPreconditionRequired" + } + } + }, + "description": "Problem: precondition.required", "headers": { "traceparent": { "$ref": "#/components/headers/TraceparentHeader" @@ -17701,7 +19751,7 @@ "bearerAuth": [] } ], - "summary": "Get review task" + "summary": "Ask applicant" } }, "/v1/review-tasks/{task_id}/assign": { diff --git a/products/casework/scripts/generate_openapi.py b/products/casework/scripts/generate_openapi.py index f61606f775..8eeae90f5c 100644 --- a/products/casework/scripts/generate_openapi.py +++ b/products/casework/scripts/generate_openapi.py @@ -50,6 +50,9 @@ class Endpoint: Endpoint("GET","/v1/review-requests/{request_id}/clocks","getReviewClocks","ReviewClockOccurrenceList",source=True), Endpoint("POST","/v1/review-requests/{request_id}/notes","addReviewNote","ReviewHistoryEntry","ReviewNoteRequest",source=True,idempotency=True), Endpoint("GET","/v1/review-results","listReviewResults","ReviewResultFeedPage",query="page",review=True), + Endpoint("GET","/v1/review-asks","listReviewAsks","ReviewAskFeedPage",query="page",review=True), + Endpoint("GET","/v1/review-requests/{request_id}/asks/{ask_id}","getReviewAsk","ReviewAsk",review=True), + Endpoint("POST","/v1/review-requests/{request_id}/asks/{ask_id}/answer","answerReviewAsk","ReviewAsk","ReviewAskAnswer",idempotency=True,review=True), Endpoint("GET","/v1/review-tasks","listReviewTasks","ReviewTaskPage",query="ReviewStaffingQuery",source=True), Endpoint("GET","/v1/delegated-staff/review-tasks","listDelegatedStaffReviewTasks","ReviewTaskPage",query="page",source=True,delegated=True), Endpoint("GET","/v1/delegated-staff/review-tasks/{task_id}/context","getDelegatedStaffReviewTaskContext","ReviewTaskContext",source=True,delegated=True), @@ -66,6 +69,7 @@ class Endpoint: Endpoint("GET","/v1/review-tasks/{task_id}/draft","getReviewDecisionDraft","ReviewTaskDraft",source=True), Endpoint("PUT","/v1/review-tasks/{task_id}/draft","saveReviewDecisionDraft","ReviewTaskDraft","ReviewTaskDraftInput",source=True,revision="positive",idempotency=True), Endpoint("DELETE","/v1/review-tasks/{task_id}/draft","deleteReviewDecisionDraft",source=True,revision="positive",idempotency=True), + Endpoint("POST","/v1/review-tasks/{task_id}/asks","askApplicant","ReviewTaskAsked","ReviewTaskAskRequest",source=True,revision="positive",idempotency=True), Endpoint("POST","/v1/review-tasks/{task_id}/decisions","decideReviewTask",body="ReviewTaskDecisionRequest",source=True,revision="positive",idempotency=True), Endpoint("GET","/v1/review-tasks/{task_id}/task-templates","previewReviewTaskTemplates","TaskTemplatePreviews",source=True), Endpoint("GET","/v1/review-tasks/{task_id}/task-grants","listReviewTaskGrants","TaskGrantList",source=True), diff --git a/products/casework/scripts/test_product_contracts.py b/products/casework/scripts/test_product_contracts.py index 75d809c312..72541d94bd 100644 --- a/products/casework/scripts/test_product_contracts.py +++ b/products/casework/scripts/test_product_contracts.py @@ -124,6 +124,19 @@ def test_staffing_diagnostic_is_optional_on_both_task_projections(self): "taskId", "requestId", "queue", "revision", "state", "staffingDiagnostic", "accountabilityEventId" }) + def test_ask_timing_and_resubmission_are_published(self): + schemas = json.loads((PRODUCT / "generated/registry-casework.openapi.json").read_text())["components"]["schemas"] + self.assertIn("expired", schemas["ReviewTaskMarker"]["enum"]) + self.assertIn("paused", schemas["ReviewClockState"]["enum"]) + self.assertEqual(set(schemas["ReviewStageAsksPolicy"]["properties"]), {"answerWithin", "onDue", "pauseClocks"}) + self.assertEqual(schemas["ReviewAskOnDue"]["enum"], ["return-to-reviewer"]) + self.assertEqual(schemas["ReviewResubmissionPolicy"]["enum"], ["first-stage", "resume-at-returning-stage"]) + self.assertIn("resubmission", schemas["ReviewPolicyClosure"]["properties"]) + self.assertNotIn("resubmission", schemas["ReviewPolicyClosure"]["required"]) + project = json.loads((PRODUCT / "generated/project/project.schema.json").read_text()) + self.assertEqual(set(project["$defs"]["ReviewStageAsksPolicy"]["properties"]), {"answerWithin", "onDue", "pauseClocks"}) + self.assertIn("resubmission", project["properties"]["reviewPolicies"]["additionalProperties"]["properties"]) + def test_cli_report_contract_is_generated_from_one_typed_union(self): schemas = sorted(path.name for path in (PRODUCT / "contracts/cli").glob("*.schema.json")) self.assertEqual(schemas, ["report.schema.json"]) diff --git a/products/identifiers/contracts/catalog-source.json b/products/identifiers/contracts/catalog-source.json index 03b64b6ba3..16a2abb943 100644 --- a/products/identifiers/contracts/catalog-source.json +++ b/products/identifiers/contracts/catalog-source.json @@ -375,7 +375,7 @@ "glob": "products/breg/contracts/explain/LifecycleExplanation.schema.json", "owner": "breg", "status": "active", - "compatibilityLine": "v1alpha8", + "compatibilityLine": "v1alpha9", "description": "Base Registry Engine bregctl explain output JSON Schemas, written by hand and held to bregctl's output by its contract test." }, { diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 589a022d00..d346bb479f 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -30,11 +30,11 @@ "description": "Base Registry Engine fixed Proposal lifecycle event schema, reproduced byte-for-byte from its packaged artifact.", "source": { "path": "crates/registry-breg/src/proposal_hooks.rs", - "sha256": "23fceb42341650d4f4a3477a025fe8a8065759a7f490ec98a0ff11281c23a917" + "sha256": "8536d155fb4b4007e70122255cbac89bc40ae0aaf42c60366c5c49e0d21caff6" }, "artifact": { "path": "products/breg/generated/event-schemas/proposal-lifecycle.schema.json", - "sha256": "7d694df0140e03e1a4c1e6a564e52d69a7d334b9e0063d8aeded24d28b83d182", + "sha256": "0b68b183c193cd634e7e704051dbd87a4454fa8cc369177303b5faaae994b58e", "mediaType": "application/schema+json" } }, @@ -61,7 +61,7 @@ "description": "The declared Evidence dependency could not be accepted.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "action.evidence_failed", @@ -80,7 +80,7 @@ "description": "The action guard was not satisfied.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "action.guard_failed", @@ -99,7 +99,7 @@ "description": "The action handler could not produce an accepted result.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "action.handler_failed", @@ -118,7 +118,7 @@ "description": "The action was refused by a declared business rule.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "action.refused", @@ -137,7 +137,7 @@ "description": "The file media type is not one the attachment slot accepts.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "attachment.content-type", @@ -156,7 +156,7 @@ "description": "The file content does not match its declared SHA-256 digest.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "attachment.digest-mismatch", @@ -165,6 +165,44 @@ ] } }, + { + "uri": "https://id.registrystack.org/problems/registry-breg/attachment/limit-reached", + "kind": "problem", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "breg", + "title": "Conflict", + "description": "The supporting document slot has reached its file limit.", + "source": { + "path": "crates/registry-breg/src/problem.rs", + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" + }, + "problem": { + "code": "attachment.limit-reached", + "httpStatuses": [ + 409 + ] + } + }, + { + "uri": "https://id.registrystack.org/problems/registry-breg/attachment/required", + "kind": "problem", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "breg", + "title": "Unprocessable Entity", + "description": "The required attachment slot is empty.", + "source": { + "path": "crates/registry-breg/src/problem.rs", + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" + }, + "problem": { + "code": "attachment.required", + "httpStatuses": [ + 422 + ] + } + }, { "uri": "https://id.registrystack.org/problems/registry-breg/attachment/slot-write-once", "kind": "problem", @@ -175,7 +213,7 @@ "description": "The record attachment slot already holds a file and is write-once.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "attachment.slot-write-once", @@ -194,7 +232,7 @@ "description": "The file is larger than the attachment slot accepts.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "attachment.too-large", @@ -203,6 +241,44 @@ ] } }, + { + "uri": "https://id.registrystack.org/problems/registry-breg/attachment/verification-pending", + "kind": "problem", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "breg", + "title": "Conflict", + "description": "The attachment is awaiting verification. Refresh the Proposal before submitting.", + "source": { + "path": "crates/registry-breg/src/problem.rs", + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" + }, + "problem": { + "code": "attachment.verification-pending", + "httpStatuses": [ + 409 + ] + } + }, + { + "uri": "https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected", + "kind": "problem", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "breg", + "title": "Unprocessable Entity", + "description": "The attachment was rejected by verification. Replace or remove the file before submitting.", + "source": { + "path": "crates/registry-breg/src/problem.rs", + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" + }, + "problem": { + "code": "attachment.verification-rejected", + "httpStatuses": [ + 422 + ] + } + }, { "uri": "https://id.registrystack.org/problems/registry-breg/authentication/refused", "kind": "problem", @@ -213,7 +289,7 @@ "description": "The bearer token or delivery signature was not accepted.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "authentication.refused", @@ -232,7 +308,7 @@ "description": "The external view's indexed coverage is incomplete for this request.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "external_view.incomplete", @@ -251,7 +327,7 @@ "description": "The held response of the idempotency key expired; the key stays spent.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "idempotency.expired", @@ -270,7 +346,7 @@ "description": "The idempotency key is bound to another request.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "idempotency.key-reused", @@ -289,7 +365,7 @@ "description": "The chunk does not match the expected next chunk.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "ingestion.chunk_mismatch", @@ -308,7 +384,7 @@ "description": "The selected access profile does not match the run's bound profile.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "ingestion.profile_mismatch", @@ -327,7 +403,7 @@ "description": "The stored receipt of the chunk was erased.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "ingestion.receipt_erased", @@ -346,7 +422,7 @@ "description": "The ingestion run is blocked and refuses further chunks.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "ingestion.run_blocked", @@ -365,7 +441,7 @@ "description": "The ingestion run is not open for this transition.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "ingestion.run_not_open", @@ -384,7 +460,7 @@ "description": "The lookup did not resolve exactly one record.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "lookup.unresolved", @@ -403,7 +479,7 @@ "description": "The mutation conflicts with current state.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "mutation.conflict", @@ -422,7 +498,7 @@ "description": "The mutation precondition failed.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "precondition.failed", @@ -441,7 +517,7 @@ "description": "The mutation precondition is required.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "precondition.required", @@ -460,7 +536,7 @@ "description": "The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "proposal.rejected", @@ -479,7 +555,7 @@ "description": "The current review result does not match the retained approval.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "proposal.review_result_mismatch", @@ -498,7 +574,7 @@ "description": "The review result and application receipt of the submission are no longer retained.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "proposal.submission_expired", @@ -517,7 +593,7 @@ "description": "The query cursor is invalid.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "query.cursor_invalid", @@ -536,7 +612,7 @@ "description": "The list did not carry the search criteria its access profile requires.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "query.filter_required", @@ -555,7 +631,7 @@ "description": "The query request is invalid.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "query.invalid", @@ -574,7 +650,7 @@ "description": "The access profile requires a valid Registry-Access-Reason header.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "request.access_reason_required", @@ -593,7 +669,7 @@ "description": "The request is invalid.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "request.invalid", @@ -612,7 +688,7 @@ "description": "The request timed out.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "request.timeout", @@ -631,7 +707,7 @@ "description": "The requested resource was not found.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "resource.not_found", @@ -650,7 +726,7 @@ "description": "The Registry field-encryption service is unavailable.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "runtime.field_encryption.unavailable", @@ -669,7 +745,7 @@ "description": "Registry runtime is not ready.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "runtime.not_ready", @@ -688,7 +764,7 @@ "description": "The Registry mutation service is unavailable.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "service.unavailable", @@ -707,7 +783,7 @@ "description": "The Registry data service is unavailable.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "source.unavailable", @@ -726,7 +802,7 @@ "description": "A statistical dataset contains a code outside its declared domain.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "statistical_dataset.domain_violation", @@ -745,7 +821,7 @@ "description": "The statistical dataset release operation is not eligible.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "statistical_dataset.release_refused", @@ -764,7 +840,7 @@ "description": "The statistical dataset computation was superseded or its package changed.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "statistical_dataset.version_conflict", @@ -783,7 +859,7 @@ "description": "The statistical dataset version was withdrawn.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "statistical_dataset.version_withdrawn", @@ -802,7 +878,7 @@ "description": "The request media type is not supported.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "unsupported.media_type", @@ -821,7 +897,7 @@ "description": "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.", "source": { "path": "crates/registry-breg/src/problem.rs", - "sha256": "96e840e8d6a60808b3557277d25bdce2e41c405d843c118b9beedddb45b7b87d" + "sha256": "ed27ca26478087c611cd79391be19bb0b0598f331af4f8d31ab3d3b4e29cbdbc" }, "problem": { "code": "write.outside-boundary", @@ -840,7 +916,7 @@ "description": "Choose cover assignments that do not return to an earlier person during a shared period.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "absence.cover-cycle", @@ -859,7 +935,7 @@ "description": "Set until later than from.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "absence.invalid-period", @@ -878,7 +954,7 @@ "description": "Adjust the period so this person has no overlapping absence.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "absence.overlap", @@ -897,7 +973,7 @@ "description": "Choose a different staff member as cover.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "absence.self-cover", @@ -916,7 +992,7 @@ "description": "The bearer credential is missing, invalid, or expired. Sign in again.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "authentication.refused", @@ -935,7 +1011,7 @@ "description": "Create a new recompute preview and review it before applying.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "clock.recompute-preview-expired", @@ -954,7 +1030,7 @@ "description": "This cursor has expired. Start again without a cursor and deduplicate entries by eventId.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "cursor.expired", @@ -973,7 +1049,7 @@ "description": "The cursor is invalid for this request.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "cursor.invalid", @@ -992,7 +1068,7 @@ "description": "The stored response for this idempotency key has expired. Reconcile the original operation before choosing a new key.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "idempotency.expired", @@ -1011,7 +1087,7 @@ "description": "This idempotency key was used for a different request.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "idempotency.key-reused", @@ -1030,7 +1106,7 @@ "description": "Your current Casework authority does not allow this operation.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "operation.not-authorized", @@ -1049,7 +1125,7 @@ "description": "The item or directory changed since you loaded it. Reload and try again.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "precondition.failed", @@ -1068,7 +1144,7 @@ "description": "This mutation requires the revision that you loaded.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "precondition.required", @@ -1087,7 +1163,7 @@ "description": "The selected Casework profile does not authorize this request.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "profile.not-authorized", @@ -1106,7 +1182,7 @@ "description": "This action is reserved for a human session.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "profile.not-human", @@ -1125,7 +1201,7 @@ "description": "The request body exceeds the one MiB limit.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "request.body-too-large", @@ -1144,7 +1220,7 @@ "description": "The Casework request is invalid.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "request.invalid", @@ -1163,7 +1239,7 @@ "description": "The limit query parameter must be from 1 to 100, or from 1 to 1000 on the directory absence list. Omit it for the default page size.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "request.limit-out-of-range", @@ -1182,7 +1258,7 @@ "description": "This route does not accept that HTTP method.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "request.method-not-allowed", @@ -1201,7 +1277,7 @@ "description": "The requested Casework route does not exist.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "request.not-found", @@ -1220,7 +1296,7 @@ "description": "The request body does not match the Casework contract.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "request.unprocessable", @@ -1239,7 +1315,7 @@ "description": "Send a JSON request body with Content-Type application/json.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "request.unsupported-media-type", @@ -1248,6 +1324,139 @@ ] } }, + { + "uri": "https://id.registrystack.org/problems/registry-casework/review/ask-already-open", + "kind": "problem", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "casework", + "title": "Review ask already open", + "description": "Wait for the open ask on this request to be answered or closed before asking again.", + "source": { + "path": "crates/registry-casework/src/problem.rs", + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" + }, + "problem": { + "code": "review.ask-already-open", + "httpStatuses": [ + 409 + ] + } + }, + { + "uri": "https://id.registrystack.org/problems/registry-casework/review/ask-answer-time-invalid", + "kind": "problem", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "casework", + "title": "Review ask answer time invalid", + "description": "Report the time the applicant's answer was committed: not before the ask was made and no more than five minutes ahead of Casework's clock.", + "source": { + "path": "crates/registry-casework/src/problem.rs", + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" + }, + "problem": { + "code": "review.ask-answer-time-invalid", + "httpStatuses": [ + 422 + ] + } + }, + { + "uri": "https://id.registrystack.org/problems/registry-casework/review/ask-limit-reached", + "kind": "problem", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "casework", + "title": "Review ask limit reached", + "description": "This review request has reached its limit of 50 asks. Continue the review without opening another ask.", + "source": { + "path": "crates/registry-casework/src/problem.rs", + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" + }, + "problem": { + "code": "review.ask-limit-reached", + "httpStatuses": [ + 409 + ] + } + }, + { + "uri": "https://id.registrystack.org/problems/registry-casework/review/ask-not-offered", + "kind": "problem", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "casework", + "title": "Review ask not offered", + "description": "The active stage of this review policy does not let a reviewer ask the applicant.", + "source": { + "path": "crates/registry-casework/src/problem.rs", + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" + }, + "problem": { + "code": "review.ask-not-offered", + "httpStatuses": [ + 409 + ] + } + }, + { + "uri": "https://id.registrystack.org/problems/registry-casework/review/ask-not-open", + "kind": "problem", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "casework", + "title": "Review ask not open", + "description": "This ask was already answered or closed, or the applicant answered after its due date.", + "source": { + "path": "crates/registry-casework/src/problem.rs", + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" + }, + "problem": { + "code": "review.ask-not-open", + "httpStatuses": [ + 409 + ] + } + }, + { + "uri": "https://id.registrystack.org/problems/registry-casework/review/ask-producer-unsupported", + "kind": "problem", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "casework", + "title": "Review ask producer unsupported", + "description": "The producer of this request does not read asks, so the reviewer cannot ask the applicant.", + "source": { + "path": "crates/registry-casework/src/problem.rs", + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" + }, + "problem": { + "code": "review.ask-producer-unsupported", + "httpStatuses": [ + 409 + ] + } + }, + { + "uri": "https://id.registrystack.org/problems/registry-casework/review/ask-task-inactive", + "kind": "problem", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "casework", + "title": "Review ask task inactive", + "description": "Ask from a task at the active stage of a request that is still under review.", + "source": { + "path": "crates/registry-casework/src/problem.rs", + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" + }, + "problem": { + "code": "review.ask-task-inactive", + "httpStatuses": [ + 409 + ] + } + }, { "uri": "https://id.registrystack.org/problems/registry-casework/review/distinct-approver-required", "kind": "problem", @@ -1258,7 +1467,7 @@ "description": "Each approval in this stage must be supplied by a different reviewer.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "review.distinct-approver-required", @@ -1277,7 +1486,7 @@ "description": "You submitted this request, and this review stage excludes the person who submitted it. Another reviewer must take it.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "review.initiator-excluded", @@ -1296,7 +1505,7 @@ "description": "This review policy excludes the person who submitted the request, so the request must name its initiator.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "review.initiator-required", @@ -1315,7 +1524,7 @@ "description": "The expected review policy binding does not match the active policy.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "review.policy-mismatch", @@ -1334,7 +1543,7 @@ "description": "Narrow the queue or exact subject query to complete it within the configured read budget.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "review.query-too-broad", @@ -1353,7 +1562,7 @@ "description": "The retained review result is no longer available. Reconcile through the producer's retained source correlation.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "review.result-expired", @@ -1372,7 +1581,7 @@ "description": "The same producer, source subject, version, and policy were already submitted with different canonical content.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "review.submission-conflict", @@ -1391,7 +1600,7 @@ "description": "Claim the review task before deciding it, and decide only while the claim remains current.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "review.task-not-held", @@ -1410,7 +1619,7 @@ "description": "Casework could not complete the request.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "runtime.failure", @@ -1429,7 +1638,7 @@ "description": "Casework storage is unavailable. Try again after the service recovers.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "service.unavailable", @@ -1448,7 +1657,7 @@ "description": "Omit the Registry-Source-Profile header for this request.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "source-profile.not-applicable", @@ -1467,7 +1676,7 @@ "description": "Send the Registry-Source-Profile header to select the source profile for this request.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "source-profile.required", @@ -1486,7 +1695,7 @@ "description": "The source returned a response that does not match its registered contract.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "source.bad-gateway", @@ -1505,7 +1714,7 @@ "description": "Deploy the same Registry Stack version for Casework and its source.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "source.version-mismatch", @@ -1524,7 +1733,7 @@ "description": "The source did not report its engine version. Deploy matching Registry Stack versions.", "source": { "path": "crates/registry-casework/src/problem.rs", - "sha256": "4b2bbc4f422cb051a24673c7cb496eecedb142fb3830442ee76b3d376f94ad10" + "sha256": "be58eef528abde414d32523a76b329645c485bd020ca0d4fddb8b9eb266c274c" }, "problem": { "code": "source.version-unavailable", @@ -4927,7 +5136,7 @@ "description": "Base Registry Engine portable Action contract export schema, reproduced from the canonical compiled project.", "source": { "path": "crates/registry-breg/src/artifacts.rs", - "sha256": "6484efc2473a2e10fe88a44e977f18bd5bd851e3937d21cac8487917b6e193ab" + "sha256": "44a9edbc848221d26d1c9c787b7261ce5933547310a1f54e13ea5306d582ad8c" }, "artifact": { "path": "products/breg/generated/facility/generated/action-contracts.schema.json", @@ -5062,20 +5271,20 @@ } }, { - "uri": "https://id.registrystack.org/schemas/breg/lifecycle-explanation/lifecycle-explanation.v1alpha8.schema.json", + "uri": "https://id.registrystack.org/schemas/breg/lifecycle-explanation/lifecycle-explanation.v1alpha9.schema.json", "kind": "schema", "status": "active", - "compatibilityLine": "v1alpha8", + "compatibilityLine": "v1alpha9", "owner": "breg", "title": "LifecycleExplanation", "description": "Base Registry Engine bregctl explain output JSON Schemas, written by hand and held to bregctl's output by its contract test.", "source": { "path": "products/breg/contracts/explain/LifecycleExplanation.schema.json", - "sha256": "738c5151b6085ee5a5da8d60334f70b179e740bc1af9cb2888325436c338d546" + "sha256": "56f3cb89b5feaa96796bcd575dc25776cd4251d58f4f6621e11676907838f952" }, "artifact": { "path": "products/breg/contracts/explain/LifecycleExplanation.schema.json", - "sha256": "738c5151b6085ee5a5da8d60334f70b179e740bc1af9cb2888325436c338d546", + "sha256": "56f3cb89b5feaa96796bcd575dc25776cd4251d58f4f6621e11676907838f952", "mediaType": "application/schema+json" } }, @@ -5165,7 +5374,7 @@ }, "artifact": { "path": "products/breg/generated/authoring/registry-module.schema.json", - "sha256": "5845c55619e88b733308991629e48ec5ada815271cdbece040a646f89beb34a6", + "sha256": "4731bfc5893e72e2dabc063fdf3d9faeebbdc24662b292dca78b1e4d4b16ce37", "mediaType": "application/schema+json" } }, @@ -5183,7 +5392,7 @@ }, "artifact": { "path": "products/breg/generated/authoring/registry-project.schema.json", - "sha256": "89dbe4abf09f4667c76ff5f18c68c2b64e79bba11d49b4ffe22e891fa794ed19", + "sha256": "0ed8b2887eb5d319810442e36934a7ac7da96f01284bdde90bab8c82c014e8dc", "mediaType": "application/schema+json" } }, @@ -5305,7 +5514,7 @@ "description": "Registry Casework fixture JSON Schema.", "source": { "path": "crates/registry-casework-core/src/schema.rs", - "sha256": "aae3e2891d651ad99989ae4720c08991d954c0f3232e194ec68d18e30642a711" + "sha256": "2dcc5d47d3082f719f8a37e4aceb9db3f87b1f2fa523b6243ec268d10b7cb994" }, "artifact": { "path": "products/casework/generated/fixture/fixture.schema.json", @@ -5323,7 +5532,7 @@ "description": "Registry Casework holiday set JSON Schema.", "source": { "path": "crates/registry-casework-core/src/schema.rs", - "sha256": "aae3e2891d651ad99989ae4720c08991d954c0f3232e194ec68d18e30642a711" + "sha256": "2dcc5d47d3082f719f8a37e4aceb9db3f87b1f2fa523b6243ec268d10b7cb994" }, "artifact": { "path": "products/casework/generated/holiday-set/holiday-set.schema.json", @@ -5341,11 +5550,11 @@ "description": "Registry Casework project JSON Schema.", "source": { "path": "crates/registry-casework-core/src/schema.rs", - "sha256": "aae3e2891d651ad99989ae4720c08991d954c0f3232e194ec68d18e30642a711" + "sha256": "2dcc5d47d3082f719f8a37e4aceb9db3f87b1f2fa523b6243ec268d10b7cb994" }, "artifact": { "path": "products/casework/generated/project/project.schema.json", - "sha256": "81ecfa33b288cab822fa9286b908e54fb641a297ee09a78e14bf3790c0b64b75", + "sha256": "d6cd27cf4dcd9672f83f8afa39637a2b26dd3bc51c17a17b3beba8c3b1bfb90c", "mediaType": "application/schema+json" } }, @@ -5363,7 +5572,7 @@ }, "artifact": { "path": "products/casework/contracts/cli/report.schema.json", - "sha256": "0b19dbf18c681a79ad2f4bca44b0645c8ca0cd164d4d502a32b0c50fe22813c3", + "sha256": "37589ef451a26bfb4dbdddcdd3dd578927079d7241fe5408791bbe178fe6d1a7", "mediaType": "application/schema+json" } }, diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 783bbe344d..28c07970b6 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -1275,17 +1275,17 @@ formats: audience: generated stability: unpromised current: - apiVersion: id.registrystack.org/formats/breg/lifecycle-explanation/v1alpha8 + apiVersion: id.registrystack.org/formats/breg/lifecycle-explanation/v1alpha9 kind: BRegLifecycleExplanation checkedBy: file: crates/registry-bregctl/src/lib.rs symbol: LIFECYCLE_EXPLANATION target: - apiVersion: id.registrystack.org/formats/breg/lifecycle-explanation/v1alpha8 + apiVersion: id.registrystack.org/formats/breg/lifecycle-explanation/v1alpha9 kind: BRegLifecycleExplanation schema: path: products/breg/contracts/explain/LifecycleExplanation.schema.json - id: https://id.registrystack.org/schemas/breg/lifecycle-explanation/lifecycle-explanation.v1alpha8.schema.json + id: https://id.registrystack.org/schemas/breg/lifecycle-explanation/lifecycle-explanation.v1alpha9.schema.json origin: hand-written differentialTest: crates/registry-bregctl/tests/explain_contract.rs reader: none