Files
MikrotikManager/backend/src/services/server-poll-journal.ts
T

279 lines
27 KiB
TypeScript

import { carryPollError } from "./server-poll-error-provenance.js"
import { serverPollMaintenancePublications } from "./server-poll-maintenance-groups.js"
import { SERVER_POLL_WALL_BUDGET_MS } from "./server-poll-limits.js"
import { isDeepStrictEqual } from "node:util"
import { encodeServerPollJournalAnchor, openServerPollJournalAnchor } from "./server-poll-journal-anchor.js"
import { z } from "zod"
import type { QueryConfig } from "pg"
import type { ServerPollDependencies, ServerPollPlan, ServerPollReceipt } from "./server-poll-execution.js"
import { SERVER_POLL_NATIVE_READS } from "./server-poll-execution-model.js"
import type { ProbeJournalConnections, ProbeJournalCrypto, ProbeJournalSql } from "./server-probe-journal.js"
import { PollStorageUnknown } from "./server-poll-storage.js"
import { PollStorageSpent, bindServerPollJournalAuthority, type ServerPollJournalStorage } from "./server-poll-storage-journal.js"
import { validateServerPollJournalReceipt, type ServerPollJournalStage } from "./server-poll-journal-validation.js"
const hash=z.string().regex(/^[a-f0-9]{64}$/),uuid=z.string().uuid(),actor=z.string().min(1).max(200).refine(v=>v.trim()===v&&!/[\x00-\x1f\x7f]/.test(v))
const base={ownerId:actor,executionId:uuid,issuedAt:z.number().int().nonnegative().safe(),expiresAt:z.number().int().positive().safe()}
const identitySchema=z.discriminatedUnion("kind",[
z.object({...base,kind:z.literal("mcp"),connectionId:uuid,credentialId:uuid,operationName:z.string().regex(/^[a-z][a-z0-9_.]{0,199}$/)}).strict(),
z.object({...base,kind:z.literal("rest"),requestId:actor,authentication:z.enum(["jwt","local"])}).strict(),
])
/** executionId must be the real mcp_operations.id or a trusted REST execution.
* REST identity comes from the accepted JWT/local request, never its JSON body. */
export type ServerPollJournalIdentity=z.infer<typeof identitySchema>
export function parseServerPollJournalIdentity(value:unknown):ServerPollJournalIdentity{return identitySchema.parse(value)}
export interface ServerPollJournalContext {identity:ServerPollJournalIdentity;plan:ServerPollPlan}
export interface ServerPollJournalDependencies {
/** Validate current owner, credential, policy generation, global scope, ALL
* affected servers, protections and cancellation before every SQL boundary. */
assertAuthority(context:Readonly<ServerPollJournalContext>):Promise<void>
/** Exactly the same private proof function supplied to the poll executor. */
executionProof:ServerPollDependencies["proof"]
connections?:ProbeJournalConnections
/** Opt-in bounded storage owns BEGIN, global quota lock, admission and COMMIT.
* Legacy fixture connectors and this owner are mutually exclusive. */
storage?:ServerPollJournalStorage
crypto?:ProbeJournalCrypto
now?:()=>number
/** A trusted execution deadline. Default is 180 seconds from construction. */
deadlineAt?:number
}
export class ServerPollJournalConflict extends Error {readonly automaticReplay=false;constructor(){super("Server poll journal identity, authority or immutable state mismatch; replay forbidden")}}
export class ServerPollJournalOutcomeUnknown extends Error {readonly automaticReplay=false;constructor(readonly requiresDurableQuarantine:boolean){super("Server poll journal outcome unknown; replay forbidden")}}
function must(value:unknown):asserts value {if(!value)throw new ServerPollJournalConflict()}
function createDefaultCrypto():ProbeJournalCrypto {
// A journal repeatedly authenticates its whole immutable prefix. Derive
// purpose keys once for THIS private batch instead of reopening the same
// key file for every historical stage. This caches no authority, generation,
// decrypted context, receipt or proof result; guard() remains fresh per SQL.
const signers=new Map<string,Promise<(value:string)=>string>>()
return {
async encrypt(value){return (await import("../modules/mcp/security.js")).encryptSecret(value)},
async decrypt(value){return (await import("../modules/mcp/security.js")).decryptSecret(value)},
async proof(domain,value){const s=await import("../modules/mcp/security.js");let signer=signers.get(domain);if(!signer){signer=s.privateFingerprinter("server-poll-journal-v1:"+domain);signers.set(domain,signer)};return (await signer)(s.fingerprint(value))},
}
}
const defaultConnections:ProbeJournalConnections={async connect(){const c=await (await import("../db/index.js")).pool.connect();return {query:async(text,values)=>{const query:QueryConfig&{query_timeout:number}={text,values,query_timeout:5000};return c.query<Record<string,unknown>>(query)},release:destroy=>c.release(destroy)}}}
export interface ServerPollJournal extends Pick<ServerPollDependencies,"claim"|"intent"|"acknowledge"|"complete"> {
/** Authenticates existing immutable evidence; never creates or resumes work. */
readExisting():Promise<ServerPollReceipt|undefined>
}
type Stage = ServerPollJournalStage
/** Append-only SQL journal, one independent transaction per durable boundary.
* No import starts SQL. Normal migration 0038 enrolls the inert schema. */
export function createSqlServerPollJournal(raw:ServerPollJournalContext,deps:ServerPollJournalDependencies):ServerPollJournal {
const context=structuredClone(raw),identity=identitySchema.parse(context.identity),plan=context.plan
context.identity=identity
uuid.parse(plan.request.receiptId);hash.parse(plan.bindingProof)
const epochPlan=plan.version===3||plan.version===4
must(epochPlan?hash.safeParse(plan.approvalProof).success:!Object.hasOwn(plan,"approvalProof"))
must(identity.expiresAt>identity.issuedAt&&(plan.version===1||plan.version===2||plan.version===3||plan.version===4)&&plan.requiresHuman===true&&plan.scope==="global"&&Number.isSafeInteger(plan.request.serverId)&&plan.request.serverId>0&&plan.maintenance.length<=2000&&plan.affectedServerIds.length<=1000&&plan.affectedServerIds.includes(plan.request.serverId)&&new Set(plan.affectedServerIds).size===plan.affectedServerIds.length&&plan.affectedServerIds.every(id=>Number.isSafeInteger(id)&&id>0)&&typeof deps.assertAuthority==="function"&&typeof deps.executionProof==="function")
let maintenance:ReturnType<typeof serverPollMaintenancePublications>
try{maintenance=serverPollMaintenancePublications(plan)}catch{throw new ServerPollJournalConflict()}
const codec=deps.crypto??createDefaultCrypto(),connections=deps.connections??defaultConnections,now=deps.now??Date.now
must(!(deps.storage&&deps.connections))
const deadlineAt=Math.min(identity.expiresAt,deps.deadlineAt??now()+SERVER_POLL_WALL_BUDGET_MS)
must(Number.isSafeInteger(deadlineAt)&&deadlineAt>now())
let poisoned=false
let executionStartProof:string|undefined
const firstProof=()=>{must(!epochPlan||executionStartProof);return executionStartProof??plan.beforeProof}
const ownedStorage=deps.storage?bindServerPollJournalAuthority(deps.storage,context,deps.assertAuthority):undefined
const local=()=>{must(!poisoned&&now()>=identity.issuedAt&&now()<deadlineAt);ownedStorage?.()}
const guard=async()=>{local();try{await deps.assertAuthority(structuredClone(context))}catch(error){throw carryPollError(new ServerPollJournalConflict(), error, "journal.auth")};local()}
const sqlGuard=async()=>{if(ownedStorage)local();else await guard()}
const acquire=async()=>{
let timeout:ReturnType<typeof setTimeout>|undefined,abandoned=false
const pending=connections.connect()
try{return await Promise.race([pending,new Promise<never>((_resolve,reject)=>{timeout=setTimeout(()=>{abandoned=true;reject(new ServerPollJournalConflict())},Math.max(1,Math.min(5000,deadlineAt-now())))})])}
finally{if(timeout)clearTimeout(timeout);if(abandoned)void pending.then(c=>c.release(true),()=>{})}
}
const seal=async(domain:string,value:unknown)=>{const proof=await codec.proof(domain,value);hash.parse(proof);return proof}
const contextProof=()=>seal("context",context)
const request=(receiptId:string,bindingProof=plan.bindingProof)=>must(receiptId===plan.request.receiptId&&bindingProof===plan.bindingProof)
const quarantine=async()=>{
// This is a NEW append-only uncertainty marker, never a retry of COMMIT or
// of the original intent/ACK/publication. Revoked authority cannot erase it.
let c:Awaited<ReturnType<ProbeJournalConnections["connect"]>>|undefined
try{c=await acquire();await c.query("BEGIN");await c.query("SET LOCAL statement_timeout='5000ms'");await c.query("/* poll-journal:quarantine */ INSERT INTO server_poll_quarantines(receipt_id,identity_kind,execution_id,context_proof) VALUES($1,$2,$3,$4) ON CONFLICT DO NOTHING",[plan.request.receiptId,identity.kind,identity.executionId,await contextProof()]);await c.query("COMMIT");return true}catch{return false}finally{c?.release(true)}
}
const validateTransaction=async(sql:ProbeJournalSql)=>{
await sql.query("/* poll-journal:lock */ SELECT pg_advisory_xact_lock(hashtextextended($1,0))",["server-poll-execution-v1:"+identity.kind+":"+identity.executionId])
await sql.query("/* poll-journal:lock */ SELECT pg_advisory_xact_lock(hashtextextended($1,0))",["server-poll-receipt-v1:"+plan.request.receiptId])
const servers=await sql.query("/* poll-journal:servers */ SELECT id,enabled FROM servers ORDER BY id LIMIT 1001");must(servers.rows.length<=1000&&isDeepStrictEqual(servers.rows.map(r=>Number(r.id)).sort((a,b)=>a-b),[...plan.affectedServerIds].sort((a,b)=>a-b))&&servers.rows.find(r=>Number(r.id)===plan.request.serverId)?.enabled===true)
if(identity.kind==="mcp"){
const owner=await sql.query(`/* poll-journal:owner */ SELECT o.id FROM mcp_operations o JOIN mcp_plans p ON p.id=o.plan_id AND p.connection_id=o.connection_id
JOIN mcp_connections c ON c.id=o.connection_id JOIN mcp_credentials k ON k.connection_id=c.id
WHERE o.id=$1 AND c.id=$2 AND c.owner_id=$3 AND k.id=$4 AND k.revoked_at IS NULL AND k.expires_at>clock_timestamp()
AND c.owner_valid_until>clock_timestamp() AND c.policy->>'status'='active' AND c.policy->>'mode'<>'observer'
AND (c.policy->>'expiresAt')::timestamptz>clock_timestamp() AND c.policy#>'{scope,serverIds}' @> $5::jsonb
AND c.policy#>>'{scope,allowGlobal}'='true'
AND c.policy#>'{scope,operationIds}' @> to_jsonb(ARRAY[$6::text]) AND p.operation_id=$6`,[identity.executionId,identity.connectionId,identity.ownerId,identity.credentialId,JSON.stringify(plan.affectedServerIds),identity.operationName]);must(owner.rows.length===1)
}
}
const transaction=async<T>(work:(sql:ProbeJournalSql)=>Promise<T>,phase:"claim"|"write"="write"):Promise<T>=>{
if(deps.storage){
await guard()
try{return await deps.storage.transaction(phase,async owner=>{
const sql:ProbeJournalSql={async query(text,values){await sqlGuard();const result=await owner.query(text,values);await sqlGuard();return result}}
await validateTransaction(sql);const result=await work(sql);await guard();return result
})}catch(error){
if(error instanceof PollStorageUnknown||error instanceof PollStorageSpent){poisoned=true;throw carryPollError(new ServerPollJournalOutcomeUnknown(!await deps.storage.quarantine()), error, "journal.tx")}
throw carryPollError(error instanceof ServerPollJournalConflict?error:new ServerPollJournalConflict(), error, "journal.tx")
}
}
await guard();let c:Awaited<ReturnType<ProbeJournalConnections["connect"]>>
try{c=await acquire()}catch{throw new ServerPollJournalConflict()}
let commitSent=false,committed=false,begun=false,destroy=false,released=false
const sql:ProbeJournalSql={async query(text,values){await guard();const result=await c.query(text,values);await guard();return result}}
try{
await sql.query("BEGIN");begun=true;await sql.query("SET LOCAL statement_timeout='5000ms'")
await validateTransaction(sql)
const result=await work(sql);await guard();commitSent=true;await c.query("COMMIT");committed=true;await guard();return result
}catch(error){
if(commitSent){poisoned=true;destroy=true;released=true;c.release(true);throw carryPollError(new ServerPollJournalOutcomeUnknown(!await quarantine()), error, "journal.tx")}
if(begun)try{await c.query("ROLLBACK")}catch{destroy=true}
throw carryPollError(error instanceof ServerPollJournalConflict?error:new ServerPollJournalConflict(), error, "journal.tx")
}finally{if(!released)c.release(destroy||!committed)}
}
const verifyAnchor=async(rows:Record<string,unknown>[],required=true)=>{
must(rows.length<=1&&(!required||rows.length===1))
if(rows.length){const r=rows[0];must(r.receipt_id===plan.request.receiptId&&r.identity_kind===identity.kind&&r.execution_id===identity.executionId&&r.binding_proof===plan.bindingProof&&r.context_proof===await contextProof());must(typeof r.context_ciphertext==="string"&&Buffer.byteLength(r.context_ciphertext)<=2097152);const text=await codec.decrypt(r.context_ciphertext);must(Buffer.byteLength(text)<=1048576);const start=await openServerPollJournalAnchor(JSON.parse(text),context,codec);must(!executionStartProof||executionStartProof===start);executionStartProof=start}
return rows[0]
}
const anchor=async(sql:ProbeJournalSql,required=true,readOnly=false)=>{
const blocked=await sql.query("/* poll-journal:blocked */ SELECT receipt_id FROM server_poll_quarantines WHERE receipt_id=$1 OR (identity_kind=$2 AND execution_id=$3) LIMIT 2",[plan.request.receiptId,identity.kind,identity.executionId]);must(!blocked.rows.length)
const rows=(await sql.query("/* poll-journal:anchor */ SELECT * FROM server_poll_executions WHERE receipt_id=$1 OR (identity_kind=$2 AND execution_id=$3)"+(readOnly?"":" FOR UPDATE"),[plan.request.receiptId,identity.kind,identity.executionId])).rows
return verifyAnchor(rows,required)
}
const terminal=async(sql:ProbeJournalSql)=>(await sql.query("/* poll-journal:terminal */ SELECT * FROM server_poll_receipts WHERE receipt_id=$1",[plan.request.receiptId])).rows
const verifyStages=async(rows:Stage[])=>{
must(rows.length<=maintenance.length+8)
for(const r of rows){must(r.intent_proof===await seal("intent",{receiptId:plan.request.receiptId,stage:r.stage,beforeProof:r.before_proof,effectProof:r.effect_proof}));if(r.ack_proof!==null)must(r.ack_proof===await seal("ack",{receiptId:plan.request.receiptId,stage:r.stage,resultProof:r.result_proof,outcome:r.outcome}))}
return rows
}
const stages=async(sql:ProbeJournalSql)=>verifyStages((await sql.query("/* poll-journal:stages */ SELECT i.*,a.result_proof,a.outcome,a.ack_proof FROM server_poll_intents i LEFT JOIN server_poll_acks a USING(receipt_id,stage) WHERE i.receipt_id=$1 ORDER BY i.stage LIMIT 2009",[plan.request.receiptId])).rows as Stage[])
// Only the existing private production storage owner proves that the global
// quota/admission locks already fence ALL normal writes, including quarantine.
// Preserve historical 0038 connector semantics rather than infer that fence.
const writeStages=async(sql:ProbeJournalSql)=>{
if(!ownedStorage){await anchor(sql);must(!(await terminal(sql)).length);return stages(sql)}
const result=(await sql.query(`/* poll-journal:write-snapshot */ WITH
blocked AS MATERIALIZED (
SELECT receipt_id FROM server_poll_quarantines WHERE receipt_id=$1 OR (identity_kind=$2 AND execution_id=$3) LIMIT 2
), locked_anchor AS MATERIALIZED (
SELECT e.* FROM server_poll_executions e WHERE (e.receipt_id=$1 OR (e.identity_kind=$2 AND e.execution_id=$3))
AND NOT EXISTS(SELECT 1 FROM blocked) FOR UPDATE OF e
), terminal_rows AS MATERIALIZED (
SELECT r.* FROM server_poll_receipts r WHERE r.receipt_id=$1 AND EXISTS(SELECT 1 FROM locked_anchor)
), stage_rows AS MATERIALIZED (
SELECT i.*,a.result_proof,a.outcome,a.ack_proof FROM server_poll_intents i LEFT JOIN server_poll_acks a USING(receipt_id,stage)
WHERE i.receipt_id=$1 AND EXISTS(SELECT 1 FROM locked_anchor) ORDER BY i.stage LIMIT 2009
) SELECT jsonb_build_object(
'blocked',COALESCE((SELECT jsonb_agg(to_jsonb(b)) FROM blocked b),'[]'::jsonb),
'anchors',COALESCE((SELECT jsonb_agg(to_jsonb(e)) FROM locked_anchor e),'[]'::jsonb),
'terminal',COALESCE((SELECT jsonb_agg(to_jsonb(r)) FROM terminal_rows r),'[]'::jsonb),
'stages',COALESCE((SELECT jsonb_agg(to_jsonb(s) ORDER BY s.stage) FROM stage_rows s),'[]'::jsonb)
) AS snapshot`,[plan.request.receiptId,identity.kind,identity.executionId])).rows
must(result.length===1)
const value=result[0].snapshot as Record<string,unknown>
must(value&&typeof value==='object'&&!Array.isArray(value)&&Array.isArray(value.blocked)&&Array.isArray(value.anchors)&&Array.isArray(value.terminal)&&Array.isArray(value.stages))
must(!value.blocked.length)
await verifyAnchor(value.anchors as Record<string,unknown>[])
must(!value.terminal.length)
return verifyStages(value.stages as Stage[])
}
const native=new Set(SERVER_POLL_NATIVE_READS.map(v=>"native."+v))
const publish=(rows:Stage[])=>rows.filter(r=>r.stage.startsWith("publish.")).sort((a,b)=>Number(a.stage.slice(8))-Number(b.stage.slice(8)))
const validateReceipt=(receipt:ServerPollReceipt,rows:Stage[])=>{
try { validateServerPollJournalReceipt(plan,receipt,rows,firstProof()) } catch { throw new ServerPollJournalConflict() }
}
const storedReceipt=async(sql:ProbeJournalSql)=>{
const receipts=await terminal(sql);must(receipts.length<=1)
if(!receipts.length)return undefined
const stored=receipts[0];must(typeof stored.receipt_ciphertext==="string"&&Buffer.byteLength(stored.receipt_ciphertext)<=262144)
const text=await codec.decrypt(stored.receipt_ciphertext);await guard()
must(Buffer.byteLength(text)<=131072&&stored.receipt_proof===await seal("receipt",text))
const receipt=JSON.parse(text) as ServerPollReceipt,rows=await stages(sql);validateReceipt(receipt,rows)
const pubs=publish(rows),offset=pubs.length-maintenance.length
for(let i=0;i<maintenance.length;i++)must(pubs[offset+i].effect_proof===await deps.executionProof(maintenance[i]))
await guard();return receipt
}
const readExisting=async():Promise<ServerPollReceipt|undefined>=>{
await guard()
const read=async(sql:ProbeJournalSql)=>{
await validateTransaction(sql)
if(!await anchor(sql,false,true))return undefined
return storedReceipt(sql)
}
if(deps.storage){
try{return await deps.storage.read(async owner=>{
const sql:ProbeJournalSql={async query(text,values){await sqlGuard();const result=await owner.query(text,values);await sqlGuard();return result}}
const result=await read(sql);await guard();return result
})}catch{throw new ServerPollJournalConflict()}
}
// Historical connector ownership: read-only work cannot admit, mutate or
// quarantine even if its final COMMIT acknowledgement is lost.
let c:Awaited<ReturnType<ProbeJournalConnections["connect"]>>|undefined
let active=true,busy=false,released=false,begun=false,commitSent=false,committed=false
const close=(unsafe:boolean)=>{if(c&&!released){released=true;c.release(unsafe)}}
const live=()=>must(active&&!released&&now()<deadlineAt)
let stop!:()=>void
const stopped=new Promise<never>((_yes,reject)=>{stop=()=>{active=false;close(true);reject(new ServerPollJournalConflict())}})
const timer=setTimeout(stop,Math.max(1,deadlineAt-now()))
const sql:ProbeJournalSql={async query(text,values){live();await guard();live();must(c&&!busy);busy=true;try{const result=await c.query(text,values);live();await guard();live();return result}finally{busy=false}}}
const completion=Promise.resolve().then(async()=>{
c=await acquire();if(!active){close(true);throw new ServerPollJournalConflict()}
await sql.query("BEGIN READ ONLY");begun=true;await sql.query("SET LOCAL statement_timeout='5000ms'")
const result=await read(sql);await guard();live();commitSent=true;await c.query("COMMIT");committed=true;await guard();live();return result
})
try{return await Promise.race([completion,stopped])}
catch{if(begun&&!commitSent&&active&&!busy&&c&&!released)try{await Promise.race([c.query("ROLLBACK"),stopped])}catch{/* Destroy below. */};throw new ServerPollJournalConflict()}
finally{active=false;clearTimeout(timer);close(!committed||busy)}
}
return {
readExisting,
async claim(value,bindingProof,rawStart){const start=rawStart?structuredClone(rawStart):undefined;must(epochPlan?start&&hash.safeParse(start.fullProof).success&&start.approvalProof===plan.approvalProof:start===undefined);request(value.receiptId,bindingProof);must(value.serverId===plan.request.serverId);const {bindingProof:binding,...core}=plan;must(binding===await deps.executionProof(core));return transaction(async sql=>{
const existing=await anchor(sql,false)
if(!existing){if(identity.kind==="mcp"){const active=await sql.query("/* poll-journal:active */ SELECT o.id FROM mcp_operations o JOIN mcp_plans p ON p.id=o.plan_id WHERE o.id=$1 AND o.state IN ('pending','running') AND p.state='executing'",[identity.executionId]);must(active.rows.length===1)};const text=await encodeServerPollJournalAnchor(context,start,codec);executionStartProof=start?.fullProof;must(Buffer.byteLength(text)<=1048576);const encrypted=await codec.encrypt(text);must(Buffer.byteLength(encrypted)<=2097152);const inserted=await sql.query("/* poll-journal:claim */ INSERT INTO server_poll_executions(receipt_id,identity_kind,execution_id,binding_proof,context_ciphertext,context_proof) VALUES($1,$2,$3,$4,$5,$6) RETURNING receipt_id",[value.receiptId,identity.kind,identity.executionId,bindingProof,encrypted,await contextProof()]);must(inserted.rows.length===1);return {state:"new" as const}}
const receipts=await terminal(sql);must(receipts.length<=1)
if(!receipts.length)return {state:"unresolved" as const,bindingProof}
const stored=receipts[0];must(typeof stored.receipt_ciphertext==="string"&&Buffer.byteLength(stored.receipt_ciphertext)<=262144);const text=await codec.decrypt(stored.receipt_ciphertext);must(Buffer.byteLength(text)<=131072&&stored.receipt_proof===await seal("receipt",text));const receipt=JSON.parse(text) as ServerPollReceipt;validateReceipt(receipt,await stages(sql));return {state:"known" as const,bindingProof,receipt}
},"claim")},
async intent(value){request(value.receiptId);hash.parse(value.beforeProof);hash.parse(value.effectProof);await transaction(async sql=>{const rows=await writeStages(sql);must(!rows.some(r=>r.stage===value.stage))
if(native.has(value.stage))must(rows.every(r=>native.has(r.stage))&&value.beforeProof===firstProof())
else {const pubs=publish(rows);must(value.stage==="publish."+pubs.length&&rows.filter(r=>native.has(r.stage)).length===4&&rows.every(r=>r.ack_proof!==null)&&pubs.length<maintenance.length+4&&value.beforeProof===(pubs.at(-1)?.result_proof??firstProof()))}
const result=await sql.query("/* poll-journal:intent */ INSERT INTO server_poll_intents(receipt_id,stage,before_proof,effect_proof,intent_proof) VALUES($1,$2,$3,$4,$5) RETURNING stage",[value.receiptId,value.stage,value.beforeProof,value.effectProof,await seal("intent",value)]);must(result.rows.length===1)
})},
async acknowledge(value){request(value.receiptId);hash.parse(value.resultProof);must(["confirmed","read-failed"].includes(value.outcome));await transaction(async sql=>{const rows=await writeStages(sql),stage=rows.find(r=>r.stage===value.stage);must(stage&&stage.ack_proof===null&&(native.has(value.stage)||value.outcome==="confirmed"));const inserted=await sql.query("/* poll-journal:ack */ INSERT INTO server_poll_acks(receipt_id,stage,result_proof,outcome,ack_proof) VALUES($1,$2,$3,$4,$5) RETURNING stage",[value.receiptId,value.stage,value.resultProof,value.outcome,await seal("ack",value)]);must(inserted.rows.length===1)})},
async complete(receipt,bindingProof){request(receipt.receiptId,bindingProof);await transaction(async sql=>{await anchor(sql);must(!(await terminal(sql)).length);const rows=await stages(sql);validateReceipt(receipt,rows);const pubs=publish(rows),offset=pubs.length-maintenance.length;for(let i=0;i<maintenance.length;i++)must(pubs[offset+i].effect_proof===await deps.executionProof(maintenance[i]));const text=JSON.stringify(receipt),encrypted=await codec.encrypt(text);must(Buffer.byteLength(encrypted)<=262144);const result=await sql.query("/* poll-journal:complete */ INSERT INTO server_poll_receipts(receipt_id,receipt_ciphertext,receipt_proof) VALUES($1,$2,$3) RETURNING receipt_id",[receipt.receiptId,encrypted,await seal("receipt",text)]);must(result.rows.length===1)})},
}
}
/** Exact fixed DDL enrolled by migration 0038; legacy owned fixtures use it
* separately. Public activation still requires bounded admission and retention. */
export const SERVER_POLL_JOURNAL_DDL=String.raw`
CREATE TABLE server_poll_executions (
receipt_id uuid PRIMARY KEY,identity_kind text NOT NULL CHECK(identity_kind IN ('mcp','rest')),execution_id uuid NOT NULL,
binding_proof text NOT NULL CHECK(binding_proof ~ '^[a-f0-9]{64}$'),context_ciphertext text NOT NULL CHECK(octet_length(context_ciphertext)<=2097152),
context_proof text NOT NULL CHECK(context_proof ~ '^[a-f0-9]{64}$'),created_at timestamptz NOT NULL DEFAULT clock_timestamp(),UNIQUE(identity_kind,execution_id));
CREATE TABLE server_poll_intents (
receipt_id uuid REFERENCES server_poll_executions(receipt_id),stage text NOT NULL CHECK(stage ~ '^(native\.(identity|resource|interfaces|addresses)|publish\.[0-9]{1,4})$'),
before_proof text NOT NULL CHECK(before_proof ~ '^[a-f0-9]{64}$'),effect_proof text NOT NULL CHECK(effect_proof ~ '^[a-f0-9]{64}$'),
intent_proof text NOT NULL CHECK(intent_proof ~ '^[a-f0-9]{64}$'),created_at timestamptz NOT NULL DEFAULT clock_timestamp(),PRIMARY KEY(receipt_id,stage));
CREATE TABLE server_poll_acks (
receipt_id uuid NOT NULL,stage text NOT NULL,result_proof text NOT NULL CHECK(result_proof ~ '^[a-f0-9]{64}$'),outcome text NOT NULL CHECK(outcome IN ('confirmed','read-failed')),
ack_proof text NOT NULL CHECK(ack_proof ~ '^[a-f0-9]{64}$'),created_at timestamptz NOT NULL DEFAULT clock_timestamp(),PRIMARY KEY(receipt_id,stage),FOREIGN KEY(receipt_id,stage) REFERENCES server_poll_intents(receipt_id,stage),CHECK(stage LIKE 'native.%' OR outcome='confirmed'));
CREATE TABLE server_poll_receipts (
receipt_id uuid PRIMARY KEY REFERENCES server_poll_executions(receipt_id),receipt_ciphertext text NOT NULL CHECK(octet_length(receipt_ciphertext)<=262144),receipt_proof text NOT NULL CHECK(receipt_proof ~ '^[a-f0-9]{64}$'),created_at timestamptz NOT NULL DEFAULT clock_timestamp());
CREATE TABLE server_poll_quarantines (
receipt_id uuid PRIMARY KEY,identity_kind text NOT NULL CHECK(identity_kind IN ('mcp','rest')),execution_id uuid NOT NULL,context_proof text NOT NULL CHECK(context_proof ~ '^[a-f0-9]{64}$'),created_at timestamptz NOT NULL DEFAULT clock_timestamp(),UNIQUE(identity_kind,execution_id));
CREATE FUNCTION server_poll_journal_immutable() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'server poll journal is append only'; END $$;
CREATE TRIGGER server_poll_execution_immutable BEFORE UPDATE OR DELETE ON server_poll_executions FOR EACH ROW EXECUTE FUNCTION server_poll_journal_immutable();
CREATE TRIGGER server_poll_intent_immutable BEFORE UPDATE OR DELETE ON server_poll_intents FOR EACH ROW EXECUTE FUNCTION server_poll_journal_immutable();
CREATE TRIGGER server_poll_ack_immutable BEFORE UPDATE OR DELETE ON server_poll_acks FOR EACH ROW EXECUTE FUNCTION server_poll_journal_immutable();
CREATE TRIGGER server_poll_receipt_immutable BEFORE UPDATE OR DELETE ON server_poll_receipts FOR EACH ROW EXECUTE FUNCTION server_poll_journal_immutable();
CREATE TRIGGER server_poll_quarantine_immutable BEFORE UPDATE OR DELETE ON server_poll_quarantines FOR EACH ROW EXECUTE FUNCTION server_poll_journal_immutable();
`