From 88ae1ea71e4a4cd6df324288e28923e61952e6ec Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 10 Nov 2026 13:16:08 -0600 Subject: [PATCH] test: exercise Dot through owned Linux runtime and physical App restart --- .../dot-hosted-useful.postgres.test.ts | 524 ++++++++++-------- .../helpers/owned-linux/checkpointed-fault.ts | 52 ++ .../helpers/owned-linux/child-client.ts | 31 ++ .../helpers/owned-linux/child-observation.ts | 95 ++++ .../owned-linux/committed-reply-loss.ts | 76 +++ .../owned-linux/linux-command-relay.mjs | 81 +++ .../owned-linux/linux-process-custody.mjs | 95 ++++ .../owned-linux/linux-runner-ingress.mjs | 44 ++ .../helpers/owned-linux/normal-app-child.ts | 67 +++ .../owned-linux/normal-app-generation.ts | 133 +++++ .../normal-distribution-bootstrap.ts | 49 ++ .../owned-linux/normal-runtime-composition.ts | 31 ++ .../helpers/owned-linux/owned-bulk-sync.ts | 88 +++ .../owned-linux/owned-docker-resource.mjs | 165 ++++++ .../owned-provider-implementation.mjs | 150 +++++ .../helpers/owned-linux/owned-wss-gateway.mjs | 90 +++ .../helpers/owned-linux/package-template.json | 10 + .../helpers/owned-linux/physical-app-owner.ts | 66 +++ .../helpers/owned-linux/private-ca-scope.ts | 36 ++ .../owned-linux/qualification-manifest.ts | 32 ++ .../owned-linux/qualification-provider.ts | 62 +++ .../useful-after-physical-restart.ts | 113 ++++ .../__tests__/helpers/owned-linux/worker.mjs | 9 + 23 files changed, 1862 insertions(+), 237 deletions(-) create mode 100644 server/src/__tests__/helpers/owned-linux/checkpointed-fault.ts create mode 100644 server/src/__tests__/helpers/owned-linux/child-client.ts create mode 100644 server/src/__tests__/helpers/owned-linux/child-observation.ts create mode 100644 server/src/__tests__/helpers/owned-linux/committed-reply-loss.ts create mode 100644 server/src/__tests__/helpers/owned-linux/linux-command-relay.mjs create mode 100644 server/src/__tests__/helpers/owned-linux/linux-process-custody.mjs create mode 100644 server/src/__tests__/helpers/owned-linux/linux-runner-ingress.mjs create mode 100644 server/src/__tests__/helpers/owned-linux/normal-app-child.ts create mode 100644 server/src/__tests__/helpers/owned-linux/normal-app-generation.ts create mode 100644 server/src/__tests__/helpers/owned-linux/normal-distribution-bootstrap.ts create mode 100644 server/src/__tests__/helpers/owned-linux/normal-runtime-composition.ts create mode 100644 server/src/__tests__/helpers/owned-linux/owned-bulk-sync.ts create mode 100644 server/src/__tests__/helpers/owned-linux/owned-docker-resource.mjs create mode 100644 server/src/__tests__/helpers/owned-linux/owned-provider-implementation.mjs create mode 100644 server/src/__tests__/helpers/owned-linux/owned-wss-gateway.mjs create mode 100644 server/src/__tests__/helpers/owned-linux/package-template.json create mode 100644 server/src/__tests__/helpers/owned-linux/physical-app-owner.ts create mode 100644 server/src/__tests__/helpers/owned-linux/private-ca-scope.ts create mode 100644 server/src/__tests__/helpers/owned-linux/qualification-manifest.ts create mode 100644 server/src/__tests__/helpers/owned-linux/qualification-provider.ts create mode 100644 server/src/__tests__/helpers/owned-linux/useful-after-physical-restart.ts create mode 100644 server/src/__tests__/helpers/owned-linux/worker.mjs diff --git a/server/src/__tests__/dot-hosted-useful.postgres.test.ts b/server/src/__tests__/dot-hosted-useful.postgres.test.ts index eda128f975b..1e11a9e212c 100644 --- a/server/src/__tests__/dot-hosted-useful.postgres.test.ts +++ b/server/src/__tests__/dot-hosted-useful.postgres.test.ts @@ -1,8 +1,9 @@ -import { registerNativeCancellationDelivery } from "../services/native-runtime/native-cancellation-delivery.js"; -import { registerNativeRuntimeResponseDelivery } from "../services/native-runtime/native-runtime-response-delivery.js"; -import { registerNativeCleanupReleaseWake } from "../services/native-runtime/native-cleanup-release-wake.js"; -import { registerCostAccountingWork, registerBudgetEnforcementWork } from "../services/budget-enforcement-worker.js"; -import { deliverBudgetResumeContinuations, type BudgetResumeDelivery } from "../services/budget-resume-continuation.js"; +import { forkNormalDotApp } from "./helpers/owned-linux/physical-app-owner.js"; +import { attachDotChild, type ChildSnapshot } from "./helpers/owned-linux/child-client.js"; +import { usefulAfterPhysicalRestart } from "./helpers/owned-linux/useful-after-physical-restart.js"; +import { nativeProviderRecoveryEvidence } from "../services/native-runtime/native-session-executor.js"; +import { stopCheckpointedOwnedRun } from "./helpers/owned-linux/checkpointed-fault.js"; +import { beginOwnedPrivateCA } from "./helpers/owned-linux/private-ca-scope.js"; import { z } from "zod"; import { mcpClientMirrorGeneration, mcpClientMirrorReceiptSchema } from "../services/public-mcp/client-mirror-contract.js"; import { HttpError } from "../errors.js"; @@ -10,26 +11,20 @@ import type { EventFetch } from "../services/public-mcp/event-webhooks.js"; import { DEVICE_GRANT } from "../services/public-mcp/oauth.js"; import { issueService } from "../services/issues.js"; import { documentService } from "../services/documents.js"; -import { heartbeatService } from "../services/heartbeat.js"; -import { setupRunnerPrpWebSocketServer } from "../realtime/runner-prp-ws.js"; -import { resolveLocalRuntimeApiUrl } from "../runtime-api.js"; -import { configuredPaperclipApiBaseUrl } from "../services/heartbeat/run-preparation.js"; import { idleWorkSnapshot, isIdleTaskDrainActive } from "../services/task-admission.js"; -import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; import { readIdleMcpSleepProof } from "../services/public-mcp/idle-sleep-proof.js"; import { externalOperationDigest } from "../vendor/paperclip-runner/index.js"; import { createHash, createHmac, generateKeyPairSync, randomBytes, randomUUID } from "node:crypto"; import { createServer, request as nodeRequest, type Server, type IncomingMessage, type ServerResponse } from "node:http"; import { once } from "node:events"; -import { mkdtemp, mkdir, writeFile, access } from "node:fs/promises"; +import { mkdtemp, mkdir, writeFile, access, readFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; -import type express from "express"; import request from "supertest"; import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; -import { applyPendingMigrations, createDb, closeRegisteredClients, authUsers, companies, mcpOauthGrants, agents, dotAgentBindings, dotRunnerAssignments, dotRunnerOperations, mcpOauthRequests, mcpOauthTokens, mcpOauthClientChanges, mcpOauthClientMirrorState, mcpOauthDeviceRequests, heartbeatRuns, agentWakeupRequests, completionContracts, nativeRunResults, issues, mcpEventDeliveries, mcpEventSubscriptions } from "@paperclipai/db"; +import { applyPendingMigrations, createDb, closeRegisteredClients, authUsers, companies, mcpOauthGrants, agents, dotAgentBindings, dotRunnerAssignments, dotRunnerOperations, mcpOauthRequests, mcpOauthTokens, mcpOauthClientChanges, mcpOauthClientMirrorState, mcpOauthDeviceRequests, heartbeatRuns, agentWakeupRequests, completionContracts, nativeRunResults, nativeRunFinalizations, issues, mcpEventDeliveries, mcpEventSubscriptions } from "@paperclipai/db"; import { resolveExternalTestDatabaseUrl } from "../lib/dedicated-test-database-url.js"; import { accessService } from "../services/access.js"; import { instanceSettingsService } from "../services/instance-settings.js"; @@ -111,7 +106,42 @@ const closedUnavailable=(response:{status:number;body:unknown;text?:string;heade const listen=async(server:Server)=>{server.listen(0,"127.0.0.1");await once(server,"listening");const address=server.address();if(!address||typeof address==="string")throw new Error("Missing owned principal listener");return `http://127.0.0.1:${address.port}`;}; const close=async(server:Server|undefined)=>{if(!server?.listening)return;await new Promise((resolve,reject)=>server.close(error=>error?reject(error):resolve()));}; describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device/subscription and genuine useful Retry",()=>{ - let db:ReturnType,app:express.Express|undefined,home:string,cloudServer:Server|undefined,appServer:Server|undefined; + let physicalApp:Awaited>|undefined; + let childControl:ReturnType|undefined; + let childSnapshot:ChildSnapshot|undefined; + const retiredChildren:ChildSnapshot[]=[]; + const physicalOwners:Array>>=[]; + const knownChildProcesses:Array<{child:import("node:child_process").ChildProcess;owner:ReturnType}>=[]; + let physicalFollowon:Awaited>|undefined; + let activeCaseDeadline:number|undefined,setupDeadline=0; + const childDeadline=()=>Math.min(activeCaseDeadline??Infinity,performance.now()+15_000); + const syncChildObservation=async(deadline=childDeadline())=>{ + if(!childControl)throw new Error("Missing actual child owner"); + const snapshot=await childControl.request({command:"snapshot"},deadline);childSnapshot=snapshot; + expect(childControl.snapshot()).toEqual({pending:0,failures:0}); + const all=[...retiredChildren,snapshot]; + authenticateCalls=all.reduce((sum,value)=>sum+value.database.authenticateCalls,0); + sessionCalls=all.reduce((sum,value)=>sum+value.owner.sessionCalls,0); + unexpectedDecisionWakes=all.reduce((sum,value)=>sum+value.owner.unexpectedDecisionWakes,0); + eventTransportCounts.factoryOwners=all.reduce((sum,value)=>sum+value.database.eventFactoryOwners,0); + eventTransportCounts.authorityRequests=all.reduce((sum,value)=>sum+value.database.authorityRequests,0); + eventTransportCounts.callbackRequests=all.reduce((sum,value)=>sum+value.database.callbackRequests,0); + eventTransportCounts.unexpected=all.reduce((sum,value)=>sum+value.database.unexpectedEventRequests,0); + pendingDeviceAckCheckObservers=snapshot.database.observerPending; + pendingDeviceObservers=snapshot.database.observerPending;deviceObserverFailures=snapshot.database.observerFailures; + if(snapshot.database.overflow!==0)throw new Error("Child observer overflow invalidates attribution"); + readinessStatuses.splice(0,readinessStatuses.length,...snapshot.owner.healthStatuses);readinessOverflow=snapshot.owner.healthOverflow; + return snapshot; + }; + const setChildDeviceStage=async(value:"first-select"|"retry-select"|"none")=>{ + if(!childControl)throw new Error("Missing actual child owner"); + await childControl.request({command:"device-stage",value},childDeadline()); + }; + const setChildHealth=async(value:"ready"|"unavailable"|"wake-once-then-unavailable")=>{ + if(!childControl)throw new Error("Missing actual child owner"); + await childControl.request({command:"health",value},childDeadline()); + }; + let db:ReturnType,home:string,cloudServer:Server|undefined; let cloudService:{handler:(req:IncomingMessage,res:ServerResponse)=>unknown;stopBackgroundTasks:()=>void}|undefined,restoreOAuth:(()=>void)|undefined,restoreEventFactory:(()=>void)|undefined; let signer:{publicJwks:string;signClaim:(input:{stackId:string;claimId:string;previousOrigin:string;canonicalOrigin:string;stackSlug:string})=>string;signControlAssertion:(input:{stackId:string;action:"mcp-dot:principal"|"task-drain:start"|"task-drain:read"|"task-drain:stop";requestId:string})=>string}; let registry:Registry,connectorStore:Instances,CloudStackRouter:Router,metadataCompany:(id:string)=>string; @@ -119,12 +149,11 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device const userId=randomUUID(),operatorId=userId,companyId=randomUUID(),otherCompanyId=randomUUID(),instanceId="inst_"+randomUUID(); let agentId="",serial=0,callback:Server|undefined,callbackOrigin="",customerCookie=""; - let heartbeat:ReturnType|undefined; - let dispatchWork:ReturnType["registerRunDispatchWork"]>|undefined; - let stopBudgetOwners:(()=>Promise)|undefined; - const nativeSockets=new Set(),callbacks:Array<{id:string;at:number;kind?:string}>=[],errors:unknown[]=[]; + let restoreLinuxCA:(()=>void)|undefined; + let linuxInput:{catalogRoot:string;prebuiltPackageRoot:string;expectedBundleDigest:string;providerRoot:string;remoteBinary:string;caBundle:string;caSHA256:string}; + const callbacks:Array<{id:string;at:number;kind?:string}>=[],errors:unknown[]=[]; let failures=1,unexpectedDecisionWakes=0; - let reconstructCloudOwner:()=>Promise,reconstructAppOwner:()=>Promise; + let reconstructCloudOwner:()=>Promise,makePhysicalSecond:()=>Promise; const controlledMasterKeys=new Map(); let cloudOwnerGenerations=0,appOwnerGenerations=0; const ownedTenantOrigins=new Set([origin]); @@ -236,17 +265,9 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device const callbackSecret="whsec_"+randomBytes(32).toString("base64"); // server.close's callback and each accepted Socket's close event are distinct // ownership signals. Join both without destroying or forgetting a socket. - const closeAppTransport=async()=>{ - const socketJoins=Promise.all([...nativeSockets].map(socket=>once(socket,"close"))); - await Promise.all([close(appServer),socketJoins]); - // The server close barrier ends acceptance. Include any connection delivered - // during that close whose synchronous Set-delete listener has not run yet. - await Promise.all([...nativeSockets].map(socket=>once(socket,"close"))); - expect(nativeSockets.size).toBe(0); - }; const pause=(ms:number)=>new Promise(resolve=>setTimeout(resolve,ms)); const host=new URL(origin).host; - const boardPost=(target:string)=>request(app!).post(target).set("Host",host).set("Origin",origin); + const boardPost=(target:string)=>request(appLoopback).post(target).set("Host",host).set("Origin",origin); const cloudCall=(target:string,body?:Record,browser=false,accessToken?:string)=>{ if(!cloudServer)throw new Error("Missing normal Cloud listener"); const call=body===undefined?request(cloudServer).get(target):request(cloudServer).post(target).send(body); @@ -313,7 +334,7 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device }); } - beforeAll(async()=>{ + beforeAll(async()=>{setupDeadline=performance.now()+90_000; const checkout=process.env.PAPERCLIP_DOT_PRINCIPAL_CLOUD_CHECKOUT;if(!checkout||!path.isAbsolute(checkout))throw new Error("Explicit own compiled current Cloud checkout required"); const load=(name:string)=>import(pathToFileURL(path.join(checkout,"dist",name)).href); const [runtime,postgresRegistry,provisioner,fake,stackSecrets,providers,service,routing,identity,wakeReadiness]=await Promise.all([ @@ -372,93 +393,12 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device vi.stubEnv("PAPERCLIP_PUBLIC_URL",origin);vi.stubEnv("PAPERCLIP_AUTH_PUBLIC_BASE_URL",origin);vi.stubEnv("PAPERCLIP_API_URL",origin);vi.stubEnv("PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS",publicJwks); vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_INSTANCE_ID",instanceId);vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT","test");vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_BASE_URL",cloudOrigin);vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY",sign.privateKey.export({format:"jwk"}).d!);vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_SEAL_PRIVATE_KEY",seal.privateKey.export({format:"jwk"}).d!); await applyPendingMigrations(url!); - const eventsModule=await import("../services/public-mcp/events.js"),createEvents=eventsModule.createPublicMcpEvents; - const eventsSpy=vi.spyOn(eventsModule,"createPublicMcpEvents").mockImplementation((queryDb,oauth,dispatch,options)=>{ - if(options?.enableDotRunner!==true||oauth.mode!=="openai_dot_agent"||oauth.config.resource!==resource)return createEvents(queryDb,oauth,dispatch,options); - eventTransportCounts.factoryOwners++;return createEvents(queryDb,oauth,dispatch,{...options,fetch:eventTransport}); - });restoreEventFactory=()=>eventsSpy.mockRestore(); - const deviceCutover=await import("../services/public-mcp/device-cutover.js"),actualDeviceAckCheck=deviceCutover.assertDotDeviceProfileAck; - const ackCheckSpy=vi.spyOn(deviceCutover,"assertDotDeviceProfileAck").mockImplementation((...input)=>{ - const phase=deviceStage,originalPromise=actualDeviceAckCheck(...input); - if(phase){ - if(deviceAckChecks.length>=16){deviceWireOverflow++;return originalPromise;} - const record:typeof deviceAckChecks[number]={stage:phase,result:"pending"};deviceAckChecks.push(record);pendingDeviceAckCheckObservers++; - void originalPromise.then(()=>{record.result="fulfilled";},error=>{record.result=error instanceof HttpError&&error.status===503&&error.message==="The hosted Dot connection is being reconciled."?"current-ack-denial":"other";}).finally(()=>{pendingDeviceAckCheckObservers--;}); - } - return originalPromise; - }); - const createOAuth=oauthModule.createPublicMcpOAuth;const spy=vi.spyOn(oauthModule,"createPublicMcpOAuth").mockImplementation((...args)=>{const owner=createOAuth(...args);if(owner.mode==="openai_dot_agent"){const original=owner.authenticate;owner.authenticate=token=>{authenticateCalls++;return original.call(owner,token);}; - const register=owner.register;owner.register=(...input)=>{ - const observe=holdDeviceMirrorAck;if(deviceStage)actualDeviceRegistrationCalls++; - const originalPromise=register.apply(owner,input); - if(observe){ - pendingDeviceObservers++; - void originalPromise.then(async value=>{ - try{ - actualDeviceClientId=value.client_id; - const [change]=await db.select({revision:mcpOauthClientChanges.revision}).from(mcpOauthClientChanges).where(eq(mcpOauthClientChanges.clientId,value.client_id)); - if(!change||!Number.isSafeInteger(change.revision)||change.revision<=deviceAckBaselineRevision)throw new Error("Actual DCR revision was not retained"); - deviceAckTargetRevision=change.revision;resolveDeviceAckTarget?.(change.revision); - }catch{deviceObserverFailures++;resolveDeviceAckTarget?.(undefined);}finally{pendingDeviceObservers--;} - },()=>{pendingDeviceObservers--;deviceObserverFailures++;resolveDeviceAckTarget?.(undefined);}); - } - return originalPromise; - };}return owner;});restoreOAuth=()=>{spy.mockRestore();ackCheckSpy.mockRestore();}; - const makeAppOwner=async()=>{ - db=createDb(url!,{maxConnections:2,applicationName:"dot-principal-normal-app"});await migrateCloudConfiguration(db);await initializeAdapterSettings(db);await initializeCloudRuntimeConfig(db);resetCloudRuntimeIdentityForTests();resetCloudControlReplayFenceForTests();await initializeCloudRuntimeIdentity(db); - const standby=await createCloudWarmStandby(db);expect(standby()).toBe(appOwnerGenerations===0); - const {createApp}=await import("../app.js"); - const budgetResumeDelivery:BudgetResumeDelivery={}; - app=await createApp(db,{budgetResumeDelivery,uiMode:"none",serverPort:3100,storageService:createStorageService(createLocalDiskStorageProvider(path.join(home,"objects"))),deploymentMode:"authenticated",deploymentExposure:"private",bindHost:"127.0.0.1",allowedHostnames:[new URL(origin).hostname],authPublicBaseUrl:origin,authReady:true,companyDeletionEnabled:false,managedPluginAutoInstall:[],cloudWarmStandby:standby,decisionServiceOptions:{wakeOriginAgent:async()=>{unexpectedDecisionWakes++;throw new Error("Unexpected Decision dependency in closed Dot journey");}},resolveSession:async req=>{sessionCalls++;if(req.get("x-selected-operator")!==userId)return null;const [user]=await db.select().from(authUsers).where(eq(authUsers.id,userId));return user?{session:{id:"principal-hop-session",userId},user}:null;}}); - await app.locals.bundledPluginsStartup;const actualApp=app;appServer=createServer((req,res)=>{observeInbound("tenant",req,res);if(req.method==="GET"&&(req.url??"").split("?",1)[0]==="/api/health"&&healthAvailability!=="ready"){ - if(readinessStatuses.length<32){res.once("finish",()=>{readinessStatuses.push(res.statusCode);});}else readinessOverflow++; - if(healthAvailability==="wake-once-then-unavailable")healthAvailability="unavailable"; - else {res.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({status:"unavailable"}));return;} - }actualApp(req,res);}); - appServer.on("connection",socket=>{nativeSockets.add(socket);socket.once("close",()=>nativeSockets.delete(socket));});setupRunnerPrpWebSocketServer(appServer);appLoopback=await listen(appServer); - vi.stubEnv("PAPERCLIP_API_URL",appLoopback);vi.stubEnv("PAPERCLIP_RUNTIME_API_URL",appLoopback);vi.stubEnv("PAPERCLIP_LISTEN_HOST","127.0.0.1");vi.stubEnv("PAPERCLIP_LISTEN_PORT",new URL(appLoopback).port); - const coordinator:ReturnType=app!.locals.deliveryWork; - if(!coordinator||typeof coordinator.register!=="function")throw new Error("Missing normal App delivery owner"); - const owner=heartbeatService(db);heartbeat=owner; - const canRun=()=>!isIdleTaskDrainActive()&&!standby(); - dispatchWork=owner.registerRunDispatchWork(coordinator,canRun);await dispatchWork.ready; - registerNativeCancellationDelivery(db,coordinator);registerNativeRuntimeResponseDelivery(db,coordinator); - const release=registerNativeCleanupReleaseWake(db,error=>{errors.push(error);});appServer!.once("close",release); - await owner.registerDeferredReceiptWork(coordinator,canRun).ready; - await owner.registerScheduledRetryCancellationWork(coordinator,canRun).ready; - await owner.registerCapturedInstructionCommitWork(coordinator,canRun).ready; - await owner.registerInstructionDirectoryCleanupWork(coordinator,canRun).ready; - await owner.registerNativeWorkspaceFinalizationWork(coordinator,canRun).ready; - await owner.registerRetainedNativeSessionCleanupWork(coordinator,canRun).ready; - await owner.registerExternalConversationSettlementWork(coordinator,canRun).ready; - await owner.registerNativeRecoveryNoticeWork(coordinator,canRun).ready; - await owner.registerNativeEnvironmentSettlementWork(coordinator,canRun).ready; - await owner.registerNativeRunProjectionWork(coordinator,canRun).ready; - await owner.registerNativeResultCommitWork(coordinator,canRun).ready; - await owner.registerNativeStatusReassessmentWork(coordinator,canRun).ready; - await owner.registerNativeReviewResponseWork(coordinator,canRun).ready; - await owner.registerNativeResponsePresentationWork(coordinator,canRun).ready; - await owner.registerNativePendingEffectWork(coordinator,canRun).ready; - await owner.registerUnsafeWorkspaceExportWork(coordinator,canRun).ready; - await owner.registerAutomaticCompletionReviewWork(coordinator,canRun).ready; - await owner.registerObsoletePolicyReviewWork(coordinator,canRun).ready; - await owner.registerCancelledWorkspacePreservationWork(coordinator,canRun).ready; - await owner.registerStoppedInstructionCollectionWork(coordinator,canRun).ready; - const enforcement=registerBudgetEnforcementWork(db,coordinator,{cancelWorkForScope:owner.cancelBudgetScopeWork, - deliverResumeContinuations:()=>deliverBudgetResumeContinuations(db,{...budgetResumeDelivery,resumeTaskRetry:(company,request)=>owner.resumeTaskRetry(company,request)})}); - const accounting=registerCostAccountingWork(db,coordinator,owner.reconcileCostAccounting); - stopBudgetOwners=async()=>{try{await enforcement.stop();}finally{await accounting.stop();}}; - await enforcement.ready;await accounting.ready; - appOwnerGenerations++; - }; - await makeAppOwner(); - reconstructAppOwner=async()=>{ - await dispatchWork?.stop();if(heartbeat){await heartbeat.stopInvocationsForAgents([agentId],"Normal hosted owner reconstruction");await heartbeat.drainActiveRunExecutions();} - await stopBudgetOwners?.();await app?.locals.paperclipShutdown?.();await closeAppTransport(); - await db.$client.end({timeout:1});await closeRegisteredClients(url!,{scope:"database"}); - await makeAppOwner(); - vi.stubEnv("PAPERCLIP_API_URL",appLoopback);vi.stubEnv("PAPERCLIP_RUNTIME_API_URL",appLoopback);vi.stubEnv("PAPERCLIP_LISTEN_PORT",new URL(appLoopback).port); - }; + const linuxInputFile=process.env.PAPERCLIP_DOT_LINUX_RUNTIME_INPUT; + if(!linuxInputFile||!path.isAbsolute(linuxInputFile))throw new Error("Explicit owned Linux runtime input required"); + const absolute=z.string().refine(value=>path.isAbsolute(value)); + linuxInput=z.object({catalogRoot:absolute,prebuiltPackageRoot:absolute,expectedBundleDigest:z.string().regex(/^sha256:[a-f0-9]{64}$/),providerRoot:absolute,remoteBinary:absolute,caBundle:absolute,caSHA256:z.string().regex(/^[a-f0-9]{64}$/)}).strict().parse(JSON.parse(await readFile(linuxInputFile,"utf8"))); + restoreLinuxCA=beginOwnedPrivateCA({pem:await readFile(linuxInput.caBundle,"utf8"),SHA256:linuxInput.caSHA256}); + vi.stubEnv("PAPERCLIP_RUNNER_REMOTE_BINARY_PATH",linuxInput.remoteBinary); callback=createServer(async(req,res)=>{ try{ const parts:Buffer[]=[];let length=0;for await(const chunk of req){length+=Buffer.byteLength(chunk);if(length>1_048_576)throw new Error("Bounded callback body exceeded");parts.push(Buffer.from(chunk));} @@ -468,23 +408,60 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device expect(body.data).not.toHaveProperty("challenge");callbacks.push({id,at:Date.now(),kind:body.data?.kind});res.writeHead(failures-->0?500:204).end(); }catch(error){errors.push(error);res.writeHead(500).end();} });callbackOrigin=await listen(callback); + const makeAppOwner=async()=>{ + db=createDb(url!,{maxConnections:2,applicationName:"dot-principal-parent-observer"}); + // Parent observer has no delivery/Native/plugin owner. These normal setup + // writes happen BEFORE generation1 starts, so both process snapshots read + // the same persisted authorized fixture configuration. + if(appOwnerGenerations===0){await migrateCloudConfiguration(db);await initializeAdapterSettings(db);await initializeCloudRuntimeConfig(db);} + const generation=appOwnerGenerations+1; + const inputFile=path.join(home,`dot-child-generation-${generation}.json`); + await writeFile(inputFile,JSON.stringify({stackId,databaseUrl:url,home,origin,userId,companyId,generation,resource, + cloudOrigin,cloudLoopback,callbackPublicOrigin,callbackLoopback:callbackOrigin,linuxInput}),{mode:0o600,flag:"wx"}); + const closedEnv=Object.fromEntries(Object.entries(process.env).filter(([key,value])=>value!==undefined&& + (key.startsWith("PAPERCLIP_")||["PATH","HOME","TMPDIR","LANG","TZ","NODE_OPTIONS","NODE_EXTRA_CA_CERTS"].includes(key)))) as Record; + closedEnv.PAPERCLIP_DOT_CHILD_INPUT=inputFile; + physicalApp=await forkNormalDotApp({entry:new URL("./helpers/owned-linux/normal-app-child.ts",import.meta.url), + nodeExecutable:process.execPath,normalTsxImport:new URL("../../node_modules/tsx/dist/loader.mjs",import.meta.url), + cwd:process.cwd(),closedEnv,setupDeadline:activeCaseDeadline??setupDeadline, + registerActualChild:(child,owner)=>{ + knownChildProcesses.push({child,owner}); + childControl=attachDotChild(child,event=>{ + if(event.kind==="dcr-committed"){ + actualDeviceRegistrationCalls++;actualDeviceClientId=z.string().min(1).parse(event.clientId); + const revision=z.number().int().positive().parse(event.revision); + if(holdDeviceMirrorAck){deviceAckTargetRevision=revision;resolveDeviceAckTarget?.(revision);} + }else if(event.kind==="ack-check"){ + if(deviceAckChecks.length>=16){deviceWireOverflow++;return;} + deviceAckChecks.push(z.object({stage:z.enum(["first-select","retry-select"]),result:z.enum(["fulfilled","current-ack-denial","other"])}).parse(event)); + }else if(event.kind==="stopped"){ + if(event.owner&&event.snapshot)retiredChildren.push({owner:event.owner as ChildSnapshot["owner"],database:event.snapshot as ChildSnapshot["database"]}); + }else if(event.kind==="failed")errors.push(new Error("Actual owned Dot child failed")); + }); + },privateLog:(channel,bytes)=>{if(channel==="stdout")process.stdout.write(bytes);else process.stderr.write(bytes);}}); + physicalOwners.push(physicalApp);appLoopback=physicalApp.origin;appOwnerGenerations++; + await syncChildObservation(); + }; + await makeAppOwner();makePhysicalSecond=makeAppOwner; + + },90_000); - afterAll(async()=>{ + afterAll(async()=>{activeCaseDeadline=undefined; const errors:unknown[]=[]; releaseDeviceAckControl();deviceStage=undefined;observingPhase=undefined; - try{await dispatchWork?.stop();if(heartbeat){ - const owner=heartbeat;let timer:ReturnType|undefined; - try{await Promise.race([(async()=>{if(z.uuid().safeParse(agentId).success)await owner.stopInvocationsForAgents([agentId],"Hosted Dot fixture teardown");await owner.drainActiveRunExecutions();})(),new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new Error("Owned Native join exceeded original15-second bound")),15_000);})]);}finally{clearTimeout(timer);} - }}catch(error){errors.push(error);} - try{await stopBudgetOwners?.();}catch(error){errors.push(error);} - try{await app?.locals.paperclipShutdown?.();}catch(error){errors.push(error);} - try{await closeAppTransport();}catch(error){errors.push(error);} + try{ + for(const physical of physicalOwners)await physical.stop(childDeadline()); + for(const known of knownChildProcesses){await known.owner.observe(); + if(known.child.exitCode!==0||known.child.signalCode!==null||known.owner.liveGroups().length) + errors.push(new Error("Known child startup/execution ownership remains unknown; retain evidence"));} + }catch(error){errors.push(error);} try{await cloudService?.stopBackgroundTasks();await close(cloudServer);await close(callback);await registry?.close();}catch(error){errors.push(error);} try{if(db)await db.$client.end({timeout:1});if(url)await closeRegisteredClients(url,{scope:"database"});}catch(error){errors.push(error);} + try{restoreLinuxCA?.();}catch(error){errors.push(error);} restoreGateObservation?.();restoreOAuth?.();restoreEventFactory?.();setCloudRuntimeConfigSnapshot(null);resetCloudRuntimeIdentityForTests();resetCloudControlReplayFenceForTests();vi.unstubAllEnvs();vi.unstubAllGlobals(); process.stdout.write(JSON.stringify({scope:"credential-free actual principal fixture transport",records:transportRecords,overflow:transportOverflow})+"\n"); - expect(unexpectedDecisionWakes).toBe(0);expect(databaseObservation.listenersOpen).toBe(0);expect(databaseObservation.dedicatedOpen).toBe(0); + expect(unexpectedDecisionWakes).toBe(0);expect(physicalOwners.every(owner=>owner.child.exitCode===0)).toBe(true);expect(databaseObservation.listenersOpen).toBe(0);expect(databaseObservation.dedicatedOpen).toBe(0); const tokenDiagnostic=process.env.PAPERCLIP_DOT_ACCEPTANCE_RECEIPT; if(tokenDiagnostic){ if(!path.isAbsolute(tokenDiagnostic))errors.push(new Error("Private token diagnostic needs absolute receipt path")); @@ -495,23 +472,27 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device },30_000); it("uses real hosted code/device OAuth, reverse subscription and genuine failed-task recovery before strict quiet/revoke",async()=>{ - const caseStarted=performance.now(); - if(!app)throw new Error("Missing normal App"); + const caseStarted=performance.now();activeCaseDeadline=caseStarted+90_000; + if(!physicalApp)throw new Error("Missing normal physical App"); const claim=signer.signClaim({stackId,claimId:randomUUID(),previousOrigin:origin,canonicalOrigin:origin,stackSlug:slug}); - expect((await request(app).get("/api/health").set("Host",host).set(CLOUD_RUNTIME_IDENTITY_HEADER,claim)).status).toBe(200); - expect(getCloudRuntimeIdentity()).toMatchObject({stackId,canonicalOrigin:origin}); - await db.insert(companies).values([{id:companyId,name:"Hosted Dot original grant company",issuePrefix:"HDC"},{id:otherCompanyId,name:"Primary not consent",issuePrefix:"HDP"}]); - await db.insert(authUsers).values({id:userId,name:"Current operator",email:userId+"@example.test",createdAt:new Date(),updatedAt:new Date()}); - await accessService(db).ensureMembership(companyId,"user",userId,"owner","active");await accessService(db).ensureRoleDefaultGrants(companyId,userId,"owner",userId); - await instanceSettingsService(db).updateExperimental({enablePublicMcp:true,enableOpenAiDot:true,enableNativeRunner:true}); + expect((await request(appLoopback).get("/api/health").set("Host",host).set(CLOUD_RUNTIME_IDENTITY_HEADER,claim)).status).toBe(200); + expect((await syncChildObservation()).owner.runtimeIdentity).toMatchObject({stackId,canonicalOrigin:origin}); + await db.insert(companies).values([{id:companyId,name:"Hosted Dot original grant company",issuePrefix:"HDC"},{id:otherCompanyId,name:"Primary not consent",issuePrefix:"HDP"}]); + await db.insert(authUsers).values({id:userId,name:"Current operator",email:userId+"@example.test",createdAt:new Date(),updatedAt:new Date()}); + await accessService(db).ensureMembership(companyId,"user",userId,"owner","active"); + await accessService(db).ensureRoleDefaultGrants(companyId,userId,"owner",userId); + await instanceSettingsService(db).updateExperimental({enablePublicMcp:true,enableOpenAiDot:true,enableNativeRunner:true}); const stack=await registry.getAssistantMcpStack(stackId);if(!stack)throw new Error("Missing normal stack"); const route=await new CloudStackRouter({registry:{findStackByHost:async value=>value===stack.primaryHost?stack:undefined,findStackBySlug:async value=>value===stack.stackSlug?stack:undefined},baseDomain:"paperclip.app"}).resolveRoute({trustedHost:stack.primaryHost}); if(route.kind!=="tenant"||!route.target?.activeAppOrigin)throw new Error("Missing normal tenant route");upstreamOrigin=route.target.activeAppOrigin; await vi.waitFor(async()=>{const receipt=await registry.mcpClientMirrorStore().readCurrent(stackId,origin);expect(receipt).toMatchObject({instanceId,origin,dotProfile:"hosted-dot-v1",enabled:true,frontDoor:"tenant-personal-v1"});},{timeout:10_000,interval:50}); + const initialClaim=await boardPost("/api/bootstrap/claim").set("x-selected-operator",userId).send({});expect(initialClaim.status).toBe(200);expect(initialClaim.body).toMatchObject({claimed:true,userId}); + const environment=await boardPost(`/api/companies/${companyId}/environments`).set("x-selected-operator",userId).send({name:"Owned real Linux Dot",driver:"sandbox",config:{provider:"dot-linux-qualification",qualificationId:"dot-owned-linux",reuseLease:false,runnerLifecycleMode:"per_turn"}}); + expect(environment.status).toBe(201);expect(z.uuid().safeParse(environment.body.id).success).toBe(true); const invited=await boardPost(`/api/companies/${companyId}/dot-invitations`).set("x-selected-operator",userId).send({});expect(invited.status).toBe(200);agentId=invited.body.agent.id; const workspace=path.join(home,"workspace");await mkdir(workspace,{recursive:true});await writeFile(path.join(workspace,"AGENTS.md"),"Use only the assigned Paperclip tools to save the requested arithmetic document.\n"); const [invitedAgent]=await db.select().from(agents).where(eq(agents.id,agentId)); - const configuration=await request(app).patch(`/api/agents/${agentId}`).set("Host",host).set("Origin",origin).set("x-selected-operator",userId).send({adapterConfig:{...invitedAgent.adapterConfig,cwd:workspace}});expect(configuration.status).toBe(200); + const configuration=await request(appLoopback).patch(`/api/agents/${agentId}`).set("Host",host).set("Origin",origin).set("x-selected-operator",userId).send({adapterConfig:{...invitedAgent.adapterConfig,cwd:workspace}});expect(configuration.status).toBe(200); const pairing=await boardPost(`/api/companies/${companyId}/agents/${agentId}/dot-binding`).set("x-selected-operator",userId).send({});expect(pairing.status).toBe(201); const registration=await cloudCall("/mcp/runner/oauth/register",{client_name:"Actual hosted Dot",redirect_uris:[redirect],grant_types:["authorization_code","refresh_token",DEVICE_GRANT],response_types:["code"],token_endpoint_auth_method:"none"});expect(registration.status).toBe(201); const clientId=registration.body.client_id,verifier=randomBytes(48).toString("base64url"); @@ -526,7 +507,7 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device const callbackCode=z.enum(["temporarily_unavailable","invalid_grant","invalid_request","access_denied"]).safeParse(returned.body?.error); callbackHttp={status:returned.status,code:closedUnavailable(returned)?"temporarily_unavailable":callbackCode.success?callbackCode.data:"unclassified",retryAfter30:returned.headers["retry-after"]==="30"}; expect(returned.status,JSON.stringify({stage:"authorization-code-callback",...callbackHttp})).toBe(303); - const beforeAuth=authenticateCalls,tokenRequest={grant_type:"authorization_code",client_id:clientId,redirect_uri:redirect,resource,code:new URL(returned.headers.location).searchParams.get("code"),code_verifier:verifier}; + await syncChildObservation();const beforeAuth=authenticateCalls,tokenRequest={grant_type:"authorization_code",client_id:clientId,redirect_uri:redirect,resource,code:new URL(returned.headers.location).searchParams.get("code"),code_verifier:verifier}; const originalRequestDigest=createHash("sha256").update(JSON.stringify(tokenRequest)).digest("hex"); const exchange=async()=>{tokenObservationStart=performance.now();observingPhase="token";try{return await cloudCall("/mcp/runner/oauth/token",tokenRequest);}finally{observingPhase=undefined;}}; let tokens=await exchange(); @@ -556,7 +537,7 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device } const errorCode=z.enum(["temporarily_unavailable","invalid_grant","invalid_request","access_denied"]).safeParse(tokens.body?.error); tokenHttp={status:tokens.status,code:closedUnavailable(tokens)?"temporarily_unavailable":errorCode.success?errorCode.data:"unclassified"}; - expect(tokens.status,JSON.stringify({stage:"authorization-code-token",...tokenHttp})).toBe(200);expect(authenticateCalls).toBe(beforeAuth+1); + await syncChildObservation();expect(tokens.status,JSON.stringify({stage:"authorization-code-token",...tokenHttp})).toBe(200);expect(authenticateCalls).toBe(beforeAuth+1); let raw=tokens.body.access_token;expect(raw).toMatch(/^pcm1\./); const paired=await tool(raw,"paperclip_dot_pair",{pairingCode:pairing.body.pairingCode});expect(paired.status).toBe(200);expect(paired.body.result.isError).toBe(false); const [binding]=await db.select().from(dotAgentBindings).where(eq(dotAgentBindings.id,pairing.body.bindingId));expect(binding.grantId).toBeTruthy(); @@ -586,11 +567,11 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device const selectArgs={stackId:slug},selectPath=`/v1/assistant-mcp/requests/${device.body.user_code}/select`; const selectDigest=createHash("sha256").update(JSON.stringify(selectArgs)).digest("hex"); deviceAckTargetGate=new Promise(resolve=>{resolveDeviceAckTarget=resolve;});deviceAckReleaseGate=new Promise(resolve=>{releaseDeviceMirrorAck=resolve;});deviceAckHeldGate=new Promise(resolve=>{resolveDeviceAckHeld=resolve;}); - holdDeviceMirrorAck=true;deviceStage="first-select";observingPhase="device-first-select";tokenObservationStart=performance.now(); + holdDeviceMirrorAck=true;await setChildDeviceStage("first-select");deviceStage="first-select";observingPhase="device-first-select";tokenObservationStart=performance.now(); let knownClientId:string|undefined; try{ const firstSelect=await cloudCall(selectPath,selectArgs,true); - expect(firstSelect.status).toBe(503);expect(closedUnavailable(firstSelect)!==undefined).toBe(true); + await syncChildObservation();expect(firstSelect.status).toBe(503);expect(closedUnavailable(firstSelect)!==undefined).toBe(true); expect(deviceWire.some(value=>value.stage==="first-select"&&value.route==="device-mint"&&value.status===503&&value.error==="closed-error")).toBe(true); let timer:ReturnType|undefined; try{await Promise.race([deviceAckHeldGate,new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new Error("Actual complete ACK response was not observed within its existing15-second transport budget")),Math.min(15_000,90_000-(performance.now()-caseStarted)));})]);}finally{clearTimeout(timer);} @@ -615,13 +596,13 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device expect(await db.select({id:mcpOauthDeviceRequests.id}).from(mcpOauthDeviceRequests).where(eq(mcpOauthDeviceRequests.clientId,pending.tenantClientId)).limit(2)).toHaveLength(0); expect(await db.select({id:mcpOauthGrants.id}).from(mcpOauthGrants).where(eq(mcpOauthGrants.clientId,pending.tenantClientId)).limit(2)).toHaveLength(0); expect(pending.expiresAt).toBeGreaterThan(Date.now());knownClientId=pending.tenantClientId; - }finally{releaseDeviceAckControl();deviceStage=undefined;observingPhase=undefined;} + }finally{releaseDeviceAckControl();await setChildDeviceStage("none");deviceStage=undefined;observingPhase=undefined;} const acknowledgedDevice=await currentMirrorAck();expect(acknowledgedDevice.revision).toBe(deviceAckTargetRevision);expect(acknowledgedDevice.generation).toBe(heldDeviceAck?.generation); expect(pendingDeviceAckResponses).toBe(0);expect(deviceObserverFailures).toBe(0);expect(deviceWireOverflow).toBe(0); expect(createHash("sha256").update(JSON.stringify(selectArgs)).digest("hex")).toBe(selectDigest); - deviceStage="retry-select";observingPhase="device-retry-select";tokenObservationStart=performance.now(); + await setChildDeviceStage("retry-select");deviceStage="retry-select";observingPhase="device-retry-select";tokenObservationStart=performance.now(); let deviceSelect:Awaited>; - try{deviceSelect=await cloudCall(selectPath,selectArgs,true);}finally{deviceStage=undefined;observingPhase=undefined;} + try{deviceSelect=await cloudCall(selectPath,selectArgs,true);await syncChildObservation();}finally{await setChildDeviceStage("none");deviceStage=undefined;observingPhase=undefined;} expect(deviceSelect.status).toBe(200);expect(actualDeviceRegistrationCalls).toBe(1); const selectedDevice=await registry.assistantMcpStore().getAuthorization(device.body.user_code); expect(selectedDevice?.status==="selected"&&selectedDevice.tenantClientId===knownClientId&&selectedDevice.expiresAt===originalDeviceExpiry).toBe(true); @@ -639,13 +620,13 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device await pause(device.body.interval*1000+1);const deviceToken=await cloudCall("/mcp/runner/oauth/token",{grant_type:DEVICE_GRANT,client_id:clientId,resource,device_code:device.body.device_code});expect(deviceToken.status).toBe(200);expect(deviceToken.body.access_token).toMatch(/^pcm1\./); expect((await cloudCall("/mcp/runner/oauth/revoke",{client_id:clientId,resource,token:deviceToken.body.refresh_token})).status).toBe(200); const subscription={name:"paperclip.dot.mailbox_updated",arguments:{companyId,bindingId:pairing.body.bindingId},delivery:{mode:"webhook",url:callbackPublicOrigin+"/events",secret:callbackSecret}}; - expect(eventTransportCounts.factoryOwners).toBe(appOwnerGenerations); + await syncChildObservation();expect(eventTransportCounts.factoryOwners).toBe(appOwnerGenerations); const subscribed=await rpc(raw,"events/subscribe",subscription); const rpcError=z.object({code:z.number().int(),message:z.string().max(300),data:z.unknown().optional()}).strict().safeParse(subscribed.body?.error); const error:SubscriptionWitness["error"]=subscribed.body?.error===undefined&&subscribed.status===200?"none":!rpcError.success?"unclassified":rpcError.data.code===-32602&&rpcError.data.message==="Hosted Dot subscription authority is unavailable."?"hosted-authority-unavailable":rpcError.data.message==="Callback endpoint is unavailable."?"invalid-destination":rpcError.data.message==="Callback verification failed."?"callback-verification-failed":"unclassified"; subscriptionWitness={status:subscribed.status,rpcCode:rpcError.success&&[-32602,-32015,-32603].includes(rpcError.data.code)?rpcError.data.code:undefined,error}; expect(subscriptionWitness).toEqual({status:200,rpcCode:undefined,error:"none"}); - expect(eventTransportCounts.authorityRequests).toBeGreaterThan(0);expect(eventTransportCounts.callbackRequests).toBeGreaterThan(0);expect(eventTransportCounts.unexpected).toBe(0); + await syncChildObservation();expect(eventTransportCounts.authorityRequests).toBeGreaterThan(0);expect(eventTransportCounts.callbackRequests).toBeGreaterThan(0);expect(eventTransportCounts.unexpected).toBe(0); await vi.waitFor(()=>expect(callbacks.length).toBeGreaterThanOrEqual(2),{timeout:10_000,interval:25});expect(callbacks[0].id).toBe(callbacks[1].id);expect(callbacks[1].at-callbacks[0].at).toBeGreaterThanOrEqual(1900); const inbox=await tool(raw,"paperclip_dot_inbox",{});expect(inbox.status).toBe(200);const challenge=inbox.body.result.structuredContent.result.items.find((item:{kind:string})=>item.kind==="readiness_challenge");expect(challenge).toBeTruthy(); expect((await tool(raw,"paperclip_dot_confirm_event",{challenge:challenge.references.challenge})).body.result.isError).toBe(false); @@ -653,17 +634,17 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device expect((await db.select().from(dotAgentBindings).where(eq(dotAgentBindings.id,pairing.body.bindingId)))[0].status).toBe("ready"); const [readyAgent]=await db.select().from(agents).where(eq(agents.id,agentId));expect(readyAgent.lifecycleState).toBe("ready");expect(["active","idle"].includes(readyAgent.status)).toBe(true); },{timeout:10_000,interval:25}); + const selected=await request(appLoopback).patch(`/api/agents/${agentId}`).set("Host",host).set("Origin",origin).set("x-selected-operator",userId).send({defaultEnvironmentId:environment.body.id}); + expect(selected.status).toBe(200);expect(selected.body.defaultEnvironmentId).toBe(environment.body.id); const binary=process.env.PAPERCLIP_DOT_HOSTED_RUNNER_BINARY; expect(binary,"Explicit source-matched local Runner binary is required").toBeTruthy();if(!binary||!path.isAbsolute(binary))throw new Error("PAPERCLIP_DOT_HOSTED_RUNNER_BINARY must be absolute");await access(binary); vi.stubEnv("PAPERCLIP_RUNNER_BINARY",binary);vi.stubEnv("PAPERCLIP_RUNNER_STATE_DIR",path.join(home,"runner-state"));vi.stubEnv("PAPERCLIP_IN_WORKTREE","false"); - if(!appServer)throw new Error("Missing actual normal App listener"); + if(!physicalApp)throw new Error("Missing actual normal App process/listener"); const nativeOrigin=appLoopback;vi.stubEnv("PAPERCLIP_API_URL",nativeOrigin);vi.stubEnv("PAPERCLIP_RUNTIME_API_URL",nativeOrigin);vi.stubEnv("PAPERCLIP_LISTEN_HOST","127.0.0.1");vi.stubEnv("PAPERCLIP_LISTEN_PORT",String(new URL(nativeOrigin).port)); - expect(resolveLocalRuntimeApiUrl()).toBe(nativeOrigin);expect(configuredPaperclipApiBaseUrl()).toBe(nativeOrigin); - if(!heartbeat||!dispatchWork)throw new Error("Normal Native owners were not composed at startup"); - vi.stubEnv("PAPERCLIP_RUNNER_BINARY","relative-invalid-dot-retry-controller"); + expect(physicalApp.origin).toBe(nativeOrigin); + expect((await syncChildObservation()).owner.pid).toBe(physicalApp.pid); const task=await issueService(db).create(companyId,{title:"Save the arithmetic report",description:"Save a report document containing 17 + 25 = 42 using the assigned Paperclip tools.",workMode:"standard",status:"todo",assigneeAgentId:agentId,createdByUserId:operatorId}); const read=await tool(raw,"paperclip_dot_tasks",{});expect(read.status).toBe(200);expect(read.body.result.isError).toBe(false);expect(read.body.result.structuredContent.result.some((item:{id:string})=>item.id===task.id)).toBe(true); - vi.stubEnv("PAPERCLIP_RUNNER_BINARY","relative-invalid-dot-retry-controller"); const admissionId=randomUUID(),requestArgs={issueId:task.id,requestId:admissionId}; const admission=await tool(raw,"paperclip_dot_request_work",requestArgs);expect(admission.status,JSON.stringify(admission.body)).toBe(200);expect(admission.body.result.isError,JSON.stringify(admission.body)).toBe(false); const admissionKey=`dot-work:${pairing.body.bindingId}:${(await db.select().from(dotAgentBindings).where(eq(dotAgentBindings.id,pairing.body.bindingId)))[0].generation}:${admissionId}`; @@ -672,49 +653,64 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device const [wake]=await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey,admissionKey));let runId=wake.runId!; const replay=await tool(raw,"paperclip_dot_request_work",requestArgs);expect(replay.body.result.structuredContent.result.runId).toBe(runId);expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey,admissionKey))).toHaveLength(1); const failedRunId=runId; + // A real offered assignment plus current durable checkpoint/header must + // precede the fault. No useful business operation has been sent yet. await vi.waitFor(async()=>{ - const [failed]=await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id,failedRunId)); - expect(failed?.status).toBe("failed");expect(failed?.finishedAt).not.toBeNull(); - expect(failed?.error).toContain("PAPERCLIP_RUNNER_BINARY must be an absolute path");expect(failed).toMatchObject({runtimeMode:"legacy",nativeSessionId:null,completionContractId:null}); + expect(await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId,failedRunId))).toHaveLength(1); + },{timeout:30_000,interval:50}); + await vi.waitFor(async()=>{ + expect(await nativeProviderRecoveryEvidence({db,runId:failedRunId, + sourceFailureCode:"native_session_interrupted",executionTargetKind:"remote"})) + .toMatchObject({recoveryMode:"exact_checkpoint_resume",checkpointExists:true,providerSessionEstablished:true}); + },{timeout:30_000,interval:50}); + if(!childControl)throw new Error("Missing actual installed child provider owner"); + const fault=z.object({status:z.literal("stopped"),runId:z.literal(failedRunId),providerLeaseId:z.string(),containerId:z.string(), + kernel:z.object({pid:z.number().int().positive(),fingerprint:z.string()}).passthrough(),checkpoint:z.object({recoveryMode:z.literal("exact_checkpoint_resume")}).passthrough(), + namespaceTerminationOnly:z.literal(true),termination:z.object({providerLeaseId:z.string(),state:z.literal("stopped")})}).strict() + .parse((await childControl.request({command:"stop-checkpointed",runId:failedRunId,environmentId:environment.body.id},childDeadline())).result); + expect(fault.termination).toEqual({providerLeaseId:fault.providerLeaseId,state:"stopped"}); + let failureEpisode:Record|undefined; + await vi.waitFor(async()=>{ + const [owner]=await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId,failedRunId)); + const episodes=owner?.recoveryHistory.filter(row=>row.disposition==="retryable_failure")??[]; + expect(episodes).toHaveLength(1);failureEpisode=episodes[0]; + expect(failureEpisode).toMatchObject({checkpointExists:true,providerSessionEstablished:true}); + // Observe the actual native settlement category; never substitute the + // old local-adapter code or accept an arbitrary failure as this fault. + expect(["native_runner_process_exited","native_session_interrupted","provider_process_exited", + "provider_stdout_closed","provider_process_output_closed"]).toContain(failureEpisode.reason); + expect(Date.parse(String(failureEpisode.at))).toBeGreaterThan(0); },{timeout:30_000,interval:50}); - await heartbeat.waitForRunExecutionDrain(failedRunId,{timeoutMs:15_000}); - const failedAssignments=await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId,failedRunId));expect(failedAssignments).toHaveLength(0); expect(await documentService(db).getIssueDocumentByKey(task.id,"report")).toBeNull(); - const failedReplay=await tool(raw,"paperclip_dot_request_work",requestArgs); - expect(failedReplay.body.result.structuredContent.result).toMatchObject({status:"admission_failed",runId:failedRunId,admissionStatus:"failed"}); - vi.stubEnv("PAPERCLIP_RUNNER_BINARY",binary); + const failedAssignments=await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId,failedRunId)); + expect(failedAssignments).toHaveLength(1); let actualSuccessor:typeof heartbeatRuns.$inferSelect|undefined; const retryKey=randomUUID(),retryBody={idempotencyKey:retryKey,observedRunId:failedRunId}; const unauthorizedRetry=await boardPost(`/api/issues/${task.id}/retry`).send(retryBody);expect(unauthorizedRetry.status).toBe(403); const retry=await boardPost(`/api/issues/${task.id}/retry`).set("x-selected-operator",operatorId).send(retryBody); - if(retry.status===202){ - expect(retry.status,JSON.stringify(retry.body)).toBe(202);expect(retry.body).toMatchObject({accepted:true,stale:false,observedRunId:failedRunId});expect(retry.body.requestId).toBeTruthy(); - const repeatedRetry=await boardPost(`/api/issues/${task.id}/retry`).set("x-selected-operator",operatorId).send(retryBody); - expect(repeatedRetry.status,JSON.stringify(repeatedRetry.body)).toBe(202);expect(repeatedRetry.body.requestId).toBe(retry.body.requestId); - expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey,`task-retry:${retryKey}`))).toHaveLength(1); - await vi.waitFor(async()=>{ - const [retryWake]=await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id,retry.body.requestId)); - expect(retryWake).toMatchObject({companyId,agentId,requestedByActorId:operatorId}); - expect(retryWake.payload).toMatchObject({issueId:task.id,taskRetry:{sourceRunId:failedRunId,actorId:operatorId}}); - expect(retryWake.runId).toBeTruthy();expect(retryWake.runId).not.toBe(failedRunId);runId=retryWake.runId!; - },{timeout:30_000,interval:50}); - }else{ - expect(retry.status,JSON.stringify(retry.body)).toBe(200); - expect(retry.body,JSON.stringify(retry.body)).toMatchObject({requestId:null,accepted:false,stale:true}); - expect(retry.body.observedRunId).toBeTruthy();expect(retry.body.observedRunId).not.toBe(failedRunId);runId=retry.body.observedRunId; - expect(retry.body.presentation).toMatchObject({intentId:null,responsibility:"system",state:"working",nextRetryAt:null,canRetry:false,userAction:null,sourceRunIds:[runId],observedRunId:runId}); - const [successor]=await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id,runId)); - expect(successor).toMatchObject({id:runId,companyId,agentId,issueId:task.id,retryOfRunId:failedRunId,invocationSource:"automation",triggerDetail:"system"}); - expect(successor.contextSnapshot).toMatchObject({source:"issue.continuation_recovery"});expect(successor.wakeupRequestId).toBeTruthy(); - const [automaticWake]=await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id,successor.wakeupRequestId!)); - expect(automaticWake).toMatchObject({companyId,agentId,runId,source:"automation",triggerDetail:"system",reason:"issue_continuation_needed"}); - expect(automaticWake.payload).toMatchObject({issueId:task.id});expect(automaticWake.payload?.taskRetry).toBeUndefined(); - expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey,`task-retry:${retryKey}`))).toHaveLength(0); - } - const stillFailed=await tool(raw,"paperclip_dot_request_work",requestArgs); - expect(stillFailed.body.result.structuredContent.result).toMatchObject({status:"admission_failed",runId:failedRunId}); - await vi.waitFor(async()=>{const [run]=await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id,runId));actualSuccessor=run;if(run&&["failed","cancelled","timed_out"].includes(run.status))throw new Error(`Normal Dot admission failed: ${run.errorCode??run.status}`);expect(await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId,runId))).toHaveLength(1);},{timeout:30_000,interval:50}); - const successorAssignments=await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId,runId));expect(successorAssignments).toHaveLength(1);const assignment=successorAssignments[0];expect(assignment).toMatchObject({bindingId:pairing.body.bindingId,agentId,companyId,status:"offered"}); + expect(retry.status,JSON.stringify(retry.body)).toBe(202); + expect(retry.body).toMatchObject({accepted:true,stale:false,observedRunId:failedRunId});expect(retry.body.requestId).toBeTruthy(); + const repeatedRetry=await boardPost(`/api/issues/${task.id}/retry`).set("x-selected-operator",operatorId).send(retryBody); + expect(repeatedRetry.status).toBe(202);expect(repeatedRetry.body.requestId).toBe(retry.body.requestId); + await vi.waitFor(async()=>{ + const [retryWake]=await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id,retry.body.requestId)); + expect(retryWake).toMatchObject({companyId,agentId,requestedByActorId:operatorId}); + expect(retryWake.payload).toMatchObject({issueId:task.id,taskRetry:{sourceRunId:failedRunId,actorId:operatorId}}); + expect(retryWake.runId).toBeTruthy();runId=retryWake.runId!; + if(runId===failedRunId)expect(retryWake.status).toBe("coalesced"); + // A normal authorized Retry can admit a successor if it wins the race; + // an automatic same-run resume can instead own the coalesced receipt. + // Neither branch is forced by suppressing normal recovery workers. + const [current]=await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id,runId));actualSuccessor=current; + expect(current).toMatchObject({companyId,agentId}); + expect(current.status).toBe("running"); + },{timeout:30_000,interval:50}); + await vi.waitFor(async()=>{ + expect(await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId,runId))).toHaveLength(1); + },{timeout:30_000,interval:50}); + const successorAssignments=await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId,runId)); + const assignment=successorAssignments[0];expect(assignment).toMatchObject({bindingId:pairing.body.bindingId,agentId,companyId}); + expect(["offered","accepted"]).toContain(assignment.status); const assigned=await tool(raw,"paperclip_dot_read",{assignmentId:assignment.id});expect(assigned.body.result.isError,JSON.stringify(assigned.body)).toBe(false); const operation=async(name:"paperclip_dot_accept"|"paperclip_dot_tool"|"paperclip_dot_finish",input:Record,requestId=randomUUID(),expectedStatus:"completed"|"rejected"="completed")=>{ const action=({paperclip_dot_accept:"accept",paperclip_dot_tool:"tool",paperclip_dot_finish:"finish"} as const)[name]; @@ -744,31 +740,60 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device const [run]=await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id,runId));const [contract]=await db.select().from(completionContracts).where(eq(completionContracts.id,run.completionContractId!));const specification=z.object({revision:z.string(),criteria:z.array(z.object({id:z.string()}))}).passthrough().parse(contract.contractJson); const result={reportedWorkDisposition:"completed",summary:"Saved the arithmetic report.",completionClaim:{contractRevision:specification.revision,objectiveSatisfied:true,criteria:specification.criteria.map(criterion=>({criterionId:criterion.id,status:"passed",evidenceRefs:[]})),remainingWork:[]},evidence:[],verification:[{commandOrCheck:"Read the persisted report: 17 + 25 = 42.",status:"pass"}]}; expect((await operation("paperclip_dot_tool",{name:"paperclip_finish",arguments:result})).receipt).toMatchObject({status:"completed",isError:false}); - await operation("paperclip_dot_finish",{result});await heartbeat.waitForRunExecutionDrain(runId,{timeoutMs:15_000}); + await operation("paperclip_dot_finish",{result});await childControl!.request({command:"drain-run",runId},childDeadline()); const [settledAssignment]=await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.id,assignment.id));expect(settledAssignment.status).toBe("settled");const successorResults=await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId,runId));expect(successorResults).toHaveLength(1);const [settledTask]=await db.select().from(issues).where(eq(issues.id,task.id));expect(settledTask.status).toBe("done"); - const heartbeatOwner=heartbeat; - const passiveConnectionSnapshot=()=>({clients:databaseObservation.clients,opened:databaseObservation.connectionsOpened,closed:databaseObservation.connectionsClosed,live:databaseObservation.liveConnections.size,dedicated:databaseObservation.dedicatedOpen,listeners:databaseObservation.listenersOpen}); + const passiveConnectionSnapshot=async(deadline=childDeadline())=>{ + const child=await syncChildObservation(deadline),all=[...retiredChildren,child]; + return{clients:databaseObservation.clients+all.reduce((n,v)=>n+v.database.clients,0), + opened:databaseObservation.connectionsOpened+all.reduce((n,v)=>n+v.database.opened,0), + closed:databaseObservation.connectionsClosed+all.reduce((n,v)=>n+v.database.closed,0), + live:databaseObservation.liveConnections.size+all.reduce((n,v)=>n+v.database.connections,0), + dedicated:databaseObservation.dedicatedOpen+all.reduce((n,v)=>n+v.database.dedicated,0), + listeners:databaseObservation.listenersOpen+all.reduce((n,v)=>n+v.database.listeners,0)}; + }; + const totalTenantSnapshot=async(deadline=childDeadline())=>{ + const connections=await passiveConnectionSnapshot(deadline); + const all=[...retiredChildren,childSnapshot!]; + return{queryCount:databaseObservation.queries+all.reduce((n,v)=>n+v.database.queries,0),callbacks:callbacks.length,connections}; + }; const awaitPassiveConnectionClosure=async(deadline:number)=>{ expect(databaseObservation.connectionsOpened).toBeGreaterThan(0); - const remaining=deadline-performance.now();expect(remaining,"Original15-second settlement budget must include transport closure").toBeGreaterThan(0); - await vi.waitFor(()=>{ - expect(databaseObservation.liveConnections.size).toBe(0);expect(databaseObservation.dedicatedOpen).toBe(0);expect(databaseObservation.listenersOpen).toBe(0); - expect(databaseObservation.connectionsClosed).toBe(databaseObservation.connectionsOpened); + const remaining=deadline-performance.now();expect(remaining,"Original15-second settlement includes all used transports").toBeGreaterThan(0); + await vi.waitFor(async()=>{ + const connections=await passiveConnectionSnapshot(deadline); + expect(childSnapshot!.database.opened).toBeGreaterThan(0);expect(childSnapshot!.database.queries).toBeGreaterThan(0); + expect(connections.live).toBe(0);expect(connections.dedicated).toBe(0);expect(connections.listeners).toBe(0); + expect(connections.closed).toBe(connections.opened); },{timeout:remaining,interval:25}); }; + const inspect=async(deadline=childDeadline())=>{ + const value=(await childControl!.request({command:"inspect"},deadline)).result; + return z.object({frontDoor:z.object({blocked:z.boolean()}).passthrough(),subscriptions:z.object({blocked:z.boolean()}).passthrough(), + schedule:z.object({blocked:z.boolean()}).passthrough()}).passthrough().parse(value); + }; + const settleActualOwners=async(deadline:number)=>{ + await vi.waitFor(async()=>{ + const child=await syncChildObservation(deadline); + expect(child.owner.taskDrain).toMatchObject({activeRuns:0,pendingWakes:0,quiescent:true}); + expect(child.owner.worker.active+idleWorkSnapshot().active).toBe(0); + expect(child.owner.errorCount).toBe(0);expect(child.owner.unexpectedDecisionWakes).toBe(0); + expect(child.database.observerPending).toBe(0);expect(child.database.observerFailures).toBe(0);expect(child.database.overflow).toBe(0); + const childReadBefore=child.database.queries; + const proof=await inspect(deadline); + expect((await syncChildObservation(deadline)).database.queries).toBeGreaterThan(childReadBefore); + expect(proof.frontDoor.blocked).toBe(false);expect(proof.subscriptions.blocked).toBe(false);expect(proof.schedule.blocked).toBe(false); + expect((await db.select().from(mcpEventDeliveries)).every(row=>row.finishedAt!==null)).toBe(true); + },{timeout:deadline-performance.now(),interval:25}); + }; const firstSettlementDeadline=performance.now()+15_000; - const budget={beforeRead:async()=>{},check:()=>{}}; - const inspect=()=>readIdleMcpSleepProof(db,db,{stackId,ownerId:randomUUID(),capabilityGeneration:"a".repeat(64),challenge:"b".repeat(64),now:Date.now(),budget}); - await vi.waitFor(async()=>{ - expect(heartbeatOwner.getTaskDrainStatus()).toMatchObject({activeRuns:0,pendingWakes:0,quiescent:true});expect(idleWorkSnapshot().active).toBe(0); - expect(databaseObservation.listenersOpen).toBe(0);expect(databaseObservation.dedicatedOpen).toBe(0); - const proof=await inspect();expect(proof.frontDoor.blocked).toBe(false);expect(proof.subscriptions.blocked).toBe(false);expect(proof.schedule.blocked).toBe(false); - expect((await db.select().from(mcpEventDeliveries)).every(row=>row.finishedAt!==null)).toBe(true); - },{timeout:15_000,interval:25}); + await settleActualOwners(firstSettlementDeadline); const beforeRead=databaseObservation.queries;expect((await documentService(db).getIssueDocumentByKey(task.id,"report"))?.body).toBe("17 + 25 = 42.");expect(databaseObservation.queries).toBeGreaterThan(beforeRead); await awaitPassiveConnectionClosure(firstSettlementDeadline); - const before={queryCount:databaseObservation.queries,callbacks:callbacks.length,connections:passiveConnectionSnapshot()};let quietAfter:typeof before|undefined;const quietTraceStart=performance.now(); - await pause(15_000);const quietTraceEnd=performance.now();quietAfter={queryCount:databaseObservation.queries,callbacks:callbacks.length,connections:passiveConnectionSnapshot()};expect(quietAfter).toEqual(before);expect(errors).toEqual([]); + const before=await totalTenantSnapshot();let quietAfter:typeof before|undefined;const quietTraceStart=performance.now(); + // No SQL observer or child IPC request during this strict window. Only the + // original actual tenant/Cloud owners can change the passive counters. + await pause(15_000);const quietTraceEnd=performance.now();quietAfter=await totalTenantSnapshot(); + expect(quietAfter).toEqual(before);expect(errors).toEqual([]); // The normal owner route acquires the signed tenant idle hold, reads the // real current mirror/admission and calls the existing provider stop owner. // This is controlled local provider/HTTP availability, not deployed suspension. @@ -777,14 +802,14 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device const idleAdmission=await registry.readIdleMcpWakeAdmission(stackId);expect(idleAdmission).toBeTruthy(); const admissionDigest=createHash("sha256").update(JSON.stringify(idleAdmission)).digest("hex"); const [preWakeBinding]=await db.select().from(dotAgentBindings).where(eq(dotAgentBindings.id,pairing.body.bindingId)); - healthAvailability="wake-once-then-unavailable"; + await setChildHealth("wake-once-then-unavailable"); const failedReadiness=await tool(raw,"paperclip_dot_tasks",{});expect(failedReadiness.status).toBe(503);expect(failedReadiness.body).toMatchObject({error:"temporarily_unavailable"}); - expect(readinessStatuses[0]).toBe(200);expect(readinessStatuses.some(status=>status===503)).toBe(true);expect(readinessOverflow).toBe(0); + await syncChildObservation();expect(readinessStatuses[0]).toBe(200);expect(readinessStatuses.some(status=>status===503)).toBe(true);expect(readinessOverflow).toBe(0); // Provider readiness has legitimately settled awake, but the original // credential request was refused by the real entry HTTP readiness owner. // Retry the same wrapped credential; do not mint or publish new authority. expect(await registry.getStack(stackId)).toMatchObject({lifecycleState:"active",sleepState:"awake"}); - healthAvailability="ready"; + await setChildHealth("ready"); const readyRetry=await tool(raw,"paperclip_dot_tasks",{});expect(readyRetry.status).toBe(200);expect(readyRetry.body.result.isError).toBe(false); const [postWakeBinding]=await db.select().from(dotAgentBindings).where(eq(dotAgentBindings.id,pairing.body.bindingId)); expect(postWakeBinding).toMatchObject({id:preWakeBinding.id,generation:preWakeBinding.generation,grantId:originalGrant.id,status:"ready"}); @@ -792,48 +817,73 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device wakeEvidence={sleepStatus:sleepResponse.status,failedReadinessStatus:failedReadiness.status,retryStatus:readyRetry.status,admissionDigest,grantId:originalGrant.id,bindingGeneration:postWakeBinding.generation,healthStatuses:[...readinessStatuses],overflow:readinessOverflow}; const firstBindingSnapshot=(await db.select().from(dotAgentBindings).where(eq(dotAgentBindings.id,pairing.body.bindingId)))[0]; const callbackCountBeforeRestart=callbacks.length; - await reconstructAppOwner();await reconstructCloudOwner(); - expect(appOwnerGenerations).toBe(2);expect(cloudOwnerGenerations).toBe(2); - const restoredBinding=(await db.select().from(dotAgentBindings).where(eq(dotAgentBindings.id,pairing.body.bindingId)))[0]; - expect(restoredBinding).toMatchObject({id:firstBindingSnapshot.id,companyId,agentId,grantId:originalGrant.id,generation:firstBindingSnapshot.generation,status:"ready"}); - expect((await documentService(db).getIssueDocumentByKey(task.id,"report"))?.body).toBe("17 + 25 = 42."); - expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId,runId))).toHaveLength(1); - const refreshed=await cloudCall("/mcp/runner/oauth/token",{grant_type:"refresh_token",client_id:clientId,resource,refresh_token:tokens.body.refresh_token});expect(refreshed.status).toBe(200); - raw=refreshed.body.access_token;expect(raw).toMatch(/^pcm1\./); - const afterRestart=await rpc(raw,"events/subscribe",subscription);expect(afterRestart.status).toBe(200); - const resumedSettlementDeadline=performance.now()+15_000; - await vi.waitFor(async()=>{ - expect(idleWorkSnapshot().active).toBe(0);expect(databaseObservation.listenersOpen).toBe(0);expect(databaseObservation.dedicatedOpen).toBe(0); - const proof=await inspect();expect(proof.frontDoor.blocked).toBe(false);expect(proof.subscriptions.blocked).toBe(false);expect(proof.schedule.blocked).toBe(false); - expect((await db.select().from(mcpEventDeliveries)).every(row=>row.finishedAt!==null)).toBe(true); - },{timeout:15_000,interval:25}); - // A refresh/reconstruction may legitimately redeliver a pending notification, - // but it cannot duplicate the completed task, run result or durable operation. - expect(callbacks.length).toBeGreaterThanOrEqual(callbackCountBeforeRestart); - await awaitPassiveConnectionClosure(resumedSettlementDeadline); - const resumedBefore={queryCount:databaseObservation.queries,callbacks:callbacks.length,connections:passiveConnectionSnapshot()},resumedStart=performance.now(); - await pause(15_000);const resumedElapsed=performance.now()-resumedStart; - const resumedAfter={queryCount:databaseObservation.queries,callbacks:callbacks.length,connections:passiveConnectionSnapshot()};expect(resumedAfter).toEqual(resumedBefore);expect(errors).toEqual([]); - const [retainedFailure]=await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id,failedRunId));expect(retainedFailure).toMatchObject({id:failedRunId,companyId,agentId,status:"failed"});expect(retainedFailure.error).toContain("PAPERCLIP_RUNNER_BINARY must be an absolute path"); - const failedResults=await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId,failedRunId));expect(failedResults).toHaveLength(0); - if(retry.status===200){ - expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.issueId,task.id))).filter(row=>row.retryOfRunId===failedRunId).map(row=>row.id)).toEqual([runId]); - expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey,`task-retry:${retryKey}`))).toHaveLength(0); - } + if(!physicalApp)throw new Error("Missing first physical App generation"); + let resumedBefore:Awaited>|undefined,resumedAfter:typeof resumedBefore; + let resumedElapsed=0; + physicalFollowon=await usefulAfterPhysicalRestart({get db(){return db;},companyId,agentId,first:physicalApp,get cloudLoopback(){return cloudLoopback;}, + caseDeadline:caseStarted+90_000, + startSecond:async()=>{ + // First real Node/group closed before this new child can be started. + await db.$client.end({timeout:1});await closeRegisteredClients(url!,{scope:"database"}); + await makePhysicalSecond(); + await reconstructCloudOwner(); + expect(appOwnerGenerations).toBe(2);expect(cloudOwnerGenerations).toBe(2); + const restoredBinding=(await db.select().from(dotAgentBindings).where(eq(dotAgentBindings.id,pairing.body.bindingId)))[0]; + expect(restoredBinding).toMatchObject({id:firstBindingSnapshot.id,companyId,agentId,grantId:originalGrant.id,generation:firstBindingSnapshot.generation,status:"ready"}); + expect((await documentService(db).getIssueDocumentByKey(task.id,"report"))?.body).toBe("17 + 25 = 42."); + expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId,runId))).toHaveLength(1); + const refreshed=await cloudCall("/mcp/runner/oauth/token",{grant_type:"refresh_token",client_id:clientId,resource,refresh_token:tokens.body.refresh_token});expect(refreshed.status).toBe(200); + raw=refreshed.body.access_token;expect(raw).toMatch(/^pcm1\./); + const afterRestart=await rpc(raw,"events/subscribe",subscription);expect(afterRestart.status).toBe(200); + expect(callbacks.length).toBeGreaterThanOrEqual(callbackCountBeforeRestart); + if(!physicalApp)throw new Error("Second real child did not start");return physicalApp; + }, + createTask:async body=>{const response=await boardPost(`/api/companies/${companyId}/issues`).set("x-selected-operator",operatorId).send(body);return{status:response.status,body:response.body};}, + tool:async(name,args,ownedOrigin)=>{ + if(!ownedOrigin){const response=await tool(raw,name,args);return{status:response.status,body:response.body};} + const selected=new URL(ownedOrigin);expect(selected.protocol).toBe("http:");expect(selected.hostname).toBe("127.0.0.1"); + // Same actual wrapped credential, virtual tenant Host, protocol and RPC + // body through the ONE owned lost-response proxy. No retry/new requestID. + const response=await request(ownedOrigin).post("/mcp/runner").set("Host",host).set("Authorization","Bearer "+raw) + .set("Accept","application/json, text/event-stream").set("mcp-protocol-version","2026-07-28").set("mcp-method","tools/call").set("mcp-name",name) + .send({jsonrpc:"2.0",id:++serial,method:"tools/call",params:{name,arguments:args,_meta:{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{events:{}}}}}); + return{status:response.status,body:response.body}; + }, + assertPassiveQuiet:async duration=>{ + const resumedSettlementDeadline=performance.now()+15_000; + await settleActualOwners(resumedSettlementDeadline);await awaitPassiveConnectionClosure(resumedSettlementDeadline); + resumedBefore=await totalTenantSnapshot();const resumedStart=performance.now(); + await pause(duration);resumedElapsed=performance.now()-resumedStart;resumedAfter=await totalTenantSnapshot(); + expect(resumedElapsed).toBeGreaterThanOrEqual(15_000);expect(resumedAfter).toEqual(resumedBefore);expect(errors).toEqual([]); + }, + }); + const [retainedFailure]=await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id,failedRunId)); + expect(retainedFailure).toMatchObject({id:failedRunId,companyId,agentId}); + const [retainedOwner]=await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId,failedRunId)); + expect(retainedOwner.recoveryHistory.filter(row=>row.disposition==="retryable_failure")).toEqual([failureEpisode]); + if(runId===failedRunId)expect(retainedFailure.status).toBe("succeeded"); + else expect(retainedFailure.status).toBe("failed"); + const failedResults=await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId,failedRunId));expect(failedResults).toHaveLength(runId===failedRunId?1:0); + const retryReceipts=await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey,`task-retry:${retryKey}`)); + expect(retryReceipts).toHaveLength(1);expect(retryReceipts[0].runId).toBe(runId); + if(runId===failedRunId)expect(retryReceipts[0].status).toBe("coalesced"); const subscriptionsBefore=await db.select().from(mcpEventSubscriptions); const wrongBinding=await rpc(raw,"events/subscribe",{...subscription,arguments:{companyId,bindingId:randomUUID()}});expect(wrongBinding.status).toBe(400);expect(wrongBinding.body.error).toMatchObject({code:-32602,message:"Invalid arguments or unavailable authority."});expect(await db.select().from(mcpEventSubscriptions)).toEqual(subscriptionsBefore); - const revoked=await request(app!).delete(`/api/companies/${companyId}/agents/${agentId}/dot-binding`).set("Host",host).set("Origin",origin).set("x-selected-operator",userId);expect(revoked.status).toBe(204); + const revoked=await request(appLoopback).delete(`/api/companies/${companyId}/agents/${agentId}/dot-binding`).set("Host",host).set("Origin",origin).set("x-selected-operator",userId);expect(revoked.status).toBe(204); const revokedTasks=await tool(raw,"paperclip_dot_tasks",{});expect(revokedTasks.status).toBe(503);expect(revokedTasks.body).toMatchObject({error:"temporarily_unavailable"}); const revokedOperation=await tool(raw,"paperclip_dot_operation_status",{assignmentId:assignment.id,requestId:writeId});expect(revokedOperation.status).toBe(503);expect(revokedOperation.body).toMatchObject({error:"temporarily_unavailable"}); + const revokedFreshOperation=await tool(raw,"paperclip_dot_operation_status",{assignmentId:physicalFollowon.assignmentId,requestId:physicalFollowon.requestId}); + expect(revokedFreshOperation.status).toBe(503);expect(revokedFreshOperation.body).toMatchObject({error:"temporarily_unavailable"}); expect((await db.select().from(dotAgentBindings).where(eq(dotAgentBindings.id,pairing.body.bindingId)))[0].generation).toBeGreaterThan(1); expect((await db.select().from(mcpOauthGrants).where(eq(mcpOauthGrants.id,originalGrant.id)))[0].revokedAt).not.toBeNull(); - expect(eventTransportCounts.factoryOwners).toBe(appOwnerGenerations);expect(eventTransportCounts.unexpected).toBe(0); + await syncChildObservation();expect(eventTransportCounts.factoryOwners).toBe(appOwnerGenerations);expect(eventTransportCounts.unexpected).toBe(0); expect(deviceRetryEvidence).toMatchObject({firstStatus:503,retryStatus:200,registrationCalls:1,sameClient:true,originalExpiryUnchanged:true,zeroInnerAuthorizationsBeforeRetry:true,pendingInnerAuthorizationsAfterRetry:1,heldExactDcrRevision:true,scopeValidated:true}); const evidencePath=process.env.PAPERCLIP_DOT_ACCEPTANCE_RECEIPT; if(!evidencePath)throw new Error("Explicit owned Dot acceptance receipt path required"); await writeFile(evidencePath,JSON.stringify({ version:1,scope:"controlled-normal-hosted-Dot-useful-retry",companyId,agentId,taskId:task.id, - retryHttpStatus:retry.status,retryBranch:retry.status===202?"authorized-manual":"verified-normal-automatic", + retryHttpStatus:retry.status,retryBranch:runId===failedRunId?"normal-native-resume-retry-coalesced":"authorized-retry-successor", + originalFailureEpisode:failureEpisode,ownedFault:fault,recoveryIdentity:runId===failedRunId?"same-run-native-resume":"authorized-retry-successor", originalRun:{id:failedRunId,status:retainedFailure.status,errorCode:retainedFailure.errorCode,runtimeMode:retainedFailure.runtimeMode, nativeSessionPresent:retainedFailure.nativeSessionId!==null,assignmentCount:failedAssignments.length,resultCount:failedResults.length, costAccountingPending:retainedFailure.costAccountingPending}, @@ -843,10 +893,10 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device operation:{requestId:writeId,journalCount:writeJournals.length,journalStatus:journal.status,sourceEventPresent:journal.sourceEventId!==null}, quiet:{elapsedMs:quietTraceEnd-quietTraceStart,queryCountBefore:before.queryCount,queryCountAfter:quietAfter?.queryCount, callbackCountBefore:before.callbacks, - callbackCountAfter:quietAfter?.callbacks,connectionCountsBefore:before.connections,connectionCountsAfter:quietAfter?.connections,allCreatedClientsObserved:databaseObservation.clients,closedDedicatedOwners:databaseObservation.dedicatedOpen,closedListenerOwners:databaseObservation.listenersOpen}, + callbackCountAfter:quietAfter?.callbacks,connectionCountsBefore:before.connections,connectionCountsAfter:quietAfter?.connections,allCreatedClientsObserved:before.connections.clients,closedDedicatedOwners:before.connections.dedicated,closedListenerOwners:before.connections.listeners}, errorsCount:errors.length,revocationChecksCompleted:true, successorAccounting:{finalRecorded:false,reason:"No added post-settlement accounting query; original443had no final accounting assertion"}, - reconstruction:{appOwners:appOwnerGenerations,cloudOwners:cloudOwnerGenerations,newDbOwners:true,fullProcessRestart:false,masterKeyProvider:"controlled provider port retained outside reconstructed owners",quiet:{elapsedMs:resumedElapsed,before:resumedBefore,after:resumedAfter}}, + reconstruction:{appOwners:appOwnerGenerations,cloudOwners:cloudOwnerGenerations,newDbOwners:true,fullProcessRestart:true,physicalRestart:{first:physicalFollowon.firstIdentity,second:physicalFollowon.secondIdentity},freshUseful2:{taskId:physicalFollowon.taskId,runId:physicalFollowon.runId,assignmentId:physicalFollowon.assignmentId,requestId:physicalFollowon.requestId,lostCommittedReply:physicalFollowon.committedReplyLoss},masterKeyProvider:"controlled provider port retained outside reconstructed owners",quiet:{elapsedMs:resumedElapsed,before:resumedBefore,after:resumedAfter}}, controlledNormalAppCloud:true,hostedCredentialWake:wakeEvidence,originalGrantId:originalGrant.id,codeAndDeviceVerified:true,deviceSelectionRetry:deviceRetryEvidence,eventTransport:{...eventTransportCounts,scope:"controlled exact-owned virtual HTTP; production DNS/peer/SSRF NOT qualified"},subscriptionWitness,fullDotMirrorVerified:true, }),{mode:0o600}); casePassed=true; diff --git a/server/src/__tests__/helpers/owned-linux/checkpointed-fault.ts b/server/src/__tests__/helpers/owned-linux/checkpointed-fault.ts new file mode 100644 index 00000000000..11204bab41d --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/checkpointed-fault.ts @@ -0,0 +1,52 @@ +// PRIVATE UNRUN fixture-only fault. No outcome, grant or lifecycle row writes. +import path from "node:path"; +import { readFile, readdir, writeFile } from "node:fs/promises"; +import { eq } from "drizzle-orm"; +import { z } from "zod"; +import { environmentLeases, type Db } from "@paperclipai/db"; +import type { PluginWorkerManager } from "../../../services/plugin-worker-manager.js"; +import { nativeProviderRecoveryEvidence } from "../../../services/native-runtime/native-session-executor.js"; + +export async function stopCheckpointedOwnedRun(input: { db: Db; workerManager: PluginWorkerManager; + runId: string; companyId: string; environmentId: string; providerRoot: string }) { + // Uses the actual current remote checkpoint/header classifier. An offered + // assignment alone is insufficient. This helper never creates a checkpoint. + const evidence = await nativeProviderRecoveryEvidence({ db: input.db, runId: input.runId, + sourceFailureCode: "native_session_interrupted", executionTargetKind: "remote" }); + if (evidence.recoveryMode !== "exact_checkpoint_resume" || !evidence.checkpointExists || !evidence.providerSessionEstablished) + throw new Error("owned_fault_checkpoint_frontier_not_ready"); + const candidates = (await input.db.select().from(environmentLeases).where(eq(environmentLeases.heartbeatRunId, input.runId))) + .filter(row => row.companyId === input.companyId && row.environmentId === input.environmentId && row.status === "active"); + if (candidates.length !== 1) throw new Error("owned_fault_current_lease_ambiguous"); + const lease = candidates[0]; + const id = z.string().regex(/^dot-linux-[a-f0-9]{24}$/).parse(lease.providerLeaseId); + const pluginId = z.string().min(1).parse(lease.metadata?.pluginId); + const root = path.join(input.providerRoot, id); + const resource = z.object({ id: z.literal(id), companyId: z.literal(input.companyId), + environmentId: z.literal(input.environmentId), runId: z.literal(input.runId), + containerId: z.string().regex(/^[a-f0-9]{64}$/), status: z.literal("active") }).passthrough() + .parse(JSON.parse(await readFile(path.join(root, "resource.json"), "utf8"))); + const custody = path.join(root, "workspace/.qualification-custody"); + const names = (await readdir(custody)).filter(name => /^[a-f0-9-]{36}\.json$/.test(name)); + if (names.length > 128) throw new Error("owned_fault_custody_inventory_overflow"); + const journals = await Promise.all(names.map(async name => JSON.parse(await readFile(path.join(custody, name), "utf8")))); + const proofs = journals.filter(row => row.joined === true && !row.timedOut && !row.overflow && !row.spawnError && row.verifiedNativeKernel); + if (!proofs.length) throw new Error("owned_fault_original_kernel_witness_missing"); + const kernel = z.object({ pid: z.number().int().positive(), group: z.number().int().positive(), + fingerprint: z.string().regex(/^linux:[a-f0-9-]+:[0-9]+$/) }).passthrough().parse(proofs.at(-1).verifiedNativeKernel); + const intent = { runId: input.runId, providerLeaseId: id, containerId: resource.containerId, + kernel, checkpoint: evidence, namespaceTerminationOnly: true }; + const faultFile = path.join(input.providerRoot, "first-native-stop.json"); + await writeFile(faultFile, JSON.stringify({ status: "stop_intent", ...intent }), { flag: "wx", mode: 0o600 }); + // Real verified SDK owner terminates the exact container, then joins actual + // WSS/relay close events. DB lease/Native failure state remain normal owners'. + const termination = z.object({ providerLeaseId: z.literal(id), state: z.literal("stopped") }).strict().parse( + await input.workerManager.call(pluginId, "environmentStopLease", { + driverKey: "dot-linux-qualification", config: { qualificationId: "dot-owned-linux" }, + companyId: input.companyId, environmentId: input.environmentId, providerLeaseId: id, + resourceDisposition: "stop_and_retain", leaseMetadata: lease.metadata ?? undefined, + })); + const receipt = { status: "stopped", ...intent, termination }; + await writeFile(faultFile, JSON.stringify(receipt), { mode: 0o600 }); + return receipt; +} diff --git a/server/src/__tests__/helpers/owned-linux/child-client.ts b/server/src/__tests__/helpers/owned-linux/child-client.ts new file mode 100644 index 00000000000..ff8cf17e12c --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/child-client.ts @@ -0,0 +1,31 @@ +// PRIVATE finite IPC client, matching only actual fixture commands. +import type { ChildProcess } from "node:child_process"; +import type { startNormalDotAppGeneration } from "./normal-app-generation.js"; +import type { installDotChildPorts } from "./child-observation.js"; +export type ChildSnapshot={owner:ReturnType>["snapshot"]>; + database:ReturnType>["snapshot"]>}; +export type ChildControl={command:"snapshot"|"inspect"}|{command:"health";value:"ready"|"unavailable"|"wake-once-then-unavailable"} + |{command:"device-stage";value:"first-select"|"retry-select"|"none"} + |{command:"drain-run";runId:string}|{command:"stop-checkpointed";runId:string;environmentId:string}; +export function attachDotChild(child:ChildProcess,onEvent:(event:Record)=>void){ + let serial=0,failures=0;const pending=new Mapvoid;reject:(error:Error)=>void}>(); + child.on("message",(value:unknown)=>{ + if(!value||typeof value!=="object")return;const event=value as Record; + if(event.kind==="snapshot"&&typeof event.id==="number"){ + const request=pending.get(event.id);if(!request){failures++;return;}pending.delete(event.id); + if(!event.owner||!event.database){request.reject(new Error("owned_child_snapshot_missing"));return;} + request.resolve(event as unknown as ChildSnapshot&{result?:unknown});return; + } + if(event.kind==="failed"){failures++;for(const request of pending.values())request.reject(new Error("owned_child_control_failed"));pending.clear();} + onEvent(event); + }); + child.once("close",()=>{for(const request of pending.values())request.reject(new Error("owned_child_closed_with_pending_control"));pending.clear();}); + return{async request(command:ChildControl,deadline:number){ + const remaining=deadline-performance.now();if(remaining<=0||!child.connected)throw new Error("owned_child_original_deadline_or_transport_unavailable"); + const id=++serial;let timer:ReturnType|undefined; + try{return await new Promise((resolve,reject)=>{ + pending.set(id,{resolve,reject});timer=setTimeout(()=>{pending.delete(id);failures++;reject(new Error("owned_child_original_control_deadline_exhausted"));},remaining); + child.send({...command,id},error=>{if(error){pending.delete(id);failures++;reject(new Error("owned_child_control_send_failed"));}}); + });}finally{clearTimeout(timer);} + },snapshot:()=>({pending:pending.size,failures})}; +} diff --git a/server/src/__tests__/helpers/owned-linux/child-observation.ts b/server/src/__tests__/helpers/owned-linux/child-observation.ts new file mode 100644 index 00000000000..04a66d9c58d --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/child-observation.ts @@ -0,0 +1,95 @@ +// PRIVATE UNRUN. Pass-through observation/owned transport only; no grants, +// ACKs, database results, readiness answers or business outcomes are fabricated. +import assert from "node:assert/strict"; +import { mock } from "node:test"; +import { request } from "node:http"; +import { eq } from "drizzle-orm"; + +export async function installDotChildPorts(input: { + resource: string; cloudOrigin: string; cloudLoopback: string; + callbackPublicOrigin: string; callbackLoopback: string; + deviceStage: () => "first-select"|"retry-select"|undefined; + emit: (event: Record) => void; +}) { + const actual=await import("@paperclipai/db"); + const database={queries:0,clients:0,opened:0,closed:0,dedicated:0,listeners:0}; + const connections=new Set(),observed=new WeakSet(); + const attach=(db:ReturnType)=>{ + if(observed.has(db.$client))return db;observed.add(db.$client);const id=++database.clients; + const debug=db.$client.options.debug,onclose=db.$client.options.onclose; + db.$client.options.debug=(...args)=>{const key=`${id}:${args[0]}`; + if(!connections.has(key)){connections.add(key);database.opened++;}database.queries++; + if(typeof debug==="function")debug(...args);}; + db.$client.options.onclose=connectionId=>{if(connections.delete(`${id}:${connectionId}`))database.closed++; + if(typeof onclose==="function")onclose(connectionId);};return db; + }; + const createDb:(...args:Parameters)=>ReturnType=(...args)=>{ + const db=attach(actual.createDb(...args));attach(actual.livenessDb(db));attach(actual.checkpointDb(db));attach(actual.fileStorageDb(db));return db;}; + mock.module("@paperclipai/db",{namedExports:{...actual,createDb, + withDedicatedDbConnection:async(db:ReturnType,action:(db:ReturnType)=>Promise)=> + actual.withDedicatedDbConnection(db,async dedicated=>{attach(dedicated);database.dedicated++;try{return await action(dedicated);}finally{database.dedicated--;}}), + createOwnedDatabaseListener:(db:ReturnType)=>{const listener=actual.createOwnedDatabaseListener(db);database.listeners++;let closed=false; + return{listen:listener.listen,async close(){await listener.close();if(!closed){closed=true;database.listeners--;}}};}, + }}); + assert.equal((await import("@paperclipai/db")).createDb,createDb,"Child DB observer did not bind actual module graph"); + let authorityRequests=0,callbackRequests=0,unexpectedEventRequests=0,eventFactoryOwners=0,deviceRegistrations=0,authenticateCalls=0,observerPending=0,observerFailures=0,overflow=0,events=0; + const emit=(event:Record)=>{if(events++>=32){overflow++;return;}input.emit(event);}; + const originalFetch=globalThis.fetch; + const mapped:typeof fetch=async(value,init)=>{ + const original=new Request(value,init),url=new URL(original.url); + const target=url.origin===input.cloudOrigin?input.cloudLoopback:url.origin===input.callbackPublicOrigin?input.callbackLoopback:undefined; + if(!target)return originalFetch(value,init); + if(url.protocol!=="https:"||url.username||url.password||url.hash)throw new Error("child_owned_transport_denied"); + const base=new URL(target);assert.equal(base.protocol,"http:");assert.equal(base.hostname,"127.0.0.1"); + const body=original.body?Buffer.from(await original.arrayBuffer()):undefined; + assert((body?.length??0)<=1048576);const headers=Object.fromEntries(original.headers);headers.host=url.host; + return new Promise((resolve,reject)=>{ + const sent=request(new URL(url.pathname+url.search,base),{method:original.method,headers,signal:original.signal,agent:false},response=>{ + const chunks:Buffer[]=[];let bytes=0;response.on("data",part=>{bytes+=part.length;if(bytes>1048576){overflow++;response.destroy(new Error("child_response_overflow"));return;}chunks.push(Buffer.from(part));}); + response.once("error",reject);response.once("end",()=>{const status=response.statusCode!;const headers=new Headers();for(const [name,value]of Object.entries(response.headers))if(value!==undefined)for(const part of Array.isArray(value)?value:[value])headers.append(name,part); + resolve(new Response([204,205,304].includes(status)?null:Buffer.concat(chunks),{status,headers}));}); + });sent.once("error",reject);sent.end(body); + }); + }; + globalThis.fetch=mapped; + const cutover=await import("../../../services/public-mcp/device-cutover.js"); + const {HttpError}=await import("../../../errors.js"); + mock.module(new URL("../../../services/public-mcp/device-cutover.ts",import.meta.url).href,{namedExports:{...cutover, + assertDotDeviceProfileAck:(...args:Parameters)=>{ + const phase=input.deviceStage(),promise=cutover.assertDotDeviceProfileAck(...args); + if(phase){observerPending++;void promise.then(()=>emit({kind:"ack-check",stage:phase,result:"fulfilled"}),error=>emit({kind:"ack-check",stage:phase, + result:error instanceof HttpError&&error.status===503&&error.message==="The hosted Dot connection is being reconciled."?"current-ack-denial":"other"})) + .catch(()=>{observerFailures++;}).finally(()=>{observerPending--;});}return promise; + }}}); + const oauthModule=await import("../../../services/public-mcp/oauth.js"); + mock.module(new URL("../../../services/public-mcp/oauth.ts",import.meta.url).href,{namedExports:{...oauthModule, + createPublicMcpOAuth:(...args:Parameters)=>{ + const ownerDb=args[0],owner=oauthModule.createPublicMcpOAuth(...args);if(owner.mode!=="openai_dot_agent")return owner; + const authenticate=owner.authenticate;owner.authenticate=token=>{authenticateCalls++;return authenticate.call(owner,token);}; + const register=owner.register;owner.register=(...args)=>{const stage=input.deviceStage(),promise=register.apply(owner,args); + if(stage){deviceRegistrations++;observerPending++;void promise.then(async client=>{ + const [row]=await ownerDb.select({revision:actual.mcpOauthClientChanges.revision}).from(actual.mcpOauthClientChanges).where(eq(actual.mcpOauthClientChanges.clientId,client.client_id)); + if(!row||!Number.isSafeInteger(row.revision))throw new Error("child_dcr_revision_missing"); + emit({kind:"dcr-committed",stage,clientId:client.client_id,revision:row.revision}); + }).catch(()=>{observerFailures++;}).finally(()=>{observerPending--;});}return promise;}; + return owner; + }}}); + const eventModule=await import("../../../services/public-mcp/events.js"); + const eventFetch:import("../../../services/public-mcp/event-webhooks.js").EventFetch=(url,init)=>{ + const value=new URL(url);assert.equal(init.method,"POST");assert.equal(init.redirect,"error"); + assert(!value.username&&!value.password&&!value.search&&!value.hash); + if(value.origin===input.cloudOrigin&&value.pathname==="/v1/connector/mcp-dot-subscription-authority")authorityRequests++; + else if(value.origin===input.callbackPublicOrigin&&value.pathname==="/events")callbackRequests++; + else{unexpectedEventRequests++;throw new Error("child_event_transport_denied");} + return mapped(url,init); + }; + mock.module(new URL("../../../services/public-mcp/events.ts",import.meta.url).href,{namedExports:{...eventModule, + createPublicMcpEvents:(...args:Parameters)=>{ + const [db,oauth,dispatch,options]=args; + if(options?.enableDotRunner===true&&oauth.mode==="openai_dot_agent"&&oauth.config.resource===input.resource){ + eventFactoryOwners++;return eventModule.createPublicMcpEvents(db,oauth,dispatch,{...options,fetch:eventFetch});} + return eventModule.createPublicMcpEvents(...args); + }}}); + return{snapshot:()=>({...database,connections:connections.size,eventFactoryOwners,authorityRequests,callbackRequests,unexpectedEventRequests,deviceRegistrations,authenticateCalls,observerPending,observerFailures,overflow}), + restore(){globalThis.fetch=originalFetch;mock.restoreAll();}}; +} diff --git a/server/src/__tests__/helpers/owned-linux/committed-reply-loss.ts b/server/src/__tests__/helpers/owned-linux/committed-reply-loss.ts new file mode 100644 index 00000000000..9826e4ca172 --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/committed-reply-loss.ts @@ -0,0 +1,76 @@ +// PRIVATE UNRUN transport fault for ONE actual committed Dot operation. +// No business row/result/receipt write. All tokens/bytes stay off diagnostics. +import { createServer, request as httpRequest, type IncomingHttpHeaders } from "node:http"; +import type { Socket } from "node:net"; +import { once } from "node:events"; +import { externalOperationDigest } from "../../../vendor/paperclip-runner/index.js"; + +export async function createCommittedReplyLoss(input: { + cloudLoopback: string; + assignmentId: string; + requestId: string; + inputDigest: string; + // Existing original operation-status/DB/document assertions, bounded by the + // original10-second operation deadline and90-second case. No added observer. + awaitActualCommit(): Promise; +}) { + const backend = new URL(input.cloudLoopback); + if (backend.protocol !== "http:" || backend.hostname !== "127.0.0.1" || backend.username || backend.password + || backend.pathname !== "/" || backend.search || backend.hash) throw new Error("owned_reply_loss_backend_denied"); + const sockets = new Set(), pending = new Set>(); + let observedDropClose: (()=>void)|undefined; + const droppedResponseClosed=new Promise(resolve=>{observedDropClose=resolve;}); + const evidence = { armed: true, selected: 0, backendCompleted: 0, committed: 0, dropped: 0, closedAfterDrop: 0, overflow: 0, observerFailures: 0 }; + const server = createServer((request, response) => { + const work = (async () => { + const chunks: Buffer[] = []; let bytes = 0; + for await (const part of request) { bytes += Buffer.byteLength(part); if (bytes > 1048576) { evidence.overflow++; throw new Error("reply_loss_request_overflow"); } chunks.push(Buffer.from(part)); } + const body = Buffer.concat(chunks); let selected = false; + if (evidence.armed && request.method === "POST" && request.url === "/mcp/runner") { + const value = JSON.parse(body.toString("utf8")), args = value?.params?.arguments; + if (value?.method === "tools/call" && value?.params?.name === "paperclip_dot_tool" && args && typeof args === "object" + && args.assignmentId === input.assignmentId && args.requestId === input.requestId) { + const { assignmentId: _assignment, requestId: _request, ...actualInput } = args; + if (externalOperationDigest("tool", actualInput) !== input.inputDigest) throw new Error("reply_loss_input_mismatch"); + evidence.armed = false; evidence.selected++; selected = true; + } + } + const upstream = httpRequest({ hostname: backend.hostname, port: backend.port, path: request.url, method: request.method, + headers: request.headers, agent: false }); + const result = await new Promise<{ status: number; headers: IncomingHttpHeaders; body: Buffer }>((resolve, reject) => { + upstream.once("error", reject); upstream.once("response", incoming => { + const parts: Buffer[] = []; let length = 0; + incoming.on("data", part => { length += Buffer.byteLength(part); if (length > 1048576) { evidence.overflow++; return; } parts.push(Buffer.from(part)); }); + incoming.once("error", reject); incoming.once("end", () => length > 1048576 ? reject(new Error("reply_loss_response_overflow")) + : resolve({ status: incoming.statusCode ?? 0, headers: incoming.headers, body: Buffer.concat(parts) })); + }); upstream.end(body); + }); + if (selected) { + // The actual handler/transaction/HTTP response has ended. Holding this + // CLIENT response cannot retain its DB lock or fake an ACK/outcome. + evidence.backendCompleted++; + const value = JSON.parse(result.body.toString("utf8")); + if (result.status !== 200 || value?.result?.isError !== false) throw new Error("reply_loss_actual_operation_refused"); + try { await input.awaitActualCommit(); evidence.committed++; } + catch (error) { evidence.observerFailures++; throw error; } + evidence.dropped++; + response.once("close", () => { evidence.closedAfterDrop++; observedDropClose?.(); }); + // Deliberate ONE request fault, not cleanup or a timeout/guard bypass. + response.destroy(); return; + } + response.writeHead(result.status, result.headers); response.end(result.body); + })(); + pending.add(work); void work.catch(() => { evidence.observerFailures++; if (!response.headersSent) response.writeHead(502); response.end(); }).finally(() => pending.delete(work)); + }); + server.on("connection", socket => { sockets.add(socket); socket.once("close", () => sockets.delete(socket)); }); + server.listen(0, "127.0.0.1"); await once(server, "listening"); const address = server.address(); + if (!address || typeof address === "string") throw new Error("owned_reply_loss_listener_missing"); + return { origin: `http://127.0.0.1:${address.port}`, evidence, droppedResponseClosed, + async close() { + const joins = [...sockets].map(socket => once(socket, "close")); + const stopped = new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); + await Promise.all([stopped, ...joins, ...pending]); + if (sockets.size || pending.size) throw new Error("owned_reply_loss_close_unknown"); + }, + }; +} diff --git a/server/src/__tests__/helpers/owned-linux/linux-command-relay.mjs b/server/src/__tests__/helpers/owned-linux/linux-command-relay.mjs new file mode 100644 index 00000000000..662eb79d9bc --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/linux-command-relay.mjs @@ -0,0 +1,81 @@ +// PRIVATE UNRUN fixture source. One JSON request over stdin, never secret argv. +import { spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import { readFile, writeFile, mkdir, realpath } from "node:fs/promises"; +import path from "node:path"; +import { kernelIdentity, launchFromActualCommand, readActualRunnerProof } from "./linux-process-custody.mjs"; + +const fail = code => Object.assign(new Error(code), { code }); +const limit = 4 * 1024 * 1024; +const chunks = []; let size = 0; +try { + if (process.platform !== "linux" || process.versions.node !== "24.22.2") throw fail("linux_node_identity_required"); + for await (const chunk of process.stdin) { size += chunk.length; if (size > limit) throw fail("request_overflow"); chunks.push(chunk); } + const request = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks))); + // Resource descriptor is a private mount written by the host for ONE lease. + const descriptorPath = process.argv[2]; + const descriptor = JSON.parse(await readFile(descriptorPath, "utf8")); + if (descriptor.containerId !== request.containerId || descriptor.id !== request.providerLeaseId + || descriptor.runId !== request.runId || descriptor.nonce !== request.nonce || descriptor.companyId !== request.companyId || descriptor.environmentId !== request.environmentId) throw fail("foreign_lease_request"); + const root = await realpath(descriptor.root); + if (root !== descriptor.root || root === "/" || request.command?.length > 4096 || !request.command || !Array.isArray(request.args) + || request.args.some(value => typeof value !== "string" || value.length > 131072)) throw fail("invalid_command_request"); + const cwd = await realpath(request.cwd ?? root); + if (cwd !== root && !cwd.startsWith(root + "/")) throw fail("foreign_command_cwd"); + const deadline = request.timeoutMs; + if (!Number.isSafeInteger(deadline) || deadline < 1 || deadline > 90000) throw fail("command_budget_invalid"); + const environment = { PATH: "/usr/local/bin:/usr/bin:/bin", HOME: path.join(root, "home"), TMPDIR: path.join(root, "tmp") }; + for (const [key, value] of Object.entries(request.env ?? {})) { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || typeof value !== "string" || value.includes("\0")) throw fail("command_environment_invalid"); + // Normal Runner supplies its controlled PATH. Never inherit this relay's env. + environment[key] = value; + } + await mkdir(environment.HOME, { recursive: true }); await mkdir(environment.TMPDIR, { recursive: true }); + const launch = launchFromActualCommand(descriptor, request); + const ledgerDirectory = path.join(root, ".qualification-custody"); await mkdir(ledgerDirectory, { recursive: true, mode: 0o700 }); + if (!/^[a-f0-9-]{36}$/.test(request.requestId)) throw fail("request_identity_invalid"); + const journal = path.join(ledgerDirectory, request.requestId + ".json"); + // Exclusive record before dispatch: unknown response must not silently reexecute. + await writeFile(journal, JSON.stringify({ status: "dispatch_recorded", requestId: request.requestId, launch }), { flag: "wx", mode: 0o600 }); + if (launch) { + if (descriptor.launchDescriptor !== path.join(ledgerDirectory, "active-launch.json")) throw fail("launch_journal_path_invalid"); + await writeFile(descriptor.launchDescriptor, JSON.stringify(launch), { flag: "wx", mode: 0o600 }); + } + const child = spawn(request.command, request.args, { cwd, env: environment, detached: true, stdio: ["pipe", "pipe", "pipe"] }); + const stdout = [], stderr = []; let bytes = 0, overflow = false, timedOut = false, spawnError = false, kernel = null; + const collect = output => chunk => { bytes += chunk.length; if (bytes > limit) { overflow = true; return; } output.push(chunk); }; + child.stdout.on("data", collect(stdout)); child.stderr.on("data", collect(stderr)); + child.on("error", () => { spawnError = true; }); + const joined = new Promise(resolve => child.once("close", (exitCode, signal) => resolve({ exitCode, signal }))); + if (child.pid) { try { kernel = await kernelIdentity(child.pid); } catch (error) { if (!["ENOENT", "ESRCH"].includes(error.code)) throw error; } } + child.stdin.on("error", () => {}); child.stdin.end(request.stdin ?? ""); + // Signals only this child handle; a timeout is retained UNKNOWN until all + // detached descendants/normal Runner identities are separately reconciled. + const timer = setTimeout(() => { timedOut = true; child.kill("SIGTERM"); }, deadline); + const exit = await joined; clearTimeout(timer); + let proof = null; + // Normal launch detaches before the marker is ready. Observe ONLY the + // existing host waitForRemoteRunnerProcessIdentity successful read, not a + // new provider poll or an immediate post-launch marker assumption. + if (!timedOut && !overflow && !spawnError && exit.exitCode === 0 + && request.command === "sh" && request.args[2] === "paperclip-runner-process-identity") { + const active = JSON.parse(await readFile(descriptor.launchDescriptor, "utf8")); + if (request.args[3] !== active.marker) throw fail("foreign_identity_read"); + proof = await readActualRunnerProof(descriptor, active); + } + if (kernel) { const { argv: _privateArgv, ...safeKernel } = kernel; kernel = safeKernel; } + const response = { requestId: request.requestId, ...exit, pid: child.pid ?? null, group: child.pid ?? null, + kernel, joined: true, timedOut, overflow, spawnError, launch, proof, + stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8") }; + const hash = chunks => createHash("sha256").update(Buffer.concat(chunks)).digest("hex"); + await writeFile(journal, JSON.stringify({ requestId: request.requestId, ...exit, pid: response.pid, group: response.group, + joined: true, timedOut, overflow, spawnError, kernel, verifiedNativeKernel: proof?.kernel ?? null, + stdoutBytes: Buffer.concat(stdout).length, stderrBytes: Buffer.concat(stderr).length, stdoutSHA256: hash(stdout), stderrSHA256: hash(stderr) }), { mode: 0o600 }); + process.stdout.write(JSON.stringify(response)); + if (timedOut || overflow || spawnError) process.exitCode = 1; +} catch (error) { + // Fixed classification only. Child/remote stderr and request material are NOT + // attached as a cause or reflected in control-plane error/log output. + process.stdout.write(JSON.stringify({ error: typeof error?.code === "string" && /^[a-z_]+$/.test(error.code) ? error.code : "linux_relay_failed", unknownOutcome: true })); + process.exitCode = 1; +} diff --git a/server/src/__tests__/helpers/owned-linux/linux-process-custody.mjs b/server/src/__tests__/helpers/owned-linux/linux-process-custody.mjs new file mode 100644 index 00000000000..37c972e0ffb --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/linux-process-custody.mjs @@ -0,0 +1,95 @@ +// Private fixture provider custody. Reads the real Linux kernel only; no polling, +// synthetic /proc data, host PID signal or public/product authority is added. +import { createHash } from "node:crypto"; +import { createReadStream } from "node:fs"; +import { lstat, readFile, readlink, readdir, realpath } from "node:fs/promises"; +import path from "node:path"; + +const closed = (code) => Object.assign(new Error(code), { code }); +const inside = (root, value) => path.isAbsolute(value) && path.resolve(root) === root && path.resolve(value) === value && (value === root || value.startsWith(root + "/")); +export async function fileDigest(file) { + const hash = createHash("sha256"); for await (const chunk of createReadStream(file)) hash.update(chunk); return hash.digest("hex"); +} +export async function kernelIdentity(pid) { + if (process.platform !== "linux" || !Number.isSafeInteger(pid) || pid < 1) throw closed("linux_identity_required"); + const stat = await readFile(`/proc/${pid}/stat`, "utf8"), end = stat.lastIndexOf(") "); + if (end < 0) throw closed("kernel_stat_invalid"); + const fields = stat.slice(end + 2).trim().split(/\s+/), ticks = fields[19]; + const bootId = (await readFile("/proc/sys/kernel/random/boot_id", "utf8")).trim(); + if (!/^[-a-f0-9]+$/.test(bootId) || !/^\d+$/.test(ticks ?? "")) throw closed("kernel_start_invalid"); + return { pid, ppid: Number(fields[1]), group: Number(fields[2]), session: Number(fields[3]), + ticks, bootId, fingerprint: `linux:${bootId}:${ticks}`, pidNamespace: await readlink("/proc/self/ns/pid"), + executable: await readlink(`/proc/${pid}/exe`), argv: (await readFile(`/proc/${pid}/cmdline`)).toString().split("\0").filter(Boolean) }; +} +export function launchFromActualCommand(resource, command) { + const args = command.args ?? []; + if (command.command !== "sh" || args[2] !== "paperclip-runner-launch") return null; + const marker = args[3], nonce = args[4], runnerId = args[5], binary = args[8]; + if (!inside(resource.root, marker) || path.basename(marker) !== "runner-process.identity" || !nonce || !runnerId + || binary !== path.join(resource.root, ".paperclip-runtime/paperclip-runner/bin/paperclip-runnerd")) throw closed("foreign_launch_descriptor"); + const stateRoot = path.dirname(marker), index = args.indexOf("--state-dir", 9); + if (index < 0 || args[index + 1] !== stateRoot || !stateRoot.startsWith(path.join(resource.root, ".paperclip-runtime/paperclip-runner/sessions/"))) throw closed("foreign_runner_state_root"); + // Record this before executing the ORIGINAL command. A lost launch response is + // UNKNOWN, never an inference that no detached process exists. + return { marker, nonce, runnerId, binary, stateRoot, runId: resource.runId, companyId: resource.companyId, environmentId: resource.environmentId, + providerLeaseId: resource.id, containerId: resource.containerId, status: "dispatch_recorded" }; +} +export async function readActualRunnerProof(resource, launch) { + if (!launch || launch.containerId !== resource.containerId || launch.providerLeaseId !== resource.id) throw closed("launch_custody_missing"); + const stat = await lstat(launch.marker); + if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 4096 || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid() || await realpath(launch.marker) !== launch.marker) throw closed("marker_owner_unknown"); + const rawMarker = await readFile(launch.marker, "utf8"); + const [nonce, rawPid, startedAt, runnerId, fingerprint, ...extra] = rawMarker.trim().split("\n"); + if (extra.length || nonce !== launch.nonce || runnerId !== launch.runnerId || !startedAt || Number.isNaN(Date.parse(startedAt)) || !/^linux:[-a-f0-9]+:\d+$/.test(fingerprint ?? "")) throw closed("marker_identity_mismatch"); + const kernel = await kernelIdentity(Number(rawPid)); + const arg = (flag) => { const index = kernel.argv.indexOf(flag); return index < 0 ? undefined : kernel.argv[index + 1]; }; + if (kernel.fingerprint !== fingerprint || arg("--runner-id") !== runnerId || arg("--state-dir") !== launch.stateRoot + || kernel.executable !== launch.binary || await fileDigest(`/proc/${kernel.pid}/exe`) !== resource.expectedRunnerSHA256) throw closed("live_runner_identity_mismatch"); + const { argv: _privateArgv, ...safeKernel } = kernel; + return { rawMarker, startedAt, kernel: safeKernel, marker: launch.marker, stateRoot: launch.stateRoot, nonce, runnerId, + providerLeaseId: resource.id, companyId: resource.companyId, environmentId: resource.environmentId, runId: resource.runId, containerId: resource.containerId }; +} +export async function proveListener(proof, port) { + const current = await kernelIdentity(proof.kernel.pid); + if (current.pidNamespace !== proof.kernel.pidNamespace || current.fingerprint !== proof.kernel.fingerprint || current.group !== proof.kernel.group) throw closed("ingress_process_replaced"); + const fds = await readdir(`/proc/${current.pid}/fd`); if (fds.length > 4096) throw closed("ingress_fd_inventory_overflow"); + const inodes = new Set(); + for (const fd of fds) { try { const target = await readlink(`/proc/${current.pid}/fd/${fd}`), match = /^socket:\[(\d+)\]$/.exec(target); if (match) inodes.add(match[1]); } catch (error) { if (error.code !== "ENOENT") throw error; } } + for (const table of ["tcp", "tcp6"]) { + const rows = (await readFile(`/proc/${current.pid}/net/${table}`, "utf8")).trim().split("\n").slice(1); + for (const row of rows) { const fields = row.trim().split(/\s+/), address = fields[1]?.split(":"); + if (fields[3] === "0A" && Number.parseInt(address?.[1] ?? "", 16) === port && inodes.has(fields[9])) return; + } + } + throw closed("owned_runner_listener_not_proven"); +} +export async function groupMembers(group) { + const entries = (await readdir("/proc")).filter(value => /^\d+$/.test(value)); + if (entries.length > 256) throw closed("owned_pid_inventory_overflow"); + const members = []; + for (const entry of entries) { + try { + // Stat-only inventory retains zombies too: exe/cmdline may disappear + // before wait/reaping. A missing exe is never group-absence proof. + const stat = await readFile(`/proc/${entry}/stat`, "utf8"), end = stat.lastIndexOf(") "); + if (end < 0) throw closed("kernel_stat_invalid"); + const fields = stat.slice(end + 2).trim().split(/\s+/); + if (Number(fields[2]) === group) members.push({ pid: Number(entry), group, state: fields[0], ticks: fields[19] }); + } catch (error) { if (!['ENOENT', 'ESRCH'].includes(error.code)) throw error; } + } + return members; +} +export async function proveRetirement(resource, ledger) { + if (!ledger.launches.length || ledger.launches.some(launch => !launch.verified)) throw closed("native_launch_unknown_retained"); + if (ledger.commands.some(command => !command.joined || !Number.isSafeInteger(command.pid) || command.group !== command.pid)) throw closed("command_join_unknown_retained"); + for (const launch of ledger.launches) { + try { await readFile(`/proc/${launch.verified.kernel.pid}/stat`, "utf8"); throw closed("runner_live_zombie_or_reused_retained"); } + catch (error) { if (!['ENOENT', 'ESRCH'].includes(error.code)) throw error; } + } + for (const group of new Set([...ledger.commands.map(command => command.group), ...ledger.launches.map(launch => launch.verified.kernel.group)])) { + if ((await groupMembers(group)).length) throw closed("owned_group_still_present_retained"); + } + if (ledger.usedIngressSockets !== 0) throw closed("ingress_close_not_joined_retained"); + return { providerLeaseId: resource.id, state: "stopped", containerId: resource.containerId, + companyId: resource.companyId, environmentId: resource.environmentId, runId: resource.runId, pidNamespace: await readlink("/proc/self/ns/pid") }; +} diff --git a/server/src/__tests__/helpers/owned-linux/linux-runner-ingress.mjs b/server/src/__tests__/helpers/owned-linux/linux-runner-ingress.mjs new file mode 100644 index 00000000000..e4ef7355456 --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/linux-runner-ingress.mjs @@ -0,0 +1,44 @@ +// PRIVATE UNRUN Linux-side ingress. One descriptor-authenticated JSON line, +// then raw upgrade bytes over stdin. No ports published by this module. +import net from "node:net"; +import { readFile } from "node:fs/promises"; +import { readActualRunnerProof, proveListener } from "./linux-process-custody.mjs"; + +const fail = code => Object.assign(new Error(code), { code }); +let input = Buffer.alloc(0), remote = null; +try { + if (process.platform !== "linux" || process.versions.node !== "24.22.2") throw fail("linux_node_identity_required"); + const request = await new Promise((resolve, reject) => { + const onData = chunk => { + input = Buffer.concat([input, chunk]); const end = input.indexOf(10); + if (input.length > 16384 && end < 0) { process.stdin.off("data", onData); reject(fail("ingress_request_overflow")); return; } + if (end < 0) return; + process.stdin.pause(); process.stdin.off("data", onData); + try { const line = input.subarray(0, end); input = input.subarray(end + 1); resolve(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(line))); } + catch { reject(fail("ingress_request_invalid")); } + }; + process.stdin.on("data", onData); process.stdin.once("error", reject); + }); + const resource = JSON.parse(await readFile(process.argv[2], "utf8")); + if (request.nonce !== resource.nonce || request.runId !== resource.runId + || request.providerLeaseId !== resource.id || request.containerId !== resource.containerId + || request.companyId !== resource.companyId || request.environmentId !== resource.environmentId + || !Number.isSafeInteger(request.port) || request.port < 1 || request.port > 65535) throw fail("ingress_lease_mismatch"); + // The launch descriptor is recorded by the original actual command BEFORE + // execution. Marker + boot/ticks + exe SHA + real listener inode must agree. + const launch = JSON.parse(await readFile(resource.launchDescriptor, "utf8")); + const proof = await readActualRunnerProof(resource, launch); await proveListener(proof, request.port); + remote = net.connect({ host: "127.0.0.1", port: request.port }); + await new Promise((resolve, reject) => { remote.once("connect", resolve); remote.once("error", reject); }); + process.stdout.write(JSON.stringify({ ready: true, rawMarker: proof.rawMarker, nonce: proof.nonce, runnerId: proof.runnerId, kernel: proof.kernel, companyId: resource.companyId, environmentId: resource.environmentId, + providerLeaseId: resource.id, containerId: resource.containerId }) + "\n"); + if (input.length) remote.write(input); + process.stdin.pipe(remote); remote.pipe(process.stdout); process.stdin.resume(); + const closed = new Promise(resolve => remote.once("close", resolve)); + process.stdin.once("end", () => remote.end()); + remote.once("error", () => { process.exitCode = 1; }); + await closed; +} catch (error) { + process.stderr.write(typeof error?.code === "string" && /^[a-z_]+$/.test(error.code) ? error.code : "linux_ingress_failed"); + process.exitCode = 1; +} finally { if (remote && !remote.closed) remote.end(); } diff --git a/server/src/__tests__/helpers/owned-linux/normal-app-child.ts b/server/src/__tests__/helpers/owned-linux/normal-app-child.ts new file mode 100644 index 00000000000..4d23e4e7c5c --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/normal-app-child.ts @@ -0,0 +1,67 @@ +// PRIVATE UNRUN physical child. Same entry for FIRST and SECOND generations. +import assert from "node:assert/strict"; +import path from "node:path"; +import { readFile } from "node:fs/promises"; +import { randomUUID } from "node:crypto"; +import { z } from "zod"; +import { beginOwnedPrivateCA } from "./private-ca-scope.js"; +import { installDotChildPorts } from "./child-observation.js"; +const file=process.env.PAPERCLIP_DOT_CHILD_INPUT;assert(file&&path.isAbsolute(file)); +const absolute=z.string().refine(value=>path.isAbsolute(value)); +const loopback=z.url().refine(value=>{const url=new URL(value);return url.protocol==="http:"&&url.hostname==="127.0.0.1"&&!url.username&&!url.password&&!url.search&&!url.hash;}); +const input=z.object({stackId:z.string().min(1),databaseUrl:z.url(),home:absolute,origin:z.url(),userId:z.string().min(1),companyId:z.uuid(),generation:z.number().int().min(1).max(2), + resource:z.url(),cloudOrigin:z.url(),cloudLoopback:loopback,callbackPublicOrigin:z.url(),callbackLoopback:loopback, + linuxInput:z.object({catalogRoot:absolute,prebuiltPackageRoot:absolute,expectedBundleDigest:z.string().regex(/^sha256:[a-f0-9]{64}$/),providerRoot:absolute,remoteBinary:absolute,caBundle:absolute,caSHA256:z.string().regex(/^[a-f0-9]{64}$/)}).strict(), +}).strict().parse(JSON.parse(await readFile(file,"utf8"))); +const database=new URL(input.databaseUrl);assert(database.hostname==="127.0.0.1"&&database.port==="55448"&&database.pathname.endsWith("_test")); +assert.equal(process.versions.node,"24.22.2");assert(process.send&&process.connected); +let health:"ready"|"unavailable"|"wake-once-then-unavailable"="ready"; +let stage:"first-select"|"retry-select"|undefined; +const send=(event:Record)=>{if(!process.connected)throw new Error("owned_child_ipc_disconnected");process.send!(event);}; +const restoreCA=beginOwnedPrivateCA({pem:await readFile(input.linuxInput.caBundle,"utf8"),SHA256:input.linuxInput.caSHA256}); +let ports:Awaited>; +try{ports=await installDotChildPorts({...input,deviceStage:()=>stage,emit:send});} +catch(primary){try{restoreCA();}catch(cleanup){throw new AggregateError([primary,cleanup],"owned_dot_child_port_setup_failed");}throw primary;} +let owner:Awaited>|undefined; +let shutting:Promise|undefined; +const shutdown=()=>shutting??=(async()=>{ + try{await owner?.stop();const snapshot=ports.snapshot();assert.equal(snapshot.connections,0);assert.equal(snapshot.dedicated,0);assert.equal(snapshot.listeners,0); + assert.equal(snapshot.observerPending,0);assert.equal(snapshot.observerFailures,0);assert.equal(snapshot.overflow,0); + send({kind:"stopped",pid:process.pid,owner:owner?.snapshot(),snapshot}); + }finally{try{ports.restore();}finally{restoreCA();}} +})(); +try{ + const {startNormalDotAppGeneration}=await import("./normal-app-generation.js"); + owner=await startNormalDotAppGeneration({...input,health:()=>health,consumedWakeHealth:()=>{health="unavailable";}}); + const port=Number(new URL(owner.origin).port);send({kind:"ready",pid:process.pid,port,bootId:randomUUID()}); + process.on("message",async(raw:unknown)=>{ + try{ + const message=z.discriminatedUnion("command",[ + z.object({command:z.literal("snapshot"),id:z.number().int()}).strict(), + z.object({command:z.literal("health"),id:z.number().int(),value:z.enum(["ready","unavailable","wake-once-then-unavailable"])}).strict(), + z.object({command:z.literal("device-stage"),id:z.number().int(),value:z.enum(["first-select","retry-select","none"])}).strict(), + z.object({command:z.literal("drain-run"),id:z.number().int(),runId:z.uuid()}).strict(), + z.object({command:z.literal("stop-checkpointed"),id:z.number().int(),runId:z.uuid(),environmentId:z.uuid()}).strict(), + z.object({command:z.literal("inspect"),id:z.number().int()}).strict(), + z.object({command:z.literal("shutdown")}).strict(), + ]).parse(raw); + if(message.command==="shutdown"){await shutdown();process.disconnect();return;} + if(message.command==="health")health=message.value; + if(message.command==="device-stage")stage=message.value==="none"?undefined:message.value; + let result:unknown; + if(message.command==="drain-run")await owner!.heartbeat.waitForRunExecutionDrain(message.runId,{timeoutMs:15000}); + if(message.command==="stop-checkpointed"){ + const {stopCheckpointedOwnedRun}=await import("./checkpointed-fault.js"); + result=await stopCheckpointedOwnedRun({db:owner!.db,workerManager:owner!.workerManager,runId:message.runId, + companyId:input.companyId,environmentId:message.environmentId,providerRoot:input.linuxInput.providerRoot}); + } + if(message.command==="inspect"){ + const {readIdleMcpSleepProof}=await import("../../../services/public-mcp/idle-sleep-proof.js"); + result=await readIdleMcpSleepProof(owner!.db,owner!.db,{stackId:input.stackId,ownerId:randomUUID(), + capabilityGeneration:"a".repeat(64),challenge:"b".repeat(64),now:Date.now(),budget:{beforeRead:async()=>{},check:()=>{}}}); + } + send({kind:"snapshot",id:message.id,result,owner:owner!.snapshot(),database:ports.snapshot()}); + }catch{send({kind:"failed",code:"owned_child_command_failed"});process.exitCode=1;} + }); + process.once("disconnect",()=>{void shutdown().catch(()=>{process.exitCode=1;});}); +}catch(primary){try{await shutdown();}catch(cleanup){throw new AggregateError([primary,cleanup],"owned_dot_child_failed_retained");}throw primary;} diff --git a/server/src/__tests__/helpers/owned-linux/normal-app-generation.ts b/server/src/__tests__/helpers/owned-linux/normal-app-generation.ts new file mode 100644 index 00000000000..33e85351dab --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/normal-app-generation.ts @@ -0,0 +1,133 @@ +// PRIVATE UNRUN extraction of the SAME v4 normal App owner graph. +// Target: server/src/__tests__/helpers/owned-linux/normal-app-generation.ts +import assert from "node:assert/strict"; +import path from "node:path"; +import { createServer } from "node:http"; +import { once } from "node:events"; +import { eq } from "drizzle-orm"; +import { createDb, closeRegisteredClients, authUsers, agents } from "@paperclipai/db"; +import { prepareOwnedLinuxDistribution } from "./normal-distribution-bootstrap.js"; +import { heartbeatService } from "../../../services/heartbeat.js"; +import { setupRunnerPrpWebSocketServer } from "../../../realtime/runner-prp-ws.js"; +import { migrateCloudConfiguration } from "../../../services/cloud-configuration-migration.js"; +import { initializeAdapterSettings } from "../../../services/adapter-settings.js"; +import { initializeCloudRuntimeConfig } from "../../../services/cloud-runtime-config.js"; +import { createCloudWarmStandby } from "../../../services/cloud-warm-standby.js"; +import { getCloudRuntimeIdentity, initializeCloudRuntimeIdentity, resetCloudRuntimeIdentityForTests, resetCloudControlReplayFenceForTests } from "../../../services/cloud-runtime-identity.js"; +import { createStorageService } from "../../../storage/service.js"; +import { createLocalDiskStorageProvider } from "../../../storage/local-disk-provider.js"; +import { isIdleTaskDrainActive, idleWorkSnapshot } from "../../../services/task-admission.js"; +import { registerNativeCancellationDelivery } from "../../../services/native-runtime/native-cancellation-delivery.js"; +import { registerNativeRuntimeResponseDelivery } from "../../../services/native-runtime/native-runtime-response-delivery.js"; +import { registerNativeCleanupReleaseWake } from "../../../services/native-runtime/native-cleanup-release-wake.js"; +import { registerCostAccountingWork, registerBudgetEnforcementWork } from "../../../services/budget-enforcement-worker.js"; +import { deliverBudgetResumeContinuations, type BudgetResumeDelivery } from "../../../services/budget-resume-continuation.js"; +import type { Socket } from "node:net"; + +export async function startNormalDotAppGeneration(input: { + databaseUrl: string; home: string; origin: string; userId: string; companyId: string; generation: number; + linuxInput: Parameters[0]; + health: () => "ready"|"unavailable"|"wake-once-then-unavailable"; + consumedWakeHealth: () => void; +}) { + const errors: unknown[]=[]; let unexpectedDecisionWakes=0,sessionCalls=0; + const healthStatuses:number[]=[];let healthOverflow=0; + const linuxBootstrap=await prepareOwnedLinuxDistribution(input.linuxInput); + const db=createDb(input.databaseUrl,{maxConnections:2,applicationName:"dot-principal-normal-app"}); + const nativeSockets=new Set(); + let dispatchWork:ReturnType["registerRunDispatchWork"]>|undefined; + let stopBudgetOwners:(()=>Promise)|undefined; + let app:Awaited>|undefined; + let owner:ReturnType|undefined; + let appServer:ReturnType|undefined; + let stopping:Promise|undefined; + const stop=()=>stopping??=(async()=>{ + // Same real owner order, with no signals or broad process cleanup. A child + // must not exit0 until all normal execution/plugin/DB/socket owners close. + await dispatchWork?.stop(); + if(owner){ + const ownedAgents=await db.select({id:agents.id}).from(agents).where(eq(agents.companyId,input.companyId)); + await owner.stopInvocationsForAgents(ownedAgents.map(agent=>agent.id),"Owned physical App generation shutdown"); + await owner.drainActiveRunExecutions(); + } + await stopBudgetOwners?.();await app?.locals.paperclipShutdown?.(); + await linuxBootstrap.workerManager.stopAll(); + if(appServer){ + const joins=[...nativeSockets].map(socket=>once(socket,"close")); + await Promise.all([new Promise((resolve,reject)=>appServer!.close(error=>error?reject(error):resolve())),...joins]); + } + assert.equal(nativeSockets.size,0,"all actual owned close events must be joined"); + await db.$client.end({timeout:1});await closeRegisteredClients(input.databaseUrl,{scope:"database"}); + assert.equal(unexpectedDecisionWakes,0);assert.deepEqual(errors,[]); + })(); + try{ + await migrateCloudConfiguration(db);await initializeAdapterSettings(db);await initializeCloudRuntimeConfig(db); + resetCloudRuntimeIdentityForTests();resetCloudControlReplayFenceForTests();await initializeCloudRuntimeIdentity(db); + const standby=await createCloudWarmStandby(db);assert.equal(standby(),input.generation===1); + const {createApp}=await import("../../../app.js"); + const budgetResumeDelivery:BudgetResumeDelivery={}; + app=await createApp(db,{...linuxBootstrap.appOptions,budgetResumeDelivery,uiMode:"none",serverPort:3100, + storageService:createStorageService(createLocalDiskStorageProvider(path.join(input.home,"objects"))), + deploymentMode:"authenticated",deploymentExposure:"private",bindHost:"127.0.0.1",allowedHostnames:[new URL(input.origin).hostname], + authPublicBaseUrl:input.origin,authReady:true,companyDeletionEnabled:false,cloudWarmStandby:standby, + decisionServiceOptions:{wakeOriginAgent:async()=>{unexpectedDecisionWakes++;throw new Error("Unexpected Decision dependency in closed Dot journey");}}, + resolveSession:async req=>{sessionCalls++;if(req.get("x-selected-operator")!==input.userId)return null; + const [user]=await db.select().from(authUsers).where(eq(authUsers.id,input.userId)); + return user?{session:{id:"principal-hop-session",userId:input.userId},user}:null;}}); + await app.locals.bundledPluginsStartup; + const actualApp=app; + appServer=createServer((req,res)=>{ + if(req.method==="GET"&&(req.url??"").split("?",1)[0]==="/api/health"&&input.health()!=="ready"){ + if(healthStatuses.length<32)res.once("finish",()=>healthStatuses.push(res.statusCode));else healthOverflow++; + if(input.health()==="wake-once-then-unavailable")input.consumedWakeHealth(); + else{res.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({status:"unavailable"}));return;} + } + actualApp(req,res); + }); + appServer.on("connection",socket=>{nativeSockets.add(socket);socket.once("close",()=>nativeSockets.delete(socket));}); + setupRunnerPrpWebSocketServer(appServer); + await new Promise((resolve,reject)=>{appServer!.once("error",reject);appServer!.listen(0,"127.0.0.1",resolve);}); + const address=appServer.address();assert(address&&typeof address!=="string"); + const origin=`http://127.0.0.1:${address.port}`; + Object.assign(process.env,{PAPERCLIP_API_URL:origin,PAPERCLIP_RUNTIME_API_URL:origin,PAPERCLIP_LISTEN_HOST:"127.0.0.1",PAPERCLIP_LISTEN_PORT:String(address.port)}); + const coordinator=app.locals.deliveryWork;assert(coordinator&&typeof coordinator.register==="function"); + const normalOwner=heartbeatService(db,{pluginWorkerManager:linuxBootstrap.workerManager});owner=normalOwner; + const canRun=()=>!isIdleTaskDrainActive()&&!standby(); + await normalOwner.registerResidualRecoveryWork(coordinator,canRun).ready; + await normalOwner.registerActiveRunSilenceWork(coordinator,canRun).ready; + await normalOwner.registerIssueStateRecoveryWork(coordinator,canRun).ready; + dispatchWork=normalOwner.registerRunDispatchWork(coordinator,canRun);await dispatchWork.ready; + registerNativeCancellationDelivery(db,coordinator);registerNativeRuntimeResponseDelivery(db,coordinator); + const release=registerNativeCleanupReleaseWake(db,error=>{errors.push(error);});appServer.once("close",release); + await normalOwner.registerDeferredReceiptWork(coordinator,canRun).ready; + await normalOwner.registerScheduledRetryCancellationWork(coordinator,canRun).ready; + await normalOwner.registerCapturedInstructionCommitWork(coordinator,canRun).ready; + await normalOwner.registerInstructionDirectoryCleanupWork(coordinator,canRun).ready; + await normalOwner.registerNativeWorkspaceFinalizationWork(coordinator,canRun).ready; + await normalOwner.registerRetainedNativeSessionCleanupWork(coordinator,canRun).ready; + await normalOwner.registerExternalConversationSettlementWork(coordinator,canRun).ready; + await normalOwner.registerNativeRecoveryNoticeWork(coordinator,canRun).ready; + await normalOwner.registerNativeEnvironmentSettlementWork(coordinator,canRun).ready; + await normalOwner.registerNativeRunProjectionWork(coordinator,canRun).ready; + await normalOwner.registerNativeResultCommitWork(coordinator,canRun).ready; + await normalOwner.registerNativeStatusReassessmentWork(coordinator,canRun).ready; + await normalOwner.registerNativeReviewResponseWork(coordinator,canRun).ready; + await normalOwner.registerNativeResponsePresentationWork(coordinator,canRun).ready; + await normalOwner.registerNativePendingEffectWork(coordinator,canRun).ready; + await normalOwner.registerUnsafeWorkspaceExportWork(coordinator,canRun).ready; + await normalOwner.registerAutomaticCompletionReviewWork(coordinator,canRun).ready; + await normalOwner.registerObsoletePolicyReviewWork(coordinator,canRun).ready; + await normalOwner.registerCancelledWorkspacePreservationWork(coordinator,canRun).ready; + await normalOwner.registerStoppedInstructionCollectionWork(coordinator,canRun).ready; + const enforcement=registerBudgetEnforcementWork(db,coordinator,{cancelWorkForScope:normalOwner.cancelBudgetScopeWork, + deliverResumeContinuations:()=>deliverBudgetResumeContinuations(db,{...budgetResumeDelivery,resumeTaskRetry:(company,request)=>normalOwner.resumeTaskRetry(company,request)})}); + const accounting=registerCostAccountingWork(db,coordinator,normalOwner.reconcileCostAccounting); + stopBudgetOwners=async()=>{try{await enforcement.stop();}finally{await accounting.stop();}}; + await enforcement.ready;await accounting.ready; + + return {origin,db,heartbeat:owner,workerManager:linuxBootstrap.workerManager,stop, + snapshot:()=>({pid:process.pid,worker:idleWorkSnapshot(),taskDrain:owner!.getTaskDrainStatus(),nativeSockets:nativeSockets.size, + unexpectedDecisionWakes,errorCount:errors.length,sessionCalls,healthStatuses:[...healthStatuses],healthOverflow, + runtimeIdentity:{stackId:getCloudRuntimeIdentity()?.stackId,canonicalOrigin:getCloudRuntimeIdentity()?.canonicalOrigin}})}; + }catch(primary){try{await stop();}catch(cleanup){throw new AggregateError([primary,cleanup],"normal_dot_child_start_cleanup_failed");}throw primary;} +} diff --git a/server/src/__tests__/helpers/owned-linux/normal-distribution-bootstrap.ts b/server/src/__tests__/helpers/owned-linux/normal-distribution-bootstrap.ts new file mode 100644 index 00000000000..4ffb2ec8c6b --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/normal-distribution-bootstrap.ts @@ -0,0 +1,49 @@ +// PRIVATE UNRUN fixture composition through EXISTING image-owned bootstrap. +import path from "node:path"; +import { mkdir, readFile, realpath, writeFile } from "node:fs/promises"; +import { distributionBundleDigest, readDistributionPluginCatalog } from "../../../services/distribution-plugin-catalog.js"; +import { BUNDLED_PLUGIN_CATALOG } from "../../../services/bundled-plugins.js"; +import { createPluginWorkerManager } from "../../../services/plugin-worker-manager.js"; +import { LINUX_QUALIFICATION_PROVIDER } from "./normal-runtime-composition.js"; + +const pluginKey = "paperclip.dot-linux-qualification"; +export async function prepareOwnedLinuxDistribution(input: { + catalogRoot: string; + prebuiltPackageRoot: string; + expectedBundleDigest: string; +}) { + // The prebuilt package is a separate OWN normal compiler output. Never copy + // donor workspace compiled exports or install runtime dependencies here. + const expected = path.join(input.catalogRoot, "distribution", LINUX_QUALIFICATION_PROVIDER); + if (input.prebuiltPackageRoot !== expected || await realpath(expected) !== expected) throw new Error("owned_distribution_path_mismatch"); + const pkg = JSON.parse(await readFile(path.join(expected, "package.json"), "utf8")); + if (pkg.version !== "0.0.1" || pkg.paperclipPlugin?.worker !== "./dist/worker.mjs" + || pkg.paperclipPlugin?.manifest !== "./dist/qualification-manifest.js") throw new Error("owned_distribution_package_mismatch"); + const digest = distributionBundleDigest(expected); + if (digest !== input.expectedBundleDigest) throw new Error("owned_distribution_output_drift"); + await mkdir(path.join(input.catalogRoot, "distribution"), { recursive: true, mode: 0o700 }); + const catalogBytes = JSON.stringify({ schemaVersion: 1, plugins: [{ + key: LINUX_QUALIFICATION_PROVIDER, pluginKey, version: "0.0.1", directory: LINUX_QUALIFICATION_PROVIDER, digest, + }] }); + const catalogFile = path.join(input.catalogRoot, "distribution/catalog.json"); + try { await writeFile(catalogFile, catalogBytes, { flag: "wx", mode: 0o600 }); } + catch (error) { + if (!(error instanceof Error && "code" in error && error.code === "EEXIST") || await readFile(catalogFile, "utf8") !== catalogBytes) throw error; + } + const entries = readDistributionPluginCatalog(input.catalogRoot, BUNDLED_PLUGIN_CATALOG); + if (entries.length !== 1 || entries[0]?.pluginKey !== pluginKey) throw new Error("owned_distribution_normal_validation_failed"); + const workerManager = createPluginWorkerManager(); + return { + workerManager, + appOptions: { pluginWorkerManager: workerManager, bundledPluginCatalogRoot: input.catalogRoot, + managedPluginAutoInstall: [LINUX_QUALIFICATION_PROVIDER] }, + }; +} + +// In makeAppOwner, spread these appOptions into the original createApp options; +// await the SAME normal app.locals.bundledPluginsStartup before environment +// setup. Normal ensureBundledPlugins/lifecycle.load creates/starts the worker; +// no ready row, supportedMethods object, loaded module or grants are faked. +// heartbeatService(db,{pluginWorkerManager:workerManager}) uses the same normal +// sandbox runtime/lease owner. Reconstruct through the same bootstrap (catalog +// bytes unchanged), not an untracked alternate environment owner. diff --git a/server/src/__tests__/helpers/owned-linux/normal-runtime-composition.ts b/server/src/__tests__/helpers/owned-linux/normal-runtime-composition.ts new file mode 100644 index 00000000000..950b662a225 --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/normal-runtime-composition.ts @@ -0,0 +1,31 @@ +// PRIVATE, UNRUN. Intended normal imports when placed beside the fixture. +import type { Db } from "@paperclipai/db"; +import type { PluginWorkerManager } from "../../../services/plugin-worker-manager.js"; +import { environmentRuntimeService, type EnvironmentRuntimeDriver } from "../../../services/environment-runtime.js"; + +export const LINUX_QUALIFICATION_PROVIDER = "dot-linux-qualification"; + +export function composeLinuxManagedRuntime(db: Db, workerManager: PluginWorkerManager) { + // Preserve the real sandbox driver's configuration validation, acquire/lease + // persistence, classifier, target resolution and release/reconciliation. The + // provider worker implements real Linux I/O; no managed/ready/target fake. + const runtime = environmentRuntimeService(db, { pluginWorkerManager: workerManager }); + const driver: EnvironmentRuntimeDriver | null = runtime.getDriver("sandbox"); + if (!driver) throw new Error("normal_sandbox_driver_missing"); + return { runtime, driver, workerManager }; +} + +// Required fixture wiring (not an alternative production bootstrap): +// 1 Install the owned worker with the normal plugin loader/registration owner. +// Its sandbox_provider driverKey is LINUX_QUALIFICATION_PROVIDER. Start the +// REAL worker; ready/verified methods must come from its actual handshake. +// 2 POST /api/companies/:companyId/environments with original board authority, +// driver=sandbox, config.provider=LINUX_QUALIFICATION_PROVIDER. No direct DB +// environment/default-agent writes, internal fake config or Daytona label. +// 3 PATCH /api/agents/:id defaultEnvironmentId through the normal authorized +// route. Keep its current company, driver, consent and setup validation. +// 4 The externally composed heartbeat uses runtime from this function. createApp +// receives the SAME workerManager; its normal runtime uses that owner too. +// 5 Stop/join heartbeat + app consumers before worker/provider shutdown. Provider +// release returns stopped only after real custody/ingress proof, then normal +// environmentService persists the release receipt. Unknown => retain. diff --git a/server/src/__tests__/helpers/owned-linux/owned-bulk-sync.ts b/server/src/__tests__/helpers/owned-linux/owned-bulk-sync.ts new file mode 100644 index 00000000000..924ea5cb30c --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/owned-bulk-sync.ts @@ -0,0 +1,88 @@ +// PRIVATE UNRUN fixture transfer over an exact owned bind mount, not Docker cp +// or base64-over-exec. The normal SDK mapping/ordered-command contract remains. +import path from "node:path"; +import { randomUUID } from "node:crypto"; +import { createReadStream, createWriteStream, constants } from "node:fs"; +import { chmod, lstat, mkdir, readdir, realpath, rename, unlink } from "node:fs/promises"; +import { pipeline } from "node:stream/promises"; +import type { PluginEnvironmentSyncResult, PluginSyncOperation } from "@paperclipai/plugin-sdk"; + +interface TransferScope { + remoteRoot: string; + hostLeaseRoot: string; + readableHostRoots: readonly string[]; + readableHostFiles: ReadonlySet; + writableHostRoot: string; + assertCurrentLease(): Promise; + execute(command: { command: string; cwd: string; timeoutMs?: number }): Promise<{ exitCode: number | null; timedOut: boolean }>; +} +const inside = (root: string, value: string) => value === root || value.startsWith(root + path.sep); +const deny = () => new Error("owned_sync_scope_denied"); +async function noSymlinkParents(root: string, destination: string) { + if (!inside(root, destination) || await realpath(root) !== root) throw deny(); + if (destination === root) return; + let current = root; + for (const component of path.relative(root, path.dirname(destination)).split(path.sep).filter(Boolean)) { + current = path.join(current, component); + await mkdir(current, { mode: 0o700 }).catch(async error => { if (error.code !== "EEXIST") throw error; }); + const stat = await lstat(current); if (!stat.isDirectory() || stat.isSymbolicLink()) throw deny(); + } + try { const stat = await lstat(destination); if (stat.isSymbolicLink()) throw deny(); } + catch (error) { if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error; } +} +export async function transferOwnedMappings(scope: TransferScope, operations: readonly PluginSyncOperation[], direction: "in" | "out"): Promise { + await scope.assertCurrentLease(); + if (await realpath(scope.hostLeaseRoot) !== scope.hostLeaseRoot || await realpath(scope.writableHostRoot) !== scope.writableHostRoot) throw deny(); + const mapped = (value: string) => { + if (!path.posix.isAbsolute(value) || path.posix.normalize(value) !== value || !inside(scope.remoteRoot, value)) throw deny(); + return path.join(scope.hostLeaseRoot, path.posix.relative(scope.remoteRoot, value)); + }; + const result: PluginEnvironmentSyncResult = { operations: [] }; + for (const operation of operations) { + let filesTransferred = 0, bytesTransferred = 0, visited = 0; + const copy = async (source: string, destination: string, destinationRoot: string, mode?: number): Promise => { + if (++visited > 10000) throw new Error("owned_sync_inventory_overflow"); + const stat = await lstat(source); if (stat.isSymbolicLink()) throw deny(); + await noSymlinkParents(destinationRoot, destination); + if (stat.isDirectory()) { + await mkdir(destination, { mode: 0o700 }).catch(error => { if (error.code !== "EEXIST") throw error; }); + const target = await lstat(destination); if (!target.isDirectory() || target.isSymbolicLink()) throw deny(); + for (const child of await readdir(source)) await copy(path.join(source, child), path.join(destination, child), destinationRoot); + if (mode !== undefined) await chmod(destination, mode); + return; + } + if (!stat.isFile()) throw deny(); + // Bounded accounting protects the fixture, not a product quota assertion. + if (bytesTransferred + stat.size > 512 * 1024 * 1024) throw new Error("owned_sync_byte_overflow"); + const temporary = path.join(path.dirname(destination), ".sync-" + randomUUID()); + try { + await pipeline(createReadStream(source, { flags: constants.O_RDONLY | constants.O_NOFOLLOW }), + createWriteStream(temporary, { flags: "wx", mode: mode ?? (stat.mode & 0o777) })); + await rename(temporary, destination); + } catch (error) { await unlink(temporary).catch(() => {}); throw error; } + filesTransferred++; bytesTransferred += stat.size; + }; + for (const mapping of operation.files) { + if (mapping.mode !== undefined && (!Number.isInteger(mapping.mode) || mapping.mode < 0 || mapping.mode > 0o777)) throw deny(); + const source = direction === "in" ? mapping.sourcePath : mapped(mapping.sourcePath); + const destination = direction === "in" ? mapped(mapping.targetPath) : mapping.targetPath; + const sourceReal = await realpath(source); + if (sourceReal !== source) throw deny(); + if (direction === "in" && !scope.readableHostFiles.has(source) + && !scope.readableHostRoots.some(root => inside(root, source))) throw deny(); + if (direction === "out" && !inside(scope.writableHostRoot, destination)) throw deny(); + const stat = await lstat(source); + if (mapping.kind === "file" ? !stat.isFile() : !stat.isDirectory()) throw deny(); + await copy(source, destination, direction === "in" ? scope.hostLeaseRoot : scope.writableHostRoot, mapping.mode); + } + for (const command of operation.postUploadCommands ?? []) { + if (direction !== "in") throw new Error("owned_sync_out_commands_denied"); + const cwd = command.cwd ?? scope.remoteRoot; mapped(cwd); // revalidate actual target confinement + await scope.assertCurrentLease(); + const exit = await scope.execute({ ...command, cwd }); + if (exit.exitCode !== 0 || exit.timedOut) throw new Error("owned_sync_post_upload_failed"); + } + result.operations.push({ operationId: operation.operationId, filesTransferred, bytesTransferred }); + } + await scope.assertCurrentLease(); return result; +} diff --git a/server/src/__tests__/helpers/owned-linux/owned-docker-resource.mjs b/server/src/__tests__/helpers/owned-linux/owned-docker-resource.mjs new file mode 100644 index 00000000000..4e4a3c34584 --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/owned-docker-resource.mjs @@ -0,0 +1,165 @@ +// PRIVATE UNRUN concrete local resource owner. No daemon setup/pull/config +// changes. Requires an already-qualified image, Node and Linux Runner artifact. +import path from "node:path"; +import { createHash, randomUUID } from "node:crypto"; +import { spawn } from "node:child_process"; +import { mkdir, readFile, writeFile, rename, realpath, readdir } from "node:fs/promises"; + +const digest = value => createHash("sha256").update(value).digest("hex"); +const closed = code => Object.assign(new Error(code), { code }); +export class OwnedDockerResources { + constructor(config) { + this.config = config; this.pending = new Set(); this.commands = []; this.resources = new Map(); this.unknown = []; + } + async initialize() { + const engine = await this.cli(["info", "--format", "{{.ID}} {{.OSType}} {{.Architecture}}"]); + if (engine.code !== 0 || engine.stdout.trim() !== `${this.config.engineId} linux aarch64`) throw closed("owned_engine_identity_drift"); + await mkdir(this.config.root, { recursive: true, mode: 0o700 }); + if (await realpath(this.config.root) !== this.config.root) throw closed("owned_resource_root_denied"); + const names = (await readdir(this.config.root)).filter(name => /^dot-linux-[a-f0-9]{24}$/.test(name)); + if (names.length > 32) throw closed("owned_resource_inventory_overflow"); + // One bounded owned-directory reconstruction, no periodic scan or Docker + // global inventory. Lost replies retain actual allocation identity. + for (const name of names) { + const resource = JSON.parse(await readFile(path.join(this.config.root, name, "resource.json"), "utf8")); + if (resource.id !== name || resource.hostRoot !== path.join(this.config.root, name)) throw closed("owned_reconstruction_scope_denied"); + const actual = await this.inspect(resource); + if (resource.status === "stopped" && (actual.State.Running || actual.State.Pid !== 0)) throw closed("owned_retirement_reconstruction_mismatch"); + if (resource.status === "resume_intent" && actual.State.Running && actual.State.Pid > 0) { + resource.status = "active"; await this.save(resource); + } + if (resource.status !== "active" && resource.status !== "stopped") { this.unknown.push({ resourceId: name, kind: "allocation_outcome_unknown" }); continue; } + this.resources.set(name, resource); + } + } + async cli(args, input, timeoutMs = 15000) { + const child = spawn(this.config.docker, ["--host", this.config.endpoint, ...args], { + env: { HOME: this.config.home, DOCKER_CONFIG: this.config.dockerConfig, PATH: "/usr/bin:/bin", LANG: "C.UTF-8" }, + stdio: ["pipe", "pipe", "pipe"], detached: true, + }); + const record = { pid: child.pid ?? null, group: child.pid ?? null, joined: false, timedOut: false, overflow: false }; + this.commands.push(record); this.pending.add(record); + const stdout = [], stderr = []; let bytes = 0; + const collect = output => chunk => { bytes += chunk.length; if (bytes > 4 * 1024 * 1024) { record.overflow = true; return; } output.push(chunk); }; + child.stdout.on("data", collect(stdout)); child.stderr.on("data", collect(stderr)); + let spawnFailed = false; child.once("error", () => { spawnFailed = true; }); + const joined = new Promise(resolve => child.once("close", (code, signal) => { Object.assign(record, { joined: true, code, signal }); this.pending.delete(record); resolve(); })); + child.stdin.on("error", () => {}); child.stdin.end(input); + const timer = setTimeout(() => { record.timedOut = true; child.kill("SIGTERM"); }, timeoutMs); + await joined; clearTimeout(timer); + if (spawnFailed || record.timedOut || record.overflow) { this.unknown.push(record); throw closed("owned_docker_transport_unknown"); } + // Raw output stays in memory/normal protocol; never log argv/input/error body. + return { code: record.code, stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8") }; + } + async inspect(resource) { + const response = await this.cli(["inspect", "--format", '{{json .}}', resource.containerId ?? resource.containerName]); + if (response.code !== 0) throw closed("owned_container_inspection_unknown"); + const value = JSON.parse(response.stdout), labels = value.Config?.Labels ?? {}; + if (value.Name !== "/" + resource.containerName || value.Image !== this.config.imageId + || labels["paperclip.qualification"] !== this.config.namespace || labels["paperclip.resource"] !== resource.id + || labels["paperclip.company"] !== resource.companyId || labels["paperclip.environment"] !== resource.environmentId + || labels["paperclip.run"] !== resource.runId || labels["paperclip.creation"] !== resource.creationOperationId + || value.HostConfig?.Privileged || value.HostConfig?.NetworkMode !== "none" + || value.HostConfig?.NanoCpus !== 2000000000 || value.HostConfig?.Memory !== 4294967296 + || value.HostConfig?.PidsLimit !== 256 || !value.HostConfig?.Init) throw closed("owned_container_identity_mismatch"); + if (resource.containerId && value.Id !== resource.containerId) throw closed("owned_container_replaced"); + return value; + } + async save(resource) { + const target = path.join(resource.hostRoot, "resource.json"), temporary = target + "." + randomUUID(); + await writeFile(temporary, JSON.stringify(resource), { flag: "wx", mode: 0o600 }); await rename(temporary, target); + } + async acquire(params) { + if (!/^sha256:[a-f0-9]{64}$/.test(this.config.imageId) || !/^[a-f0-9]{64}$/.test(this.config.runnerSHA256) + || digest(await readFile(this.config.nodeBinary)) !== this.config.nodeSHA256 + || await realpath(this.config.root) !== this.config.root || await realpath(this.config.relayRoot) !== this.config.relayRoot) throw closed("owned_runtime_prerequisite_unqualified"); + if (params.driverKey !== "dot-linux-qualification" || params.config.qualificationId !== "dot-owned-linux" + || !params.creationOperationId || !params.runId || params.purpose === "login" || params.requestedExpiresAt) throw closed("owned_allocation_scope_denied"); + // One normal creation operation => one name/resource, even after a lost + // acquire reply. Never mint a second allocation on an unknown outcome. + const id = "dot-linux-" + digest(JSON.stringify([params.companyId, params.environmentId, params.runId, params.creationOperationId])).slice(0, 24); + const hostRoot = path.join(this.config.root, id); await mkdir(hostRoot, { recursive: true, mode: 0o700 }); + if (await realpath(hostRoot) !== hostRoot) throw closed("owned_resource_path_denied"); + let resource; + try { resource = JSON.parse(await readFile(path.join(hostRoot, "resource.json"), "utf8")); } + catch (error) { if (error.code !== "ENOENT") throw error; } + if (resource) { + if (resource.companyId !== params.companyId || resource.environmentId !== params.environmentId || resource.runId !== params.runId + || resource.creationOperationId !== params.creationOperationId) throw closed("owned_creation_custody_mismatch"); + const actual = await this.inspect(resource); + if (!actual.State.Running || resource.status !== "active") throw closed("owned_creation_not_resumable"); + this.resources.set(id, resource); return resource; + } + resource = { id, hostRoot, root: "/workspace", companyId: params.companyId, environmentId: params.environmentId, + runId: params.runId, creationOperationId: params.creationOperationId, nonce: randomUUID(), containerName: id, + containerId: null, status: "dispatch_recorded", expectedRunnerSHA256: this.config.runnerSHA256, + launchDescriptor: "/workspace/.qualification-custody/active-launch.json" }; + await this.save(resource); // durable before creating anything + for (const name of ["workspace", "descriptor"]) await mkdir(path.join(hostRoot, name), { mode: 0o700 }); + const args = ["create", "--name", id, "--init", "--read-only", "--network", "none", "--cpus", "2", "--memory", "4g", "--memory-swap", "4g", "--pids-limit", "256", + "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--user", `${this.config.uid}:${this.config.gid}`, "--tmpfs", "/tmp:rw,nosuid,nodev,size=268435456"]; + for (const [key, value] of Object.entries({ qualification: this.config.namespace, resource: id, company: params.companyId, + environment: params.environmentId, run: params.runId, creation: params.creationOperationId })) args.push("--label", `paperclip.${key}=${value}`); + for (const [source, destination, readonly] of [[path.join(hostRoot, "workspace"), "/workspace", false], + [path.join(hostRoot, "descriptor"), "/descriptor", true], [this.config.relayRoot, "/qualification", true], [this.config.nodeBinary, "/usr/bin/node", true]]) { + args.push("--mount", `type=bind,src=${source},dst=${destination}${readonly ? ",readonly" : ""}`); + } + args.push(this.config.imageId, "sleep", "infinity"); + const created = await this.cli(args); + if (created.code !== 0 || !/^[a-f0-9]{64}$/.test(created.stdout.trim())) throw closed("owned_creation_unknown_retained"); + resource.containerId = created.stdout.trim(); await this.save(resource); await this.inspect(resource); + await writeFile(path.join(hostRoot, "descriptor/resource.json"), JSON.stringify(resource), { flag: "wx", mode: 0o600 }); + const started = await this.cli(["start", resource.containerId]); if (started.code !== 0) throw closed("owned_start_unknown_retained"); + const actual = await this.inspect(resource); if (!actual.State.Running) throw closed("owned_start_not_observed"); + resource.status = "active"; await this.save(resource); this.resources.set(id, resource); return resource; + } + async resolve(params, providerLeaseId) { + if (!/^dot-linux-[a-f0-9]{24}$/.test(providerLeaseId)) throw closed("owned_lease_identity_invalid"); + const resource = this.resources.get(providerLeaseId); + // Reconstruct from durable allocation, not a synthetic in-memory success. + const found = resource ?? JSON.parse(await readFile(path.join(this.config.root, providerLeaseId, "resource.json"), "utf8")); + if (!/^dot-linux-[a-f0-9]{24}$/.test(providerLeaseId) || found.id !== providerLeaseId + || found.companyId !== params.companyId || found.environmentId !== params.environmentId) throw closed("owned_lease_authority_denied"); + await this.inspect(found); this.resources.set(found.id, found); return found; + } + async resume(params) { + const resource = await this.resolve(params, params.providerLeaseId); + if (params.runId && params.runId !== resource.runId) throw closed("owned_resume_run_authority_mismatch"); + if (params.requestedCwd && params.requestedCwd !== resource.root) throw closed("owned_resume_workspace_mismatch"); + const actual = await this.inspect(resource); + if (!actual.State.Running) { + if (actual.State.Pid !== 0 || resource.status !== "stopped" || this.pending.size || this.unknown.length) + throw closed("owned_resume_previous_execution_unknown"); + // Retain the previous launch witness before a new launch can own this + // exact workspace. Container stop proved the whole prior PID namespace + // ended. Do not delete a marker/checkpoint or acquire a replacement. + const custody = path.join(resource.hostRoot, "workspace/.qualification-custody"); + const active = path.join(custody, "active-launch.json"); + try { await rename(active, path.join(custody, "retired-launch-" + randomUUID() + ".json")); } + catch (error) { if (error.code !== "ENOENT") throw error; } + resource.status = "resume_intent"; await this.save(resource); + const started = await this.cli(["start", resource.containerId]); + if (started.code !== 0) throw closed("owned_resume_transport_unknown_retained"); + } else if (resource.status !== "active") { + // Lost resume response is reconciled only for the exact durable intent. + if (resource.status !== "resume_intent") throw closed("owned_resume_state_unknown"); + } + const observed = await this.inspect(resource); + if (!observed.State.Running || observed.State.Pid <= 0) throw closed("owned_resume_not_observed_retained"); + resource.status = "active"; await this.save(resource); return resource; + } + async stop(resource) { + // The normal fixture MUST close Runner/ingress first. Exact container stop + // is an execution-termination boundary, not a claim of graceful PID join. + if (this.pending.size || this.unknown.length) throw closed("owned_calls_or_outcomes_unknown_retained"); + const current = await this.inspect(resource); + if (current.State.Running) { + const stopped = await this.cli(["stop", "--time", "15", resource.containerId], undefined, 30000); + if (stopped.code !== 0) throw closed("owned_stop_unknown_retained"); + } + const actual = await this.inspect(resource); + if (actual.State.Running || actual.State.Pid !== 0) throw closed("owned_stop_not_observed_retained"); + resource.status = "stopped"; resource.namespaceTerminationOnly = true; await this.save(resource); + return { providerLeaseId: resource.id, state: "stopped" }; + } +} diff --git a/server/src/__tests__/helpers/owned-linux/owned-provider-implementation.mjs b/server/src/__tests__/helpers/owned-linux/owned-provider-implementation.mjs new file mode 100644 index 00000000000..6fffe35ece6 --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/owned-provider-implementation.mjs @@ -0,0 +1,150 @@ +// PRIVATE UNRUN. Normal SDK hooks backed by actual owned Linux operations. +import path from "node:path"; +import { readFile, writeFile } from "node:fs/promises"; +import { randomBytes, randomUUID } from "node:crypto"; +import { OwnedDockerResources } from "./owned-docker-resource.mjs"; +import { startOwnedWssGateway } from "./owned-wss-gateway.mjs"; +import { transferOwnedMappings } from "./owned-bulk-sync.js"; + +export function createOwnedLinuxProvider(config) { + const resources = new OwnedDockerResources(config), gateways = new Map(), ingressPending = new Set(), active = new Set(), retiring = new Set(), stopPromises = new Map(); + let closing = false; + const track = (params, work, allowRetiring = false) => { + if (!allowRetiring && retiring.has(params.lease?.providerLeaseId ?? params.providerLeaseId)) return Promise.reject(new Error("owned_resource_retiring")); + if (closing) return Promise.reject(new Error("owned_provider_closing")); + const pending = Promise.resolve().then(work); active.add(pending); + return pending.finally(() => active.delete(pending)); + }; + const find = async (params, id = params.lease?.providerLeaseId ?? params.providerLeaseId, allowRetiring = false) => { + const resource = await resources.resolve(params, id); + if (params.driverKey !== "dot-linux-qualification" || params.config.qualificationId !== "dot-owned-linux") throw new Error("owned_provider_scope_denied"); + return resource; + }; + const execute = async params => { + const resource = await find(params); + if (resource.status !== "active") throw new Error("owned_execution_resource_inactive"); + const response = await resources.cli(["exec", "-i", resource.containerId, "/usr/bin/node", "/qualification/linux-command-relay.mjs", "/descriptor/resource.json"], + JSON.stringify({ ...resource, providerLeaseId: resource.id, requestId: randomUUID(), command: params.command, args: params.args ?? [], + cwd: params.cwd ?? resource.root, env: params.env ?? {}, stdin: params.stdin, timeoutMs: params.timeoutMs ?? 90000 }), + Math.min(params.timeoutMs ?? 90000, 90000) + 1000); + let value; + try { value = JSON.parse(response.stdout); } + catch { resources.unknown.push({ resourceId: resource.id, kind: "command_reply_invalid" }); throw new Error("owned_command_reply_invalid"); } + if (response.code !== 0 || value.error || value.unknownOutcome || !value.joined || value.overflow || value.spawnError) { + resources.unknown.push({ resourceId: resource.id, kind: "command_outcome_unknown" }); throw new Error("owned_command_outcome_unknown"); + } + // Fault injection is owned by the fixture AFTER a real durable checkpoint; + // never terminate from the early marker-read/handshake frontier. + return { exitCode: value.exitCode, signal: value.signal, timedOut: value.timedOut, stdout: value.stdout, stderr: value.stderr, + metadata: { ownedLinuxCommandPid: value.pid, ownedLinuxCommandGroup: value.group, processIdentity: value.kernel, + nativeIdentity: value.proof?.kernel ?? null, providerLeaseId: resource.id } }; + }; + const sync = async (params, direction) => { + const resource = await find(params); + return transferOwnedMappings({ remoteRoot: resource.root, hostLeaseRoot: path.join(resource.hostRoot, "workspace"), + readableHostRoots: config.readableHostRoots, readableHostFiles: new Set(config.readableHostFiles), writableHostRoot: config.writableHostRoot, + assertCurrentLease: async () => { const value = await find(params); if (value.status !== "active") throw new Error("owned_sync_resource_inactive"); }, + execute: command => execute({ ...params, command: "sh", args: ["-c", command.command], cwd: command.cwd, timeoutMs: command.timeoutMs }), + }, params.operations, direction); + }; + const stop = async params => { + if (stopPromises.has(params.providerLeaseId)) return stopPromises.get(params.providerLeaseId); + retiring.add(params.providerLeaseId); + const stopping = (async () => { + await Promise.allSettled([...active]); + const resource = await find(params, params.providerLeaseId, true); + const gateway = gateways.get(resource.id); + // Stop the exact verified namespace first. Its real exit closes the relay + // and WSS sockets; joining them before termination would deadlock. + const termination = await resources.stop(resource); + if (gateway) { await gateway.close(); gateways.delete(resource.id); } + // namespace stop is explicitly labeled; it does not replace the paired + // fixture's independent individual PID/group/start/used-socket join proof. + return termination; + })(); + const observed = stopping.catch(error => { stopPromises.delete(params.providerLeaseId); throw error; }); + stopPromises.set(params.providerLeaseId, observed); return observed; + }; + const provider = { + initialize: () => resources.initialize(), + async acquire(params) { + const resource = await resources.acquire(params); + return { providerLeaseId: resource.id, metadata: { remoteCwd: resource.root, shellCommand: "sh", reuseLease: false, + qualificationNamespace: config.namespace, companyId: resource.companyId, environmentId: resource.environmentId, + runId: resource.runId, creationOperationId: resource.creationOperationId } }; + }, + async resume(params) { + if (closing) throw new Error("owned_provider_closing"); + // No acquire, replacement or run-authority transfer. Same-run Native + // recovery gets the exact retained files/container through normal SDK. + const oldStop = stopPromises.get(params.providerLeaseId); if (oldStop) await oldStop; + const existing = gateways.get(params.providerLeaseId); + if (existing) { await existing.close(); gateways.delete(params.providerLeaseId); } + const resource = await resources.resume(params); + retiring.delete(resource.id); stopPromises.delete(resource.id); + return { providerLeaseId: resource.id, metadata: { remoteCwd: resource.root, + qualificationNamespace: config.namespace, runId: resource.runId } }; + }, + async inspect(params) { + const resource = await find(params, params.providerLeaseId), actual = await resources.inspect(resource); + return { providerLeaseId: resource.id, state: actual.State.Running ? "active" : actual.State.Pid === 0 ? "stopped" : "unknown" }; + }, + async realize(params) { + const resource = await find(params); + if (resource.status !== "active") throw new Error("owned_workspace_resource_inactive"); + // Actual bind-mounted owned workspace exists; no synthesized repository, + // outcome, credentials or task authority is installed here. + return { cwd: resource.root, metadata: { providerLeaseId: resource.id, ownedLinuxWorkspace: true } }; + }, + execute, + syncIn: params => sync(params, "in"), + syncOut: params => sync(params, "out"), + async ingress(params) { + const resource = await find(params); + if (params.port !== 43127 || !/^\/api\/runner\/v1\/connect\/[^/?#]+$/.test(params.path)) throw new Error("owned_ingress_target_denied"); + if (gateways.has(resource.id)) { + const existing = gateways.get(resource.id); + if (existing.requestedPath !== params.path) throw new Error("owned_ingress_generation_mismatch"); + return existing.endpoint; + } + const generation = randomUUID(), secret = randomBytes(32).toString("hex"); + const gateway = await startOwnedWssGateway({ docker: config.docker, endpoint: config.endpoint, resource, + ownedHome: config.home, ownedDockerConfig: config.dockerConfig, runnerPort: params.port, path: params.path, + key: await readFile(config.tlsKey), cert: await readFile(config.tlsCert), servername: "127.0.0.1", secret, generation, + relayPath: "/qualification/linux-runner-ingress.mjs", descriptorPath: "/descriptor/resource.json", pending: ingressPending, + verifyOwnedContainer: () => resources.inspect(resource), + readCurrentLease: async () => { + const actual = await resources.inspect(resource); + return { status: actual.State.Running && !retiring.has(resource.id) ? resource.status : "stopped", generation, providerLeaseId: resource.id, + companyId: resource.companyId, environmentId: resource.environmentId, runId: resource.runId, containerId: resource.containerId }; + }, + }); + const endpoint = { kind: "authenticated_websocket", websocketUrl: `wss://127.0.0.1:${gateway.port}${params.path}`, + secretHeaders: [{ name: "x-owned-linux-ingress", value: secret }], generation }; + Object.assign(gateway, { endpoint, requestedPath: params.path }); gateways.set(resource.id, gateway); return endpoint; + }, + stop, + idle() { return active.size === 0 && resources.pending.size === 0 && ingressPending.size === 0 && gateways.size === 0 && resources.unknown.length === 0; }, + async close() { + closing = true; + const errors = []; + try { await Promise.all([...active]); } catch (error) { errors.push(error); } + for (const resource of resources.resources.values()) { + try { await stop({ driverKey: "dot-linux-qualification", config: { qualificationId: "dot-owned-linux" }, + companyId: resource.companyId, environmentId: resource.environmentId, providerLeaseId: resource.id }); } + catch (error) { errors.push(error); } + } + if (resources.pending.size || ingressPending.size || resources.commands.some(record => !record.joined) || resources.unknown.length) errors.push(new Error("owned_linux_shutdown_unknown")); + if (errors.length) throw new AggregateError(errors, "owned_linux_shutdown_failed_retained"); + }, + }; + return { ...provider, + acquire: params => track(params, () => provider.acquire(params)), + inspect: params => track(params, () => provider.inspect(params), true), + realize: params => track(params, () => provider.realize(params)), + execute: params => track(params, () => provider.execute(params)), + ingress: params => track(params, () => provider.ingress(params)), + syncIn: params => track(params, () => provider.syncIn(params)), + syncOut: params => track(params, () => provider.syncOut(params)), + }; +} diff --git a/server/src/__tests__/helpers/owned-linux/owned-wss-gateway.mjs b/server/src/__tests__/helpers/owned-linux/owned-wss-gateway.mjs new file mode 100644 index 00000000000..830988c6d08 --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/owned-wss-gateway.mjs @@ -0,0 +1,90 @@ +// PRIVATE UNRUN fixture infrastructure. TLS stays verified. No public provider. +import https from "node:https"; +import { spawn } from "node:child_process"; +import { timingSafeEqual } from "node:crypto"; +import { once } from "node:events"; + +const sameSecret = (actual, expected) => typeof actual === "string" && Buffer.byteLength(actual) === Buffer.byteLength(expected) + && timingSafeEqual(Buffer.from(actual), Buffer.from(expected)); + +export async function startOwnedWssGateway(options) { + const sockets = new Set(), children = new Set(), unknown = [], records = []; + let closing = false; + const server = https.createServer({ key: options.key, cert: options.cert }, (_req, res) => { res.writeHead(404); res.end(); }); + server.on("connection", socket => { sockets.add(socket); socket.once("close", () => sockets.delete(socket)); }); + server.on("upgrade", (request, socket, head) => { + // Keep this promise in the explicit owner set; never swallow a rejected + // authority/kernel/transport observation as an accepted upgrade. + const work = (async () => { + if (closing || request.method !== "GET" || request.url !== options.path || request.headers.host !== `${options.servername}:${server.address()?.port}` + || !sameSecret(request.headers["x-owned-linux-ingress"], options.secret)) { + socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"); return; + } + // Supplied by actual current lease/namespace owner, not a cached allow. + const current = await options.readCurrentLease(); + if (current.status !== "active" || current.generation !== options.generation + || current.providerLeaseId !== options.resource.id || current.companyId !== options.resource.companyId + || current.runId !== options.resource.runId || current.containerId !== options.resource.containerId || current.environmentId !== options.resource.environmentId) throw new Error("current_ingress_lease_denied"); + await options.verifyOwnedContainer(); // exact ID + image + labels, no reuse + const child = spawn(options.docker, ["--host", options.endpoint, "exec", "-i", options.resource.containerId, + "/usr/bin/node", options.relayPath, options.descriptorPath], { + env: { HOME: options.ownedHome, DOCKER_CONFIG: options.ownedDockerConfig, PATH: "/usr/bin:/bin", LANG: "C.UTF-8" }, + stdio: ["pipe", "pipe", "pipe"], detached: true, + }); + const record = { pid: child.pid ?? null, group: child.pid ?? null, joined: false, status: "pending" }; records.push(record); + children.add(child); + const joined = new Promise(resolve => child.once("close", (code, signal) => { record.joined = true; record.code = code; record.signal = signal; children.delete(child); resolve(); })); + child.once("error", () => { record.status = "spawn_failed"; }); + // Never log stderr: normal ingress/command payloads may include secrets. + let errorBytes = 0; child.stderr.on("data", bytes => { errorBytes += bytes.length; }); + child.stdin.on("error", () => { record.stdinError = true; }); + child.stdin.write(JSON.stringify({ ...options.resource, providerLeaseId: options.resource.id, port: options.runnerPort }) + "\n"); + let prefix = Buffer.alloc(0); + const proof = await new Promise((resolve, reject) => { + const onData = bytes => { + prefix = Buffer.concat([prefix, bytes]); const end = prefix.indexOf(10); + if (end < 0 && prefix.length > 16384) { child.stdout.off("data", onData); reject(new Error("ingress_proof_overflow")); return; } + if (end < 0) return; + child.stdout.pause(); child.stdout.off("data", onData); + try { const value = JSON.parse(prefix.subarray(0, end).toString("utf8")); prefix = prefix.subarray(end + 1); resolve(value); } + catch { reject(new Error("ingress_proof_invalid")); } + }; + child.stdout.on("data", onData); child.once("close", () => reject(new Error("ingress_closed_before_proof"))); + }); + // The actual normal launcher has already used its canonical parser + // before initiating PRP. Linux ingress independently requires real marker, + // boot/ticks/exe+listener custody; no replacement parser/ready authority. + if (proof.ready !== true || proof.providerLeaseId !== options.resource.id + || proof.containerId !== options.resource.containerId || proof.companyId !== options.resource.companyId || proof.environmentId !== options.resource.environmentId || closing) throw new Error("ingress_proof_foreign"); + record.status = "forwarding"; + const lines = [`GET ${options.path} HTTP/1.1`]; + for (let i = 0; i < request.rawHeaders.length; i += 2) { + const name = request.rawHeaders[i], value = request.rawHeaders[i + 1]; + if (name.toLowerCase() !== "x-owned-linux-ingress") lines.push(name + ": " + value); + } + child.stdin.write(lines.join("\r\n") + "\r\n\r\n"); if (head.length) child.stdin.write(head); + if (prefix.length) socket.write(prefix); + socket.pipe(child.stdin); child.stdout.pipe(socket); child.stdout.resume(); + socket.once("end", () => child.stdin.end()); + await joined; record.stderrBytes = errorBytes; + if (!socket.closed) socket.end(); + })(); + options.pending.add(work); + void work.catch(() => { unknown.push("ingress_outcome_unknown"); if (!socket.closed) socket.end(); }) + .finally(() => options.pending.delete(work)); + }); + await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); }); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("owned_wss_listener_unknown"); + return { + port: address.port, records, unknown, + async close() { + closing = true; + // Snapshot ALL tracked close-event witnesses, never filter socket.closed. + const socketJoins = [...sockets].map(socket => once(socket, "close")); + const serverJoin = new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); + await Promise.all([serverJoin, ...socketJoins, ...options.pending]); + if (sockets.size || children.size || unknown.length || records.some(record => !record.joined)) throw new Error("owned_ingress_closure_unknown_retained"); + }, + }; +} diff --git a/server/src/__tests__/helpers/owned-linux/package-template.json b/server/src/__tests__/helpers/owned-linux/package-template.json new file mode 100644 index 00000000000..d46eca037f4 --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/package-template.json @@ -0,0 +1,10 @@ +{ + "name": "paperclip-plugin-dot-owned-linux-qualification", + "version": "0.0.1", + "private": true, + "type": "module", + "paperclipPlugin": { + "manifest": "./dist/qualification-manifest.js", + "worker": "./dist/worker.mjs" + } +} \ No newline at end of file diff --git a/server/src/__tests__/helpers/owned-linux/physical-app-owner.ts b/server/src/__tests__/helpers/owned-linux/physical-app-owner.ts new file mode 100644 index 00000000000..8e5e4f2f6a6 --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/physical-app-owner.ts @@ -0,0 +1,66 @@ +// PRIVATE UNRUN. Reuses the existing process-tree owner; no synthetic PID or +// copied/fake /proc. First App generation MUST use this owner too. +import { fork, type ChildProcess } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { z } from "zod"; +import { createProcessTreeOwner } from "../../../../../tests/runner-e2e/process-tree-owner.js"; +import { readProcessTable } from "../../../../../tests/runner-e2e/process-tree.js"; + +export async function forkNormalDotApp(input: { + entry: URL; + nodeExecutable: string; + normalTsxImport: URL; + cwd: string; + closedEnv: Readonly>; + setupDeadline: number; + registerActualChild: (child: ChildProcess, owner: ReturnType) => void; + privateLog: (channel: "stdout" | "stderr", bytes: Buffer) => void; +}) { + // Standard installed tsx is the same normal Source runtime already used by + // existing maintenance/server-harness. No custom loader or ambient env. + const child = fork(fileURLToPath(input.entry), [], { cwd: input.cwd, execPath: input.nodeExecutable, + execArgv: ["--experimental-test-module-mocks", "--import", fileURLToPath(input.normalTsxImport)], env: { ...input.closedEnv }, detached: true, + stdio: ["ignore", "pipe", "pipe", "ipc"] }); + child.stdout?.on("data", bytes => input.privateLog("stdout", bytes)); + child.stderr?.on("data", bytes => input.privateLog("stderr", bytes)); + const owner = createProcessTreeOwner(child); + input.registerActualChild(child, owner); // BEFORE awaiting readiness; startup failures retain custody. + const closed = new Promise(resolve => child.once("close", () => resolve())); + const readySchema = z.object({ kind: z.literal("ready"), pid: z.number().int().positive(), port: z.number().int().min(1).max(65535), bootId: z.uuid() }).strict(); + const ready = new Promise>((resolve, reject) => { + child.once("error", reject); + child.once("exit", () => reject(new Error("dot_app_exited_before_ready"))); + child.on("message", value => { const parsed = readySchema.safeParse(value); if (parsed.success) resolve(parsed.data); }); + }); + const bounded = async (promise: Promise, deadline: number, label: string) => { + const remaining = deadline - performance.now(); if (remaining <= 0) throw new Error(label); + let timer: ReturnType | undefined; + try { return await Promise.race([promise, new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error(label)), remaining); })]); } + finally { clearTimeout(timer); } + }; + const first = await bounded(ready, input.setupDeadline, "dot_app_original_setup_budget_exhausted"); + if (!child.pid || first.pid !== child.pid || child.pid === process.pid) throw new Error("physical_app_pid_mismatch"); + await owner.observe(); const table = await readProcessTable(); + const kernel = table?.find(row => row.pid === child.pid); + if (!kernel || kernel.parentPid !== process.pid || kernel.processGroupId !== child.pid || !Number.isFinite(Date.parse(kernel.started))) throw new Error("physical_app_start_identity_missing"); + let stopping: Promise | undefined; + return { child, pid: child.pid, started: kernel.started, bootId: first.bootId, origin: `http://127.0.0.1:${first.port}`, + async observe() { await owner.observe(); }, + stop(originalJoinDeadline: number) { + return stopping ??= (async () => { + // Existing normal bootstrap shutdown must join Native/plugin/delivery/ + // budget/App/DB/socket owners before the entry exits. NO signal fallback. + if (child.exitCode === null && child.signalCode === null) { + if (!child.connected) throw new Error("owned_app_ipc_shutdown_unavailable_retained"); + child.send({ command: "shutdown" }); + } + await bounded(closed, originalJoinDeadline, "owned_app_original15s_join_exhausted_retained"); + if (child.exitCode !== 0 || child.signalCode !== null) throw new Error("owned_app_unclean_exit_retained"); + await owner.observe(); + if (owner.liveGroups().length) throw new Error("owned_app_descendants_remain_retained"); + const after = await readProcessTable(); + if (!after || after.some(row => row.pid === child.pid)) throw new Error("owned_app_old_pid_not_absent"); + })(); + }, + }; +} diff --git a/server/src/__tests__/helpers/owned-linux/private-ca-scope.ts b/server/src/__tests__/helpers/owned-linux/private-ca-scope.ts new file mode 100644 index 00000000000..5b0017766f4 --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/private-ca-scope.ts @@ -0,0 +1,36 @@ +// PRIVATE fixture-only isolated Node24.22.2 worker scope. No TLS bypass. +import { X509Certificate, createHash } from "node:crypto"; +import { getCACertificates, setDefaultCACertificates } from "node:tls"; + +export function beginOwnedPrivateCA(input: { pem: string; SHA256: string }): () => void { + const certificate = new X509Certificate(input.pem); + if (!certificate.ca || createHash("sha256").update(input.pem).digest("hex") !== input.SHA256) throw new Error("owned_ca_identity_mismatch"); + const previous = getCACertificates("default"); + setDefaultCACertificates([...previous, input.pem]); + let restored = false; + return () => { if (!restored) { setDefaultCACertificates(previous); restored = true; } }; +} + +export async function withOwnedPrivateCA(input: { + pem: string; + SHA256: string; + run(): Promise; + closeOwnedResources(): Promise; +}): Promise { + const restore = beginOwnedPrivateCA(input); + let outcome: { ok: true; value: T } | { ok: false; error: unknown }; + try { outcome = { ok: true, value: await input.run() }; } + catch (error) { outcome = { ok: false, error }; } + const errors: unknown[] = outcome.ok ? [] : [outcome.error]; + try { await input.closeOwnedResources(); } + catch (error) { errors.push(error); } + finally { + // Restore even when the real resource join fails; retain BOTH failures. + try { restore(); } + catch (error) { errors.push(error); } + } + if (errors.length === 1) throw errors[0]; + if (errors.length > 1) throw new AggregateError(errors, "owned_ca_scope_or_cleanup_failed"); + if (!outcome.ok) throw outcome.error; + return outcome.value; +} diff --git a/server/src/__tests__/helpers/owned-linux/qualification-manifest.ts b/server/src/__tests__/helpers/owned-linux/qualification-manifest.ts new file mode 100644 index 00000000000..d5961338b20 --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/qualification-manifest.ts @@ -0,0 +1,32 @@ +// PRIVATE fixture package, never a deployed provider claim. +import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk"; +export default { + id: "paperclip.dot-linux-qualification", + apiVersion: 1, + version: "0.0.1", + displayName: "Owned Linux qualification", + description: "Controlled local Linux process boundary for Dot acceptance, not a public sandbox service.", + author: "Paperclip", + categories: ["automation"], + capabilities: ["environment.drivers.register"], + entrypoints: { worker: "./dist/worker.mjs" }, + environmentDrivers: [{ + driverKey: "dot-linux-qualification", + kind: "sandbox_provider", + displayName: "Owned Linux qualification", + description: "Runs the actual source-matched Linux Runner in a strictly owned local container.", + supportsReusableLeases: false, + creationOperationVersion: 1, + sandboxCapabilities: { + runnerWebSocketIngress: true, + incrementalSessionOutput: false, + concurrentSyncOperations: false, + duplexCommandStream: false, + }, + configSchema: { + type: "object", additionalProperties: false, + properties: { qualificationId: { type: "string", enum: ["dot-owned-linux"] } }, + required: ["qualificationId"], + }, + }], +} satisfies PaperclipPluginManifestV1; diff --git a/server/src/__tests__/helpers/owned-linux/qualification-provider.ts b/server/src/__tests__/helpers/owned-linux/qualification-provider.ts new file mode 100644 index 00000000000..820f14ea011 --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/qualification-provider.ts @@ -0,0 +1,62 @@ +// PRIVATE UNRUN provider composition. Uses actual SDK worker registration; +// never insert ready plugin/environment/lease rows from the fixture. +import { definePlugin, runWorker } from "@paperclipai/plugin-sdk"; +import type { + PluginEnvironmentAcquireLeaseParams, PluginEnvironmentExecuteParams, + PluginEnvironmentExecuteResult, PluginEnvironmentInspectLeaseParams, + PluginEnvironmentLease, PluginEnvironmentLeaseObservation, + PluginEnvironmentRealizeWorkspaceParams, PluginEnvironmentRealizeWorkspaceResult, + PluginEnvironmentReleaseLeaseParams, PluginEnvironmentRunnerIngressEndpoint, + PluginEnvironmentRunnerIngressEndpointParams, PluginEnvironmentSyncInParams, + PluginEnvironmentSyncOutParams, PluginEnvironmentSyncResult, + PluginEnvironmentTerminationReceipt, PluginEnvironmentResumeLeaseParams, +} from "@paperclipai/plugin-sdk"; + +// Concrete implementation boundary for the owned local Linux resource. No +// method may return cached ready/result/termination data. The implementation +// must inspect exact engine/container labels and use actual relay/file custody. +export interface OwnedLinuxProvider { + initialize(): Promise; + acquire(input: PluginEnvironmentAcquireLeaseParams): Promise; + resume(input: PluginEnvironmentResumeLeaseParams): Promise; + inspect(input: PluginEnvironmentInspectLeaseParams): Promise; + realize(input: PluginEnvironmentRealizeWorkspaceParams): Promise; + execute(input: PluginEnvironmentExecuteParams): Promise; + ingress(input: PluginEnvironmentRunnerIngressEndpointParams): Promise; + syncIn(input: PluginEnvironmentSyncInParams): Promise; + syncOut(input: PluginEnvironmentSyncOutParams): Promise; + stop(input: PluginEnvironmentReleaseLeaseParams): Promise; + idle(): boolean; + close(): Promise; +} + +export function linuxQualificationPlugin(provider: OwnedLinuxProvider) { + return definePlugin({ + async setup() { await provider.initialize(); }, + async onEnvironmentValidateConfig(params) { + const ok = params.driverKey === "dot-linux-qualification" && params.config.qualificationId === "dot-owned-linux"; + return ok ? { ok: true, normalizedConfig: { qualificationId: "dot-owned-linux" } } + : { ok: false, errors: ["owned_linux_configuration_mismatch"] }; + }, + onEnvironmentAcquireLease: input => provider.acquire(input), + onEnvironmentResumeLease: input => provider.resume(input), + onEnvironmentInspectLease: input => provider.inspect(input), + onEnvironmentRealizeWorkspace: input => provider.realize(input), + onEnvironmentExecute: input => provider.execute(input), + onEnvironmentRunnerIngressEndpoint: input => provider.ingress(input), + onEnvironmentSyncIn: input => provider.syncIn(input), + onEnvironmentSyncOut: input => provider.syncOut(input), + onEnvironmentStopLease: input => provider.stop(input), + onEnvironmentReleaseLease: input => provider.stop(input), + // Retains files: report only the actual observed stopped state, never destroyed. + onEnvironmentDestroyLease: input => provider.stop(input), + async onIdleDrain() { return provider.idle() ? "none" : "present"; }, + async onShutdown() { await provider.close(); }, + }); +} + +export function startLinuxQualificationWorker(provider: OwnedLinuxProvider, url: string) { + // Normal runWorker advertises the actual methods. This is not a fake manager + // or a hand-built supportedMethods/ready-row substitute. + runWorker(linuxQualificationPlugin(provider), url); +} diff --git a/server/src/__tests__/helpers/owned-linux/useful-after-physical-restart.ts b/server/src/__tests__/helpers/owned-linux/useful-after-physical-restart.ts new file mode 100644 index 00000000000..bc99d346647 --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/useful-after-physical-restart.ts @@ -0,0 +1,113 @@ +// PRIVATE UNRUN finite follow-on using the existing actual HTTP/Db owners. +// Caller starts generation1 through normal-app-child from the BEGINNING. +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import { setTimeout as pause } from "node:timers/promises"; +import { z } from "zod"; +import { eq } from "drizzle-orm"; +import { dotRunnerAssignments, dotRunnerOperations, nativeRunResults, heartbeatRuns, completionContracts, issues, type Db } from "@paperclipai/db"; +import { documentService } from "../../../services/documents.js"; +import { externalOperationDigest } from "../../../vendor/paperclip-runner/index.js"; +import { createCommittedReplyLoss } from "./committed-reply-loss.js"; +import type { forkNormalDotApp } from "./physical-app-owner.js"; + +type Child=Awaited>; +type Wire={status:number;body:{result?:{isError?:boolean;structuredContent?:{result?:unknown}}}}; +export async function usefulAfterPhysicalRestart(input:{ + db:Db; companyId:string; agentId:string; first:Child; + startSecond:()=>Promise; + // Original authorized normal board HTTP surface; no issue/outcome row writes. + createTask:(body:{title:string;description:string;workMode:"standard";status:"todo";assigneeAgentId:string})=>Promise<{status:number;body:{id:string}}>; + // Same unrevoked wrapped token, issuer/resource and original normal Cloud + // tool path. The optional origin is ONLY the owned reply-loss transport. + tool:(name:string,args:Record,ownedOrigin?:string)=>Promise; + cloudLoopback:string; + caseDeadline:number; + assertPassiveQuiet:(durationMs:15000)=>Promise; +}){ + const bounded=async(work:Promise,deadline:number,label:string)=>{ + const remaining=Math.min(deadline,input.caseDeadline)-performance.now();assert(remaining>0,label); + let timer:ReturnType|undefined; + try{return await Promise.race([work,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(label)),remaining);})]);} + finally{clearTimeout(timer);} + }; + const until=async(read:()=>Promise,accept:(value:T)=>boolean,deadline:number):Promise=>{ + for(;;){const value=await bounded(read(),deadline,"original_followon_deadline_exhausted");if(accept(value))return value; + await bounded(pause(25),deadline,"original_followon_deadline_exhausted");} + }; + const firstIdentity={pid:input.first.pid,started:input.first.started,bootId:input.first.bootId}; + await input.first.stop(Math.min(input.caseDeadline,performance.now()+15000)); + const second=await bounded(input.startSecond(),input.caseDeadline,"original_followon_setup_deadline_exhausted"); + assert.notEqual(second.pid,firstIdentity.pid);assert.notEqual(second.bootId,firstIdentity.bootId); + // First owner proved actual old PID/group absence before second startup. No + // service-only reconstruction or fake process observation can satisfy that. + const listed=await input.tool("paperclip_dot_tasks",{});assert.equal(listed.status,200);assert.equal(listed.body.result?.isError,false); + const created=await input.createTask({title:"Save a fresh post-restart report",description:"Save a report document containing 31 + 11 = 42 using assigned Paperclip tools.", + workMode:"standard",status:"todo",assigneeAgentId:input.agentId}); + assert.equal(created.status,201);assert.match(created.body.id,/^[a-f0-9-]{36}$/); + const taskId=created.body.id,admissionId=randomUUID(); + const admitted=await input.tool("paperclip_dot_request_work",{issueId:taskId,requestId:admissionId}); + assert.equal(admitted.status,200);assert.equal(admitted.body.result?.isError,false); + const runs=await until(()=>input.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.issueId,taskId)), + rows=>rows.some(row=>row.runtimeMode==="native"&&row.status==="running"),Math.min(input.caseDeadline,performance.now()+30000)); + assert.equal(runs.length,1);const runId=runs[0].id; + const assignments=await until(()=>input.db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId,runId)), + rows=>rows.length===1,Math.min(input.caseDeadline,performance.now()+30000)); + const assignment=assignments[0];assert.equal(assignment.companyId,input.companyId);assert.equal(assignment.agentId,input.agentId); + const acceptId=randomUUID(); + const accepted=await input.tool("paperclip_dot_accept",{assignmentId:assignment.id,requestId:acceptId}); + assert.equal(accepted.status,200);assert.equal(accepted.body.result?.isError,false); + await until(()=>input.db.select().from(dotRunnerOperations).where(eq(dotRunnerOperations.requestId,acceptId)), + rows=>rows.length===1&&rows[0].status==="completed",Math.min(input.caseDeadline,performance.now()+10000)); + const requestId=randomUUID(); + const args={name:"write_document",arguments:{key:"report",title:"Fresh arithmetic report",body:"31 + 11 = 42.",baseRevisionId:null,idempotencyKey:requestId}}; + const digest=externalOperationDigest("tool",args); + let committedJournal:typeof dotRunnerOperations.$inferSelect|undefined; + const awaitActualCommit=async()=>{ + const rows=await until(()=>input.db.select().from(dotRunnerOperations).where(eq(dotRunnerOperations.requestId,requestId)), + rows=>rows.length===1&&rows[0].status==="completed",Math.min(input.caseDeadline,performance.now()+10000)); + assert.equal(rows.length,1);committedJournal=rows[0];assert.equal(committedJournal.digest,digest); + assert.equal(committedJournal.assignmentId,assignment.id);assert.equal(committedJournal.companyId,input.companyId); + assert(committedJournal.sourceEventId);assert.deepEqual(committedJournal.command,{bindingId:assignment.bindingId,bindingGeneration:assignment.bindingGeneration, + runId,normalizedSessionId:assignment.normalizedSessionId,turnId:assignment.turnId,assignmentRevision:assignment.revision,requestId,action:"tool",input:args,digest}); + const document=await documentService(input.db).getIssueDocumentByKey(taskId,"report");assert(document);assert.equal(document.body,"31 + 11 = 42."); + }; + const loss=await createCommittedReplyLoss({cloudLoopback:input.cloudLoopback,assignmentId:assignment.id,requestId,inputDigest:digest,awaitActualCommit}); + try{ + let lost=false; + try{await input.tool("paperclip_dot_tool",{assignmentId:assignment.id,requestId,...args},loss.origin);} + catch{lost=true;} + // A generic network error is insufficient: exact actual request selected, + // backend handler completed and normal journal+document committed BEFORE + // this ONE frontend response was physically lost. + assert(lost);await bounded(loss.droppedResponseClosed,input.caseDeadline,"lost_response_close_not_observed"); + assert.deepEqual(loss.evidence,{armed:false,selected:1,backendCompleted:1,committed:1,dropped:1,closedAfterDrop:1,overflow:0,observerFailures:0}); + const before=await documentService(input.db).getIssueDocumentByKey(taskId,"report");assert(before); + const replay=await input.tool("paperclip_dot_tool",{assignmentId:assignment.id,requestId,...args}); + assert.equal(replay.status,200);assert.equal(replay.body.result?.isError,false); + const journals=await input.db.select().from(dotRunnerOperations).where(eq(dotRunnerOperations.requestId,requestId)); + assert.equal(journals.length,1);assert.deepEqual(journals[0],committedJournal); + const after=await documentService(input.db).getIssueDocumentByKey(taskId,"report");assert.deepEqual(after,before); + const conflict=await input.tool("paperclip_dot_tool",{assignmentId:assignment.id,requestId,...args,arguments:{...args.arguments,body:"different"}}); + assert.equal(conflict.body.result?.isError,true);assert.deepEqual(await documentService(input.db).getIssueDocumentByKey(taskId,"report"),before); + const [run]=await input.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id,runId));assert(run.completionContractId); + const [contract]=await input.db.select().from(completionContracts).where(eq(completionContracts.id,run.completionContractId)); + const specification=z.object({revision:z.string(),criteria:z.array(z.object({id:z.string()}))}).passthrough().parse(contract.contractJson); + const result={reportedWorkDisposition:"completed",summary:"Saved fresh arithmetic report.",completionClaim:{contractRevision:specification.revision, + objectiveSatisfied:true,criteria:specification.criteria.map(criterion=>({criterionId:criterion.id,status:"passed",evidenceRefs:[]})),remainingWork:[]}, + evidence:[],verification:[{commandOrCheck:"Read the persisted report: 31 + 11 = 42.",status:"pass"}]}; + const finishToolId=randomUUID(); + const finishedTool=await input.tool("paperclip_dot_tool",{assignmentId:assignment.id,requestId:finishToolId,name:"paperclip_finish",arguments:result}); + assert.equal(finishedTool.status,200);assert.equal(finishedTool.body.result?.isError,false); + await until(()=>input.db.select().from(dotRunnerOperations).where(eq(dotRunnerOperations.requestId,finishToolId)), + rows=>rows.length===1&&rows[0].status==="completed",Math.min(input.caseDeadline,performance.now()+10000)); + const finish=await input.tool("paperclip_dot_finish",{assignmentId:assignment.id,requestId:randomUUID(),result}); + assert.equal(finish.status,200);assert.equal(finish.body.result?.isError,false); + const results=await until(()=>input.db.select().from(nativeRunResults).where(eq(nativeRunResults.runId,runId)),rows=>rows.length===1, + Math.min(input.caseDeadline,performance.now()+15000));assert.equal(results.length,1); + const [task]=await input.db.select().from(issues).where(eq(issues.id,taskId));assert.equal(task.status,"done"); + await input.assertPassiveQuiet(15000); + return {second,firstIdentity,secondIdentity:{pid:second.pid,started:second.started,bootId:second.bootId},taskId,runId, + requestId,assignmentId:assignment.id,committedReplyLoss:{...loss.evidence},oneEffect:true}; + }finally{await loss.close();} +} diff --git a/server/src/__tests__/helpers/owned-linux/worker.mjs b/server/src/__tests__/helpers/owned-linux/worker.mjs new file mode 100644 index 00000000000..67bfa7722fd --- /dev/null +++ b/server/src/__tests__/helpers/owned-linux/worker.mjs @@ -0,0 +1,9 @@ +// PRIVATE unrun normal SDK worker. Normal host launcher already invokes its +// canonical parseRemoteRunnerProcessIdentity on the ORIGINAL command stdout +// before processIdentityReady/onSpawn and the real PRP connection. Preserve that +// owner rather than importing a giant App module into the provider worker. +import { readFile } from "node:fs/promises"; +import { startLinuxQualificationWorker } from "./qualification-provider.js"; +import { createOwnedLinuxProvider } from "./owned-provider-implementation.mjs"; +const config = JSON.parse(await readFile(new URL("./owned-runtime-config.json", import.meta.url), "utf8")); +startLinuxQualificationWorker(createOwnedLinuxProvider(config), import.meta.url);