@byok-sdk/bot-collaboration 0.44.1 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/testing.js CHANGED
@@ -1,6 +1,5 @@
1
- import { projectionRequestId, inboundKey, ROUTINE_WAIT_MS, RetentionRefused, ROUTINE_LATE_AFTER_MS } from './chunk-6X7ARUDF.js';
2
- import { outcomeSchema, wouldDoRows, syncTurn, OFFER_WAIT_MS, roomFields, roomInput, ROOM_GRACE_MS, archiveBot, RetiredIdentityError, CommitConflict, roomContext, json, TeamModeError } from './chunk-BGGEZHPC.js';
3
- import { describe, it, expect } from 'vitest';
1
+ import { projectionRequestId, inboundKey, ROUTINE_WAIT_MS, RetentionRefused, ROUTINE_LATE_AFTER_MS } from './chunk-DYQSVSPJ.js';
2
+ import { outcomeSchema, wouldDoRows, syncTurn, OFFER_WAIT_MS, roomFields, roomInput, ROOM_GRACE_MS, archiveBot, RetiredIdentityError, CommitConflict, roomContext, json, TeamModeError } from './chunk-4HLCBNWV.js';
4
3
  import { hash, taskId, HostLedger, MIN_TOMBSTONE_RETENTION_MS } from '@byok-sdk/server/execution-core';
5
4
  import { BOT_TURN_OUTCOME_CONTRACT, nextRoutineOccurrence } from '@byok-sdk/protocol';
6
5
  import { spawn } from 'child_process';
@@ -13,7 +12,7 @@ import { serve } from '@hono/node-server';
13
12
  import { RuntimeDisposalFailure, freezeRuntimeAdapterDescriptor, buildRuntimeEnvironment, createDaemonWithAdapters } from '@byok-sdk/client';
14
13
  import { createByokServer } from '@byok-sdk/server';
15
14
 
16
- var policy={policyRevision:"k4-v1",activity:{delivery:"latest-value",maxCoalesceMs:250,maxEventBytes:262144},reliable:{maxPendingEventsPerAgent:16,maxPendingBytesPerAgent:4096,maxPendingBytesPerTenant:16384},transfers:{workspace:"disabled",transcript:"disabled",artifact:"disabled"}};function template(deviceId,agentId="main"){return {deviceId,payload:{target:{lane:"runtime",runtimeId:"pi"},session:{mode:"fresh"},instruction:"Return the test result through submit_result.",agentRef:{agentId,profileRevision:"1"},egressPolicy:policy,terminalProjection:{mode:"result-document",contract:"host-core-test-v1",schema:{type:"object",additionalProperties:false,required:["text"],properties:{text:{type:"string"}}}}}}}var noPublish=()=>{};var VECTOR_NOW=1e3;function seedCollaboration(state,team="local"){state.team.bots.main={id:"main",name:"Main",role:"Team owner",persona:"",model:"default",mainBot:true,archived:false,revision:"1",readyRevision:"1",execution:template("device","main"),autonomy:"auto"};state.turns.t1={id:"t1",root:"t1",botId:"main",source:"user",request:"Work",hop:0,status:"processing",authority:"owner"};state.budgets.t1={continuation:0,delegation:0};state.schemas.t1=outcomeSchema("main",state,state.turns.t1);state.questions.q1={id:"q1",turnId:"t1",value:{question:"Go?",answerKind:"text"}};state.cards.c1={id:"c1",turnId:"t1",action:{action:"send_message",summary:"Send",draft:{text:"hi"}},state:"pending",expiresAt:0};if(team==="external")state.team.external={revision:1};if(team==="rooms")state.team.external={revision:1,rooms:true};}var input=(key,request="Hello")=>({kind:"input",botId:"main",key,request,sender:"owner"});var settle=async work=>work();var teamError=async work=>{try{await work();}catch(cause){return cause instanceof TeamModeError?cause.code:cause}return "no error"};function commitVectors(name,open){describe(`commit contract: ${name}`,()=>{const request=(subject,commandId,command,expectedRevision)=>({scope:subject.scope,commandId,command,...expectedRevision===void 0?{}:{expectedRevision}});const conflict=async(subject,req,code,message)=>{const before=await subject.stored();let error;try{await subject.commit(req);}catch(cause){error=cause;}expect(error).toBeInstanceOf(CommitConflict);expect(error.code).toBe(code);if(message)expect(error.message).toBe(message);expect(await subject.stored()).toBe(before);};it("commits a new command once and returns the same result to a replay",async()=>{const subject=await open(),first=await subject.commit(request(subject,"i1",input("k1")));expect(first).toEqual({revision:1,disposition:{outcome:"accepted",value:hash(["user","main","k1"])},outbox:[]});const stored=await subject.stored();expect(await subject.commit(request(subject,"i1",input("k1")))).toEqual(first);expect(await subject.stored()).toBe(stored);});it("replays with the original expected revision after the head moved",async()=>{const subject=await open(),first=await subject.commit(request(subject,"i1",input("k1"),0));expect((await subject.commit(request(subject,"i2",input("k2")))).revision).toBe(2);expect(await subject.commit(request(subject,"i1",input("k1"),0))).toEqual(first);});it("refuses the same command id with other content, and keeps the existing error text",async()=>{const subject=await open();await subject.commit(request(subject,"i1",input("k1")));await conflict(subject,request(subject,"i1",input("k1","Other")),"identity_conflict","Input identity conflict");await subject.commit(request(subject,"a1",{kind:"answer",questionId:"q1",answer:"Yes"}));await conflict(subject,request(subject,"a1",{kind:"answer",questionId:"q1",answer:"No"}),"identity_conflict","Answer identity conflict");});it("decides on the head without an expected revision, and refuses a stale explicit revision",async()=>{const subject=await open();expect((await subject.commit(request(subject,"i1",input("k1")))).revision).toBe(1);await conflict(subject,request(subject,"i2",input("k2"),0),"stale_revision");expect((await subject.commit(request(subject,"i2",input("k2"),1))).revision).toBe(2);});it("refuses a commit for another scope",async()=>{const subject=await open();await conflict(subject,{...request(subject,"i1",input("k1")),scope:`${subject.scope}:other`},"scope_mismatch");});it("keeps no revision, record or outbox row when the decision throws",async()=>{const subject=await open(),before=await subject.stored();await expect(settle(()=>subject.commit(request(subject,"i1",{...input("k1"),botId:"absent"})))).rejects.toThrow("Bot is archived or absent");expect(await subject.stored()).toBe(before);expect((await subject.commit(request(subject,"i1",input("k1")))).revision).toBe(1);});it("commits a refused disposition and replays it",async()=>{const subject=await open(),decide={kind:"decide",cardId:"c1",decision:"confirmed"};const first=await subject.commit(request(subject,"d1",decide));expect(first).toEqual({revision:1,disposition:{outcome:"refused",reasonCode:"card_expired",reason:"Card expired"},outbox:[]});expect(await subject.commit(request(subject,"d1",decide))).toEqual(first);await conflict(subject,request(subject,"d1",{...decide,decision:"rejected"}),"identity_conflict","Card expired");});it("applies a keyless command at each call, adds 1 each time and keeps no record (#739 6a)",async()=>{const subject=await open(),command={kind:"set_main_bot",botId:"main",mainBot:true};await subject.commit(request(subject,"i1",input("k1")));expect(await subject.commit(request(subject,"m1",command))).toEqual({revision:2,disposition:{outcome:"accepted"},outbox:[]});expect((await subject.commit(request(subject,"m1",command))).revision).toBe(3);expect(Object.keys((await subject.state()).commands??{})).toEqual(["i1"]);});it("protects a keyless retry only with an explicit expected revision",async()=>{const subject=await open(),command={kind:"set_main_bot",botId:"main",mainBot:false};expect((await subject.commit(request(subject,"m1",command,0))).revision).toBe(1);await conflict(subject,request(subject,"m1",command,0),"stale_revision");expect((await subject.commit(request(subject,"m1",command,1))).revision).toBe(2);});it("keys each record by its own command id, also for `constructor` and `__proto__`",async()=>{const subject=await open();for(const[index,id]of ["constructor","toString","__proto__"].entries()){const first=await subject.commit(request(subject,id,input(`k${index}`)));expect(first.revision).toBe(index+1);const stored=await subject.stored();expect(await subject.commit(request(subject,id,input(`k${index}`)))).toEqual(first);expect(await subject.stored()).toBe(stored);}});const main={id:"main",name:"Main",role:"Team owner",mainBot:true};const team=(revision,...bots)=>[hash(["team",revision]),{kind:"team_snapshot",snapshot:{revision,bots:bots.map(bot=>({name:bot.id,role:"Helper",persona:"",model:"default",mainBot:false,...bot}))}}];const withRooms=([id,command],rooms)=>[id,{...command,snapshot:{...command.snapshot,rooms}}];it("applies a newer team snapshot: archives a missing Bot, adds a new one and queues a projection for a changed one (#739 Q4c)",async()=>{const subject=await open("external");await subject.commit(request(subject,...team(2,main,{id:"b2"})));expect(await subject.commit(request(subject,...team(3,{...main,persona:"New"})))).toEqual({revision:2,disposition:{outcome:"accepted"},outbox:[]});const state=await subject.state();expect(state.team.external).toEqual({revision:3});expect(state.team.bots.b2).toMatchObject({archived:true,mainBot:false,revision:"1",readyRevision:null});expect(state.team.bots.main).toMatchObject({archived:false,mainBot:true,persona:"New",revision:"2",readyRevision:null});expect(state.team.homeOperations.map(op=>[op.botId,op.request.payload.agentRef.profileRevision])).toEqual([["b2","1"],["main","2"]]);});it("replays a team revision with the same Bots in any order, and refuses other Bots for it",async()=>{const subject=await open("external"),first=await subject.commit(request(subject,...team(2,main,{id:"b2"})));const stored=await subject.stored();expect(await subject.commit(request(subject,...team(2,{id:"b2"},main)))).toEqual(first);expect(await subject.stored()).toBe(stored);await conflict(subject,request(subject,...team(2,main)),"identity_conflict","Team snapshot identity conflict");});it("refuses a team revision that is not newer with stale_team, after a replay check",async()=>{const subject=await open("external"),applied=await subject.commit(request(subject,...team(2,main)));await subject.commit(request(subject,...team(4,main)));expect(await subject.commit(request(subject,...team(2,main)))).toEqual(applied);expect(await subject.commit(request(subject,...team(3,main)))).toEqual({revision:3,disposition:{outcome:"refused",reasonCode:"stale_team",reason:"stale_team: team revision 3 is not newer than 4"},outbox:[]});expect((await subject.commit(request(subject,...team(1,main)))).disposition).toMatchObject({reasonCode:"stale_team"});expect((await subject.state()).team.external).toEqual({revision:4});});it("changes nothing for an invalid team snapshot, a returning archived Bot or setMainBot in external mode",async()=>{const subject=await open("external"),before=await subject.stored();await expect(settle(()=>subject.commit(request(subject,...team(2,main,main))))).rejects.toThrow("Duplicate team snapshot Bot");for(const id of ["__proto__","constructor","team/helper","CON","tab here","x".repeat(300)]){await expect(settle(()=>subject.commit(request(subject,...team(2,main,{id}))))).rejects.toThrow("Invalid team snapshot Bot id");}await expect(settle(()=>subject.commit(request(subject,...team(2,main,{id:"b2",persona:"x".repeat(7e4)}))))).rejects.toThrow("Team snapshot Bot projection is too large");await expect(settle(()=>subject.commit(request(subject,...team(2,main,{id:"b2",participation:"active"}))))).rejects.toThrow(/^Invalid team snapshot Bot$/);expect(await teamError(()=>subject.commit(request(subject,"m1",{kind:"set_main_bot",botId:"main",mainBot:false})))).toBe("external_team");expect(await subject.stored()).toBe(before);await subject.commit(request(subject,...team(2,main,{id:"b2"})));await subject.commit(request(subject,...team(3,main)));const archived=await subject.stored();await expect(settle(()=>subject.commit(request(subject,...team(4,main,{id:"b2"}))))).rejects.toThrow("An archived Bot cannot return");expect(await subject.stored()).toBe(archived);const execution=(await subject.state()).team.bots.main.execution;await subject.commit(request(subject,...team(4,{...main,model:"absent"})));expect((await subject.state()).team.bots.main).toMatchObject({model:"absent",revision:"2",execution:{...execution,payload:{...execution.payload,agentRef:{agentId:"main",profileRevision:"2"}}}});});it("refuses a team snapshot for a local team",async()=>{const subject=await open(),before=await subject.stored();await expect(settle(()=>subject.commit(request(subject,...team(1,main))))).rejects.toThrow("Team snapshots need the external team mode");expect(await subject.stored()).toBe(before);});it("creates an owner room with the Host room id: a replay returns the first result, other fields conflict (#1321)",async()=>{const subject=await open(),fields={name:"Macro",members:["main"]};const create=(roomId,commandId=hash(["create_room",roomId]))=>request(subject,commandId,{kind:"create_room",roomId,fields});const first=await subject.commit(create("macro"));expect(first).toEqual({revision:1,disposition:{outcome:"accepted"},outbox:[]});const stored=await subject.stored();expect(await subject.commit(create("macro"))).toEqual(first);expect(await subject.stored()).toBe(stored);await conflict(subject,{...create("macro"),command:{kind:"create_room",roomId:"macro",fields:{...fields,name:"Other"}}},"identity_conflict","Room identity conflict");expect((await subject.state()).team.rooms.macro).toEqual({id:"macro",name:"Macro",members:["main"],mode:"mention",announcement:"",visibleFrom:{main:0},messages:[]});const round=await subject.commit(request(subject,"r1",{kind:"room_input",key:"m1",roomId:"macro",text:"Hello",mentions:["main"]}));expect((await subject.state()).team.rounds[round.disposition.value]).toMatchObject({roomId:"macro"});await expect(settle(()=>subject.commit(create("macro","other")))).rejects.toThrow("Room already exists");for(const id of ["a:b","constructor"])await expect(settle(()=>subject.commit(create(id)))).rejects.toThrow("Invalid room id");});it("writes the rooms of a team snapshot in the external rooms mode as a whole (#1321)",async()=>{const subject=await open("rooms"),bots=[main,{id:"b2"},{id:"b3"}];await subject.commit(request(subject,...withRooms(team(2,...bots),[{id:"r",name:"R",members:["main","b2"],admin:"b2",announcement:"Hi",memberMentions:"ignore"}])));expect((await subject.state()).team.rooms.r).toEqual({id:"r",name:"R",members:["main","b2"],admin:"b2",mode:"mention",announcement:"Hi",memberMentions:"ignore",visibleFrom:{main:0,b2:0},messages:[]});await subject.commit(request(subject,"r1",{kind:"room_input",key:"m1",roomId:"r",text:"Hello",mentions:[]}));await subject.commit(request(subject,...withRooms(team(3,...bots),[{id:"r",name:"R",members:["main","b3"]}])));expect((await subject.state()).team.rooms.r).toEqual({id:"r",name:"R",members:["main","b3"],mode:"mention",announcement:"",visibleFrom:{main:0,b3:1},messages:[expect.objectContaining({text:"Hello"})]});});it("refuses local room management and a snapshot whose rooms do not match the mode, and changes nothing (#1321)",async()=>{const subject=await open("rooms"),before=await subject.stored();const commands=[{kind:"create_room",roomId:"r",fields:{name:"R",members:["main"]}},{kind:"update_room",roomId:"r",update:{name:"S"}},{kind:"set_room_member_mentions",roomId:"r",memberMentions:"ignore"}];for(const command of commands)expect(await teamError(()=>subject.commit(request(subject,command.kind,command)))).toBe("external_rooms");await expect(settle(()=>subject.commit(request(subject,...team(2,main))))).rejects.toThrow("A team snapshot needs rooms in the external rooms mode");for(const field of [{mode:null},{mode:""},{mode:0},{mode:false},{mode:"admin"},{admin:""}]){await expect(settle(()=>subject.commit(request(subject,...withRooms(team(2,main),[{id:"r",name:"R",members:["main"],...field}]))))).rejects.toThrow(/^Invalid team snapshot room$/);}expect(await subject.stored()).toBe(before);const local=await open("external"),stored=await local.stored();await expect(settle(()=>local.commit(request(local,...withRooms(team(2,main),[]))))).rejects.toThrow("Snapshot rooms need the external rooms mode");expect(await local.stored()).toBe(stored);});it("records an observing Bot's create_routine once as a would-do row and creates no routine (#1229)",async()=>{const subject=await open(),document={create_routine:[{localId:"new_routine_1",schedule:{hour:9,minute:0,tz:"UTC"},prompt:"Daily report"}]};await subject.commit(request(subject,"observe",{kind:"set_autonomy",botId:"main",autonomy:"observe"}));const first=await subject.commit(request(subject,"task-1",{kind:"outcome",turnId:"t1",taskId:"task-1",document}));const replay=await subject.commit(request(subject,"task-1",{kind:"outcome",turnId:"t1",taskId:"task-1",document}));const state=await subject.state();expect(wouldDoRows(state)).toEqual([expect.objectContaining({botId:"main",action:"create_routine",index:0})]);expect(first.outbox).toEqual([{kind:"projection",id:`would-do:${wouldDoRows(state)[0].id}`}]);if(replay.revision===first.revision)expect(replay).toEqual(first);expect(state.rejected).toEqual([]);});it("returns the outbox rows that the commit wrote",async()=>{const subject=await open(),card=hash(["task-1","confirmable_action",0]);const result=await subject.commit(request(subject,"task-1",{kind:"outcome",turnId:"t1",taskId:"task-1",document:{confirmable_action:[{action:"send_message",summary:"Send",draft:{text:"hello"}}]}}));expect(result).toEqual({revision:1,disposition:{outcome:"accepted"},outbox:[{kind:"projection",id:`card:${card}`}]});});});}var SYNC_OPTIONS={now:VECTOR_NOW,models:["default"],readOnlyToolsets:[],limits:{turnLimit:12,contextMaxBytes:32768,instructionMaxBytes:65536},historyMode:false,routines:[]};function seedSync(state){Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.cards.c1.expiresAt=Number.MAX_SAFE_INTEGER;state.turns.q1={id:"q1",root:"q1",botId:"main",source:"user",request:"First",hop:0,status:"queued",authority:"owner"};state.turns.q2={id:"q2",root:"q1",botId:"main",source:"continuation",request:"Next",hop:0,status:"queued",authority:"owner"};}var NO_FACTS={intent:()=>void 0,executionStarted:()=>false,retired:()=>void 0};function syncVectors(name,open){describe(`sync contract: ${name}`,()=>{const seeded=async()=>{const subject=await open();await subject.change(seedSync);return subject};it("stores the frozen intent input as the rule returns it, with no command record and no revision change",async()=>{const subject=await seeded(),before=await subject.state();const expected=structuredClone(before),step=syncTurn(expected,expected.turns.q1,NO_FACTS,SYNC_OPTIONS,()=>{});await subject.sync();const after=await subject.state();expect(step).toMatchObject({kind:"freeze"});expect(await subject.intent("q1")).toEqual(step.input);expect(await subject.intent("q1")).toMatchObject({key:"q1",source:"user",waitUntil:VECTOR_NOW+OFFER_WAIT_MS,execution:{payload:{terminalProjection:{mode:"result-document",contract:BOT_TURN_OUTCOME_CONTRACT,schema:after.schemas.q1}}}});expect(await subject.intent("q2")).toMatchObject({key:"q2",source:"bot"});expect(await subject.intent("t1")).toBeUndefined();expect([after.turns.q1.status,after.turns.q2.status]).toEqual(["processing","processing"]);expect([after.revision,after.commands]).toEqual([before.revision,before.commands]);});it("changes no stored byte at a second sync",async()=>{const subject=await seeded();await subject.sync();const stored=await subject.stored();await subject.sync();expect(await subject.stored()).toBe(stored);});it("keeps the expected revision of a client valid across a sync",async()=>{const subject=await seeded(),revision=(await subject.state()).revision??0;await subject.sync();const result=await subject.commit({scope:subject.scope,commandId:"i1",command:input("k1"),expectedRevision:revision});expect(result.revision).toBe(revision+1);});it("writes the report of a concluded intent to the outbox once, at the same revision",async()=>{const subject=await seeded();await subject.sync();await subject.concludeIntent("q1","succeeded");const revision=(await subject.state()).revision;expect(await subject.projection("bot-turn:q1")).toEqual([]);await subject.sync();expect(await subject.projection("bot-turn:q1")).toEqual([expect.objectContaining({owner:"main",id:"q1",status:"succeeded",conclusion:"succeeded"})]);const after=await subject.state();expect([after.turns.q1.status,after.turns.q1.reported,after.revision]).toEqual(["succeeded",true,revision]);const stored=await subject.stored();await subject.sync();expect(await subject.stored()).toBe(stored);});});}function settlementSteps(open){const settled=async(subject,now=VECTOR_NOW,timers)=>{for(let round=0;round<5;round++){const before=await subject.stored();await subject.settle(now,timers);if(await subject.stored()===before)return}throw new Error("The sync does not settle")};let commands=0;const commit=async(subject,command)=>{const result=await subject.commit({scope:subject.scope,commandId:`settle-${++commands}`,command});if(result.disposition.outcome!=="accepted")throw new Error(`Refused ${command.kind}: ${JSON.stringify(result.disposition)}`);return result.disposition.value};const owner=async(subject,key,document)=>{const turnId=await commit(subject,{kind:"input",botId:"main",key,request:key,sender:"owner"});await settled(subject);await commit(subject,{kind:"outcome",turnId,taskId:taskId(turnId,0),document});await subject.terminal(turnId,"task.complete",{document});await subject.conclude(turnId,"succeeded");await settled(subject);return turnId};const delegated=async()=>{const subject=await open();await subject.change(state=>{Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.team.bots.b={...state.team.bots.main,id:"b",name:"B",role:"Reviewer",mainBot:false,execution:template("device","b")};});const root=await owner(subject,"r1",{delegate:[{to:"b",request:"Check"}]});const id=hash([taskId(root,0),"delegate",0]);expect(await subject.intent(id)).toMatchObject({key:id});return {subject,root,id,delegation:async()=>(await subject.state()).delegations[id]}};return {settled,commit,owner,delegated}}function settlementVectors(name,open){describe(`settlement contract: ${name}`,()=>{const TIMERS={cancelGraceMs:1e3,uncertainAfterMs:5e3};const{settled,commit,owner,delegated}=settlementSteps(open);const unit=(state,id)=>state.units[hash([id,"B"])].state;const ends=[["a failed terminal",async(subject,id)=>{await subject.terminal(id,"task.fail",{});await subject.conclude(id,"failed");},{verdict:"failed"},"spent"],["a busy decline",async(subject,id)=>{await subject.terminal(id,"task.decline",{code:"agent_home_writer_busy"});await subject.conclude(id,"declined");},{verdict:"failed",reason:"busy"},"released"],["a decline with no code",async(subject,id)=>{await subject.terminal(id,"task.decline",{});await subject.conclude(id,"declined");},{verdict:"failed",reason:"busy"},"released"],["another decline",async(subject,id)=>{await subject.terminal(id,"task.decline",{code:"model_unavailable"});await subject.conclude(id,"declined");},{verdict:"failed",reason:"model_unavailable"},"released"],["an expiry",async(subject,id)=>{await subject.conclude(id,"expired");},{verdict:"expired"},"released"],["a cancel that raced the wait deadline",async(subject,id)=>{await subject.conclude(id,"cancelled","expired");},{verdict:"expired",reason:"claim_raced_deadline"},"released"],["a cancel",async(subject,id)=>{await subject.conclude(id,"cancelled","cancelled");},{verdict:"cancelled",reason:"user_cancelled"},"released"]];for(const[end,conclude,verdict,units]of ends){it(`gives ${end} of the chain end its verdict, and spends or releases the unit`,async()=>{const{subject,id,delegation:delegation2}=await delegated();await conclude(subject,id);await settled(subject);const state=await subject.state(),d=await delegation2();expect(d).toMatchObject({...verdict,status:"resolved",replyTurnId:hash(["bot_reply",id])});if(!verdict.reason)expect(d.reason).toBeUndefined();expect(unit(state,id)).toBe(units);expect(state.turns[d.replyTurnId]).toMatchObject({source:"bot_reply",botId:"main",replies:[expect.objectContaining(verdict)]});});}it("spends the unit at the first claim, and the delegation runs",async()=>{const{subject,id,delegation:delegation2,root:chain}=await delegated();const root=(await delegation2()).root,before=(await subject.state()).budgets[root];await subject.claim(id);await settled(subject);const state=await subject.state();expect(unit(state,id)).toBe("spent");expect(state.budgets[root]).toMatchObject({reserved:before.reserved-1,delegation:before.delegation+1});expect(await delegation2()).toMatchObject({status:"running",claimed:{turnId:id,at:VECTOR_NOW}});expect(await subject.projection(`delegation:${id}:2`)).toEqual([expect.objectContaining({root:chain,status:"running"})]);});it("takes a decline terminal as no start, and any other terminal as a start",async()=>{const declined=await delegated();await declined.subject.terminal(declined.id,"task.decline",{code:"model_unavailable"});await settled(declined.subject);expect(unit(await declined.subject.state(),declined.id)).toBe("reserved");expect((await declined.delegation()).status).not.toBe("running");const failed=await delegated();await failed.subject.terminal(failed.id,"task.fail",{});await settled(failed.subject);expect(unit(await failed.subject.state(),failed.id)).toBe("spent");expect(await failed.delegation()).toMatchObject({status:"running"});});it("refuses a delegation whose target Bot was archived (target_archived), once its target concluded",async()=>{const{subject,id,delegation:delegation2}=await delegated();await subject.change(state=>{state.team.bots.b.archived=true;});await settled(subject);expect(await delegation2()).toMatchObject({cancel:{reason:"target_archived",targetTurnId:id}});await subject.conclude(id,"cancelled","cancelled");await settled(subject);expect(await delegation2()).toMatchObject({verdict:"refused",reason:"target_archived",status:"resolved"});});it("suspends a Bot by team snapshot: its work ends, it takes no new work, and a later snapshot restores it (#1319)",async()=>{const{subject,id,delegation:delegation2}=await delegated();const snapshot=(revision,b)=>({kind:"team_snapshot",snapshot:{revision,bots:[{id:"main",name:"Main",role:"Team owner",persona:"",model:"default",mainBot:true},{id:"b",name:"B",role:"Reviewer",persona:"",model:"default",mainBot:false,...b}]}});const input3=(botId,key)=>({kind:"input",botId,key,request:key,sender:"owner"});const targets=async turnId=>(await subject.state()).schemas[turnId].properties.delegate.items.properties.to.enum;await subject.change(state=>{state.team.external={revision:1};state.team.bots.b.autonomy="auto";state.turns.qb={id:"qb",root:"qb",botId:"b",source:"user",request:"Later",hop:0,status:"queued",authority:"owner"};state.questions.qb={id:"qb",turnId:id,value:{question:"Go?",answerKind:"text"}};state.team.rooms.r={id:"r",...roomFields(state.team,{name:"Room",members:["main","b"]}),messages:[]};});const before=(await subject.state()).team.bots.b;await commit(subject,snapshot(2,{participation:"suspended"}));await settled(subject);expect((await subject.state()).turns.qb).toMatchObject({status:"failed",conclusion:"cancelled"});expect(await delegation2()).toMatchObject({cancel:{reason:"target_suspended",targetTurnId:id}});await subject.conclude(id,"cancelled","cancelled");await settled(subject);expect(await delegation2()).toMatchObject({verdict:"refused",reason:"target_suspended",status:"resolved"});const stored=await subject.stored();for(const command of [input3("b","kb"),{kind:"answer",questionId:"qb",answer:"Yes"}]){expect(await teamError(()=>subject.commit({scope:subject.scope,commandId:`refused-${command.kind}`,command}))).toBe("bot_suspended");}expect(await subject.stored()).toBe(stored);const own=await commit(subject,input3("main","k2"));const round=await commit(subject,{kind:"room_input",key:"m1",roomId:"r",text:"Hello",mentions:"all"});await settled(subject);expect(await targets(own)).toEqual(["main"]);const team=(await subject.state()).team,seat=team.rounds[round].seats[0];expect(team.rounds[round].seats.map(id2=>team.seats[id2].botId)).toEqual(["main"]);await subject.change(state=>{state.team.rounds[round].closed=true;state.team.bots.main.autonomy="auto";const turn=state.turns[seat]={id:seat,root:round,source:"room_slot",botId:"main",request:"Hello",hop:0,status:"succeeded",conclusion:"succeeded",reported:true,authority:"bot"};const{participation:_,...b}=state.team.bots.b;state.schemas[seat]=outcomeSchema("main",{...state,team:{...state.team,bots:{...state.team.bots,b}}},turn);});await commit(subject,{kind:"outcome",turnId:seat,taskId:taskId(seat,0),document:{speech:{kind:"post",text:"Over to b"},room_call:{members:["b"]}}});const called=await subject.state();expect(called.rejected).toContainEqual(expect.objectContaining({action:"room_call",reason:"bot_suspended: Bot b is not participating"}));expect(Object.keys(called.team.rounds)).toEqual(Object.keys(team.rounds));await commit(subject,snapshot(3,{}));const after=(await subject.state()).team.bots.b;expect(after.participation).toBeUndefined();expect([after.revision,after.readyRevision,after.autonomy]).toEqual([before.revision,before.readyRevision,"auto"]);const restored=await commit(subject,input3("b","kb")),next=await commit(subject,input3("main","k3"));await settled(subject);expect(await subject.intent(restored)).toMatchObject({key:restored});expect(await targets(next)).toEqual(["main","b"]);});it("archives a room that a rooms-mode snapshot no longer lists: its seats are removed, a started seat's speech is audit only (#1321)",async()=>{const subject=await open();const bots=[{id:"main",name:"Main",role:"Team owner",persona:"",model:"default",mainBot:true},{id:"b",name:"B",role:"Reviewer",persona:"",model:"default",mainBot:false}];const snapshot=(revision,rooms)=>({kind:"team_snapshot",snapshot:{revision,bots,rooms}});const room2={id:"r",name:"Room",members:["main","b"]};await subject.change(state=>{state.team.external={revision:1,rooms:true};Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.team.bots.b={...state.team.bots.main,id:"b",name:"B",role:"Reviewer",mainBot:false,execution:template("device","b")};});await commit(subject,snapshot(2,[room2]));const round=await commit(subject,{kind:"room_input",key:"m1",roomId:"r",text:"Hello",mentions:["b","main"]});await settled(subject);const[started,waiting]=(await subject.state()).team.rounds[round].seats;await subject.claim(started);await settled(subject);await commit(subject,snapshot(3,[]));await settled(subject);const team=(await subject.state()).team;expect(team.rooms.r).toMatchObject({archived:true,members:[],visibleFrom:{}});expect([team.seats[started],team.seats[waiting]]).toMatchObject([{botId:"b",status:"removed",released:true},{botId:"main",status:"removed",released:true}]);expect(team.rounds[round].closed).toBe(true);await commit(subject,{kind:"outcome",turnId:started,taskId:taskId(started,0),document:{speech:{kind:"post",text:"Late"}}});const after=await subject.state();expect(after.audit).toContain(`Outcome audit only: ${taskId(started,0)}`);expect(after.team.rooms.r.messages.map(message=>message.id)).toEqual([round]);await expect(commit(subject,{kind:"room_input",key:"m2",roomId:"r",text:"Again",mentions:[]})).rejects.toThrow("Room is archived");const stored=await subject.stored();await expect(commit(subject,snapshot(4,[room2]))).rejects.toThrow("An archived room cannot return");expect(await subject.stored()).toBe(stored);});it("shows a cancel with no conclusion as uncertain once the cancel grace passed",async()=>{const{subject,id,delegation:delegation2}=await delegated();await subject.submit(id);await subject.change(state=>{state.team.bots.b.archived=true;});await settled(subject,VECTOR_NOW,TIMERS);await settled(subject,VECTOR_NOW+TIMERS.cancelGraceMs-1,TIMERS);expect((await delegation2()).status).not.toBe("uncertain");await settled(subject,VECTOR_NOW+TIMERS.cancelGraceMs,TIMERS);expect(await delegation2()).toMatchObject({status:"uncertain",uncertainSince:VECTOR_NOW+TIMERS.cancelGraceMs});expect(await delegation2()).not.toHaveProperty("verdict");});const uncertainClaim=async()=>{const h=await delegated();await h.subject.claim(h.id);await settled(h.subject,VECTOR_NOW,TIMERS);await settled(h.subject,VECTOR_NOW+TIMERS.uncertainAfterMs-1,TIMERS);expect((await h.delegation()).status).toBe("running");await settled(h.subject,VECTOR_NOW+TIMERS.uncertainAfterMs,TIMERS);expect(await h.delegation()).toMatchObject({status:"uncertain",uncertainSince:VECTOR_NOW+TIMERS.uncertainAfterMs});return h};it("shows a claimed chain end with no conclusion as uncertain once uncertainAfterMs passed",async()=>{await uncertainClaim();});it("writes a terminal that comes after the verdict to the audit list only, once",async()=>{const{subject,id,delegation:delegation2}=await uncertainClaim();await commit(subject,{kind:"abandon_delegation",delegationId:id});expect(await delegation2()).toMatchObject({verdict:"abandoned",lateTurnId:id});await subject.conclude(id,"cancelled","cancelled");await settled(subject,VECTOR_NOW+TIMERS.uncertainAfterMs,TIMERS);const state=await subject.state();expect(state.audit.filter(line=>line.includes(id))).toEqual([`Delegation terminal after verdict: ${id} ${taskId(id,0)}`]);expect(state.delegations[id]).not.toHaveProperty("lateTurnId");expect(state.delegations[id]).toMatchObject({verdict:"abandoned"});});for(const tried of [false,true]){it(`resolves a Main Bot cancel of ${tried?"a tried":"an untried"} target from a later owner Turn's outcome once the target concluded`,async()=>{const{subject,id,delegation:delegation2}=await delegated();if(tried)await subject.submit(id);await owner(subject,"r2",{cancel_delegation:[{delegationId:id}]});expect(await delegation2()).toMatchObject({cancel:{reason:"main_bot_cancelled",targetTurnId:id}});if(tried){const open2=await delegation2();expect(open2).not.toHaveProperty("verdict");expect(open2.status).not.toBe("uncertain");}await subject.conclude(id,"cancelled","cancelled");await settled(subject);expect(await delegation2()).toMatchObject({verdict:"cancelled",reason:"main_bot_cancelled",status:"resolved"});});}});}function replyVectors(name,open){describe(`reply check contract: ${name}`,()=>{const TIMERS={cancelGraceMs:1e3,uncertainAfterMs:5e3};const{settled,commit,delegated}=settlementSteps(open);const pending=async()=>{const h=await delegated();await commit(h.subject,{kind:"outcome",turnId:h.id,taskId:taskId(h.id,0),document:{}});await h.subject.terminal(h.id,"task.complete",{document:{}});await h.subject.conclude(h.id,"succeeded");await settled(h.subject);expect(await h.delegation()).toMatchObject({status:"reply_pending",checks:0,nextCheckAt:VECTOR_NOW,pendingSince:VECTOR_NOW});const reads=[];const reader=readback=>async(...args)=>{reads.push(args);if(readback instanceof Error)throw readback;return readback};return {...h,reads,reader}};const projected=async h=>h.subject.projection(`delegation:${h.id}:${(await h.delegation()).revision}`);for(const[read,readback]of [["a pending read",{}],["a read that throws",new Error("down")]]){it(`answers a delegation whose reply body the Host holds, after ${read}`,async()=>{const h=await pending();await h.subject.change(state=>{state.replies[taskId(h.id,0)]={turnId:h.id,messageId:"m1",contentHash:"sha256:m1",contentType:"text/markdown",acceptedAt:VECTOR_NOW,body:"Done"};});await h.subject.checkReplies(VECTOR_NOW,h.reader(readback));expect(h.reads).toEqual([[taskId(h.id,0),"device",template("device","b").payload.agentRef]]);const d=await h.delegation();expect(d).toMatchObject({verdict:"answered",status:"resolved",reply:taskId(h.id,0),replyTurnId:hash(["bot_reply",h.id])});expect(d).not.toHaveProperty("nextCheckAt");expect(await projected(h)).toEqual([expect.objectContaining({status:"resolved",verdict:"answered"})]);});}for(const[read,readback]of [["no message",void 0],["a refused message",{disposition:{outcome:"refused"}}]]){it(`fails a delegation whose readback has ${read} (no_reply)`,async()=>{const h=await pending();await h.subject.checkReplies(VECTOR_NOW,h.reader(readback));expect(await h.delegation()).toMatchObject({verdict:"failed",reason:"no_reply",status:"resolved",replyTurnId:hash(["bot_reply",h.id])});});}it("holds a delegation whose message is held, with no verdict and no next check",async()=>{const h=await pending();await h.subject.checkReplies(VECTOR_NOW,h.reader({disposition:{outcome:"held"}}));const d=await h.delegation();expect(d.status).toBe("reply_held");expect(d).not.toHaveProperty("verdict");expect(d).not.toHaveProperty("nextCheckAt");expect(await projected(h)).toEqual([expect.objectContaining({status:"reply_held"})]);});it("checks a pending readback again with backoff, not before its time, and shows it as uncertain once uncertainAfterMs passed",async()=>{const h=await pending(),read=h.reader({});await h.subject.checkReplies(VECTOR_NOW,read,TIMERS);expect(await h.delegation()).toMatchObject({status:"reply_pending",checks:1,nextCheckAt:VECTOR_NOW+1e3});await h.subject.checkReplies(VECTOR_NOW+999,read,TIMERS);expect(h.reads).toHaveLength(1);await h.subject.checkReplies(VECTOR_NOW+1e3,read,TIMERS);expect(await h.delegation()).toMatchObject({status:"reply_pending",checks:2,nextCheckAt:VECTOR_NOW+3e3});await h.subject.checkReplies(VECTOR_NOW+TIMERS.uncertainAfterMs,read,TIMERS);const d=await h.delegation();expect(d).toMatchObject({status:"uncertain",uncertainSince:VECTOR_NOW+TIMERS.uncertainAfterMs,checks:3,nextCheckAt:VECTOR_NOW+TIMERS.uncertainAfterMs+4e3});expect(d).not.toHaveProperty("verdict");expect(h.reads).toHaveLength(3);});for(const[read,readback]of [["a read that throws",new Error("down")],["an accepted message with no Host record",{disposition:{outcome:"accepted"}}]]){it(`checks again after ${read}`,async()=>{const h=await pending();await h.subject.checkReplies(VECTOR_NOW,h.reader(readback));const d=await h.delegation();expect(d).toMatchObject({status:"reply_pending",checks:1,nextCheckAt:VECTOR_NOW+1e3});expect(d).not.toHaveProperty("verdict");});}});}var COALESCE_POLICY={windowMs:1e3,maxItems:2,maxBytes:8192};function coalesceVectors(name,open){describe(`coalesce contract: ${name}`,()=>{const user=key=>hash(["user","main",key]);const busy=async policy2=>{const subject=await open(policy2);await subject.change(state=>{Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.turns.q1={id:"q1",root:"q1",botId:"main",source:"user",request:"First",hop:0,status:"queued",authority:"owner"};});await subject.sync(VECTOR_NOW);return subject};const send=async(subject,key)=>{const result=await subject.commit({scope:subject.scope,commandId:key,command:input(key,`Say ${key}`)});expect(result.disposition.outcome).toBe("accepted");return result.disposition.value};const projected=(subject,batch,revision)=>subject.projection(`input-batch:${batch}:${revision}`);it("answers inputs to a busy Bot with one open batch, and projects its revision 1 at the next sync",async()=>{const subject=await busy(COALESCE_POLICY),batch=user("k1");expect([await send(subject,"k1"),await send(subject,"k2")]).toEqual([batch,batch]);const state=await subject.state();expect(state.turns[batch]).toBeUndefined();expect(state.inputBatches?.[batch]).toMatchObject({state:"open",inputIds:[batch,user("k2")],openedAt:VECTOR_NOW,sealAt:VECTOR_NOW+COALESCE_POLICY.windowMs});expect(await projected(subject,batch,1)).toEqual([]);await subject.sync(VECTOR_NOW);expect(await projected(subject,batch,1)).toEqual([expect.objectContaining({owner:"main",id:batch,revision:1,state:"open",inputIds:[batch,user("k2")],sealAt:VECTOR_NOW+COALESCE_POLICY.windowMs})]);expect(await projected(subject,batch,2)).toEqual([]);});it("seals the batch at the first sync at or after its window ends, and freezes its Turn in that sync",async()=>{const subject=await busy(COALESCE_POLICY),batch=user("k1");await send(subject,"k1");await send(subject,"k2");const request=(await subject.state()).inputBatches[batch].request;await subject.sync(VECTOR_NOW+COALESCE_POLICY.windowMs-1);expect((await subject.state()).inputBatches[batch].state).toBe("open");await subject.sync(VECTOR_NOW+COALESCE_POLICY.windowMs);const state=await subject.state();expect(state.inputBatches[batch]).toMatchObject({state:"sealed",sealReason:"window"});expect(state.turns[batch]).toMatchObject({source:"user",request,authority:"owner",inputIds:[batch,user("k2")]});expect(await subject.intent(batch)).toMatchObject({key:batch,source:"user"});expect(await projected(subject,batch,2)).toEqual([expect.objectContaining({id:batch,revision:2,state:"sealed",sealReason:"window"})]);const stored=await subject.stored();await subject.sync(VECTOR_NOW+COALESCE_POLICY.windowMs);expect(await subject.stored()).toBe(stored);});it("seals a full batch at the next input, so a batch sealed before any sync projects only revision 2",async()=>{const subject=await busy(COALESCE_POLICY),batch=user("k1");await send(subject,"k1");await send(subject,"k2");expect(await send(subject,"k3")).toBe(user("k3"));expect((await subject.state()).inputBatches[batch]).toMatchObject({state:"sealed",sealReason:"items"});await subject.sync(VECTOR_NOW);expect(await projected(subject,batch,1)).toEqual([]);expect(await projected(subject,batch,2)).toEqual([expect.objectContaining({id:batch,revision:2,sealReason:"items"})]);expect(await projected(subject,user("k3"),1)).toEqual([expect.objectContaining({id:user("k3"),revision:1,state:"open"})]);});it("seals an open batch as idle once its Bot has no open Turn",async()=>{const subject=await busy(COALESCE_POLICY),batch=user("k1");await send(subject,"k1");await subject.concludeIntent("q1","succeeded");await subject.sync(VECTOR_NOW);await subject.sync(VECTOR_NOW);const state=await subject.state();expect(state.turns.q1).toMatchObject({conclusion:"succeeded"});expect(state.inputBatches[batch]).toMatchObject({state:"sealed",sealReason:"idle"});expect(await subject.intent(batch)).toMatchObject({key:batch,source:"user"});});it("keeps one Turn for each input without a policy",async()=>{const subject=await busy(void 0);expect(await send(subject,"k1")).toBe(user("k1"));const state=await subject.state();expect(state.turns[user("k1")]).toMatchObject({source:"user",request:"Say k1"});expect(state.inputBatches).toBeUndefined();});});}function cardVectors(name,open){describe(`card contract: ${name}`,()=>{const result=hash(["action_result","c1"]);const opened=async expiresAt=>{const subject=await open();await subject.change(state=>{Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.cards.c1.expiresAt=expiresAt;});return subject};const decide=async(subject,decision)=>{const done=await subject.commit({scope:subject.scope,commandId:`decide-${decision}`,command:{kind:"decide",cardId:"c1",decision}});expect(done.disposition).toEqual({outcome:"accepted"});};it("expires a pending card before the Turn steps, projects it once, and starts no Turn for it",async()=>{const subject=await opened(VECTOR_NOW+10);await subject.sync(VECTOR_NOW+9);expect((await subject.state()).cards.c1).toMatchObject({state:"pending"});expect(await subject.projection("card:c1:expired")).toEqual([]);await subject.change(state2=>{state2.turns.q1={id:"q1",root:"q1",botId:"main",source:"user",request:"First",hop:0,status:"queued",authority:"owner"};});await subject.sync(VECTOR_NOW+10);const state=await subject.state();expect(state.cards.c1).toMatchObject({state:"expired",decisionReported:true});expect(await subject.projection("card:c1:expired")).toEqual([expect.objectContaining({id:"c1",state:"expired"})]);expect(state.turns[result]).toBeUndefined();const instruction=String((await subject.intent("q1")).execution.payload.instruction);expect(instruction).toContain(`"id":"c1","turnId":"t1",`);expect(instruction).toContain(`"state":"expired","expiresAt":${VECTOR_NOW+10}`);const before=await subject.stored();await subject.sync(VECTOR_NOW+10);expect(await subject.stored()).toBe(before);});it("reports a rejected card once, and runs its action_result Turn under the root of the card's Turn",async()=>{const subject=await opened(VECTOR_NOW+6e4);await decide(subject,"rejected");await subject.sync(VECTOR_NOW);await subject.sync(VECTOR_NOW);const state=await subject.state();expect(await subject.projection("card:c1:rejected")).toEqual([expect.objectContaining({id:"c1",state:"rejected"})]);expect(state.turns[result]).toMatchObject({id:result,root:"t1",source:"action_result",botId:"main",hop:0,authority:"owner",request:JSON.stringify({cardId:"c1",state:"rejected"})});expect(await subject.intent(result)).toMatchObject({key:result});const before=await subject.stored();await subject.sync(VECTOR_NOW);expect(await subject.stored()).toBe(before);});it("holds a confirmed card until its action has a result, then reports it with the result",async()=>{const subject=await opened(VECTOR_NOW+6e4);await decide(subject,"confirmed");await subject.sync(VECTOR_NOW);expect(await subject.projection("card:c1:confirmed")).toEqual([]);expect((await subject.state()).turns[result]).toBeUndefined();await subject.change(state=>{Object.assign(state.cards.c1,{result:{sent:true},conclusion:"succeeded"});});await subject.sync(VECTOR_NOW);expect(await subject.projection("card:c1:confirmed")).toEqual([expect.objectContaining({id:"c1",state:"confirmed",result:{sent:true}})]);expect((await subject.state()).turns[result]).toMatchObject({source:"action_result",request:JSON.stringify({cardId:"c1",state:"confirmed",conclusion:"succeeded",result:{sent:true}})});});});}function seedRoom(state){Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.cards.c1.expiresAt=Number.MAX_SAFE_INTEGER;state.team.bots.b={...state.team.bots.main,id:"b",name:"B",role:"Reviewer",mainBot:false,execution:template("device","b")};state.team.rooms.r={id:"r",...roomFields(state.team,{name:"Room",members:["main","b"]}),messages:[]};roomInput(state.team,"m1","r","Hello",["b","main"],noPublish);}function roomVectors(name,open){describe(`room contract: ${name}`,()=>{const opened=async()=>{const subject=await open();await subject.change(seedRoom);const round=Object.values((await subject.state()).team.rounds)[0];const seats=async()=>{const team=(await subject.state()).team;return round.seats.map(id=>team.seats[id])};return {subject,round,first:round.seats[0],second:round.seats[1],seats}};it("queues the first seat as a room_slot Turn with Bot authority, and freezes it in the same sync",async()=>{const{subject,round,first,second,seats}=await opened();await subject.sync(VECTOR_NOW);expect(await seats()).toMatchObject([{botId:"b",status:"queued",released:false,deadline:VECTOR_NOW+ROOM_GRACE_MS},{botId:"main",status:"waiting",released:false}]);const state=await subject.state();expect(state.turns[first]).toMatchObject({id:first,root:first,source:"room_slot",botId:"b",hop:0,authority:"bot",request:JSON.stringify({roomId:"r",roundId:round.id,request:"Hello",requestFrom:"user"})});expect(await subject.intent(first)).toMatchObject({key:first,source:"bot"});expect(state.turns[second]).toBeUndefined();const before=await subject.stored();await subject.sync(VECTOR_NOW);expect(await subject.stored()).toBe(before);});it("cancels an unclaimed seat at its deadline as busy, and queues the next seat",async()=>{const{subject,round,first,second,seats}=await opened(),deadline=VECTOR_NOW+ROOM_GRACE_MS;await subject.sync(VECTOR_NOW);await subject.sync(deadline-1);expect((await seats())[0]).toMatchObject({status:"queued",released:false});expect(await subject.cancelReason(first)).toBeUndefined();await subject.sync(deadline);expect(await seats()).toMatchObject([{status:"busy",released:true},{status:"queued",released:false,deadline:deadline+ROOM_GRACE_MS}]);expect(await subject.cancelReason(first)).toBe("cancelled");expect(await subject.projection(`room-seat:r:${first}`)).toEqual([{roomId:"r",root:round.id,roundId:round.id,seatId:first,botId:"b",status:"busy",late:false}]);expect(await subject.projection(`room-root:r:${round.id}`)).toEqual([]);expect((await subject.state()).turns[second]).toMatchObject({source:"room_slot",botId:"main",authority:"bot"});expect(await subject.intent(second)).toMatchObject({key:second,source:"bot"});});it("releases a claimed seat as late at its running deadline, with no cancel, and queues the next seat",async()=>{const{subject,first,seats}=await opened(),started=VECTOR_NOW+5;await subject.sync(VECTOR_NOW);await subject.claim(first);await subject.sync(started);expect((await seats())[0]).toMatchObject({status:"running",released:false,startedAt:started,deadline:started+ROOM_GRACE_MS});await subject.sync(started+ROOM_GRACE_MS);expect(await seats()).toMatchObject([{status:"late",late:true,released:true},{status:"queued",released:false}]);expect(await subject.cancelReason(first)).toBeUndefined();});it("releases a seat whose Turn concluded with no speech as failed, and queues the next seat",async()=>{const{subject,first,seats}=await opened();await subject.sync(VECTOR_NOW);await subject.concludeIntent(first,"failed");await subject.sync(VECTOR_NOW+1);expect(await seats()).toMatchObject([{status:"failed",released:true,reason:"failed"},{status:"queued",released:false}]);});it("removes the admitted seat of a Bot that left the room, cancels its work, and queues the next seat",async()=>{const{subject,first,second,seats}=await opened();await subject.sync(VECTOR_NOW);await subject.change(state=>{state.team.rooms.r.members=["main"];});await subject.sync(VECTOR_NOW+1);expect(await seats()).toMatchObject([{status:"removed",released:true},{status:"queued",released:false}]);expect(await subject.cancelReason(first)).toBe("cancelled");expect((await subject.state()).turns[second]).toMatchObject({source:"room_slot",botId:"main"});});it("runs the room step again when a Turn step releases a seat, so the next seat gets its Turn in the same sync",async()=>{const{subject,round,seats}=await opened();await subject.change(state=>{state.team.rooms.r.messages[0].text="x".repeat(7e4);});await subject.sync(VECTOR_NOW);expect(await seats()).toMatchObject([{status:"blocked",released:true},{status:"blocked",released:true}]);expect((await subject.state()).team.rounds[round.id]).toMatchObject({closed:true});for(const[seatId,botId]of [[round.seats[0],"b"],[round.seats[1],"main"]]){expect(await subject.projection(`room-seat:r:${seatId}`)).toEqual([expect.objectContaining({root:round.id,seatId,botId,status:"blocked"})]);}expect(await subject.projection(`room-root:r:${round.id}`)).toEqual([{roomId:"r",root:round.id,seats:round.seats}]);});it("fails the unadmitted seat Turn of a Bot that left the room with cancelled",async()=>{const{subject,second,seats}=await opened();await subject.change(state=>{state.turns[second]={id:second,root:second,source:"room_slot",request:"{}",botId:"main",hop:0,authority:"bot",status:"queued"};state.team.rooms.r.members=["b"];});await subject.sync(VECTOR_NOW);expect((await seats())[1]).toMatchObject({status:"removed",released:true});expect((await subject.state()).turns[second]).toMatchObject({status:"failed",conclusion:"cancelled"});expect(await subject.intent(second)).toBeUndefined();});});}function deviceVectors(name,open){describe(`device observation contract: ${name}`,()=>{const{settled,commit,delegated}=settlementSteps(open);const offline=new Map([["device",false]]),online=new Map([["device",true]]);const opened=async()=>{const h=await delegated();const subject=h.subject;const projected=async()=>subject.projection(`delegation:${h.id}:${(await h.delegation()).revision}`);const unchanged=async devices=>{const before=await subject.stored();await subject.observeDevices(devices);expect(await subject.stored()).toBe(before);};return {...h,subject,projected,unchanged}};it("shows a delivered offer that no device claimed as waiting_device while its device is offline, and queued again once it connects",async()=>{const h=await opened();expect((await h.delegation()).status).toBe("queued");await h.subject.deliver(h.id,"offered");await h.subject.observeDevices(offline);expect((await h.delegation()).status).toBe("waiting_device");expect(await h.projected()).toEqual([expect.objectContaining({status:"waiting_device"})]);await h.unchanged(offline);await h.unchanged(new Map);await h.unchanged(new Map([["other",true]]));await h.subject.observeDevices(online);expect((await h.delegation()).status).toBe("queued");expect(await h.projected()).toEqual([expect.objectContaining({status:"queued"})]);});it("changes nothing before the offer is delivered: no submit, an uncertain submit, or a delivery with no attempt read",async()=>{const h=await opened();await h.unchanged(offline);await h.subject.submit(h.id);await h.unchanged(offline);await h.subject.deliver(h.id);await h.unchanged(offline);});it("changes nothing once a device claimed the offer, by its attempt or by the claim fact",async()=>{const h=await opened();await h.subject.deliver(h.id,"running");await h.unchanged(offline);await h.subject.deliver(h.id,"offered");await h.subject.claim(h.id);await settled(h.subject);expect((await h.delegation()).status).toBe("running");await h.unchanged(offline);});it("changes nothing for a delegation with a cancel or a verdict",async()=>{const cancelled=await opened();await cancelled.subject.deliver(cancelled.id,"offered");await commit(cancelled.subject,{kind:"cancel_delegation",delegationId:cancelled.id});expect((await cancelled.delegation()).cancel).toBeDefined();await cancelled.unchanged(offline);const failed=await opened();await failed.subject.deliver(failed.id,"offered");await failed.subject.observeDevices(offline);await failed.subject.conclude(failed.id,"failed");await settled(failed.subject);expect(await failed.delegation()).toMatchObject({verdict:"failed"});await failed.unchanged(online);});});}function cardCallVectors(name,open){describe(`card call contract: ${name}`,()=>{const result=hash(["action_result","c1"]);const opened=async()=>{const subject=await open();await subject.change(state=>{Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.cards.c1.expiresAt=VECTOR_NOW+6e4;});const decide=async decision=>{const done=await subject.commit({scope:subject.scope,commandId:`decide-${decision}`,command:{kind:"decide",cardId:"c1",decision}});expect(done.disposition).toEqual({outcome:"accepted"});await subject.sync(VECTOR_NOW);};const calls=[];const connector=value=>async(id,action,draft)=>{calls.push([id,action,draft]);if(value instanceof Error)throw value;return value};const unchanged=async step=>{const before=await subject.stored();await subject.callCards(step);expect(await subject.stored()).toBe(before);};return {subject,decide,calls,connector,unchanged}};it("calls the connector once for a confirmed card, writes its result, and the next sync reports it with its action_result Turn",async()=>{const h=await opened();await h.decide("confirmed");await h.subject.callCards(h.connector({sent:true}));expect(h.calls).toEqual([["c1","send_message",{text:"hi"}]]);expect((await h.subject.state()).cards.c1).toMatchObject({state:"confirmed",result:{sent:true},conclusion:"succeeded"});await h.unchanged(h.connector({sent:false}));expect(h.calls).toHaveLength(1);await h.subject.sync(VECTOR_NOW);expect(await h.subject.projection("card:c1:confirmed")).toEqual([expect.objectContaining({id:"c1",result:{sent:true}})]);expect((await h.subject.state()).turns[result]).toMatchObject({source:"action_result",request:JSON.stringify({cardId:"c1",state:"confirmed",conclusion:"succeeded",result:{sent:true}})});});it("writes a connector error, cut to 1024 characters, with a failed conclusion",async()=>{const h=await opened();await h.decide("confirmed");await h.subject.callCards(h.connector(new Error("x".repeat(2e3))));expect((await h.subject.state()).cards.c1).toMatchObject({error:"x".repeat(1024),conclusion:"failed"});expect((await h.subject.state()).cards.c1).not.toHaveProperty("result");await h.subject.sync(VECTOR_NOW);expect((await h.subject.state()).turns[result]).toMatchObject({source:"action_result",request:JSON.stringify({cardId:"c1",state:"confirmed",conclusion:"failed",error:"x".repeat(1024)})});});it("writes a result that is not JSON as an error",async()=>{const h=await opened();await h.decide("confirmed");await h.subject.callCards(h.connector(void 0));expect((await h.subject.state()).cards.c1).toMatchObject({error:expect.any(String),conclusion:"failed"});});it("calls nothing for a pending or a rejected card",async()=>{const h=await opened();await h.unchanged(h.connector({sent:true}));await h.decide("rejected");await h.unchanged(h.connector({sent:true}));expect(h.calls).toEqual([]);});});}function homeVectors(name,open){describe(`Agent home flush contract: ${name}`,()=>{const HOUR=36e5;const pendingBot=(state,bot)=>{state.team.bots[bot]={...state.team.bots.main,id:bot,name:bot,mainBot:false,revision:"2",readyRevision:"1",execution:template("device",bot)};const sequence=++state.sequence;state.team.homeOperations.push({sequence,botId:bot,status:"pending",retries:[],request:{deviceId:"device",payload:{requestId:projectionRequestId([bot,"2"]),agentRef:{agentId:bot,profileRevision:"2"},projectionHash:`sha256:${bot}`,projection:{schemaVersion:"bot-profile.v1",name:bot,role:"Member",persona:"",model:"default"}}}});return sequence};const opened=async()=>{const subject=await open();const sequences={};await subject.change(state=>{Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});for(const bot of ["b","c"])sequences[bot]=pendingBot(state,bot);});const operation=async(bot,index=0)=>(await subject.state()).team.homeOperations.filter(op=>op.botId===bot)[index];const reads=[],enqueued=[];const calls=(answer=()=>void 0)=>({read:async request=>{reads.push(request.payload.requestId);const value=answer(request);if(value instanceof Error)throw value;return value},enqueue:async request=>{enqueued.push(request.payload.requestId);}});const readback=(request,status)=>({deviceId:request.deviceId,agentRef:request.payload.agentRef,requestId:request.payload.requestId,projectionHash:request.payload.projectionHash,status});return {subject,sequences,operation,reads,enqueued,calls,readback}};for(const status of ["applied","idempotent"]){it(`applies an operation whose readback is ${status}, readies its Bot at that revision, and reads it no more`,async()=>{const h=await opened();await h.subject.flushHomes(VECTOR_NOW,h.calls(request=>h.readback(request,status)));expect(await h.operation("b")).toMatchObject({status:"applied"});expect((await h.subject.state()).team.bots.b).toMatchObject({revision:"2",readyRevision:"2"});expect(h.enqueued).toEqual([]);const reads=h.reads.length,before=await h.subject.stored();await h.subject.flushHomes(VECTOR_NOW+HOUR,h.calls(request=>h.readback(request,status)));expect(h.reads).toHaveLength(reads);expect(await h.subject.stored()).toBe(before);});}it("fails an operation whose readback is terminal and not applied, and publishes persona-failed",async()=>{const h=await opened();await h.subject.flushHomes(VECTOR_NOW,h.calls(request=>h.readback(request,"conflict")));expect(await h.operation("b")).toMatchObject({status:"failed",error:"conflict"});expect((await h.subject.state()).team.bots.b).toMatchObject({readyRevision:"1"});expect(await h.subject.projection(`persona-failed:${h.sequences.b}`)).toEqual([{owner:"b",revision:"2",reason:"conflict",recoverable:true}]);});it("keeps an operation pending with the error when a readback is for another request, and enqueues nothing",async()=>{const h=await opened();await h.subject.flushHomes(VECTOR_NOW,h.calls(request=>({...h.readback(request,"applied"),projectionHash:"sha256:other"})));expect(await h.operation("b")).toMatchObject({status:"pending",error:"Home readback identity conflict"});expect(h.enqueued).toEqual([]);});it("enqueues the first request with no terminal, then once retryAt has passed a retry with the next request id and a backoff",async()=>{const h=await opened();const first=(await h.operation("b")).request.payload.requestId;await h.subject.flushHomes(VECTOR_NOW,h.calls());expect(h.enqueued).toContain(first);expect(await h.operation("b")).toMatchObject({status:"pending",retries:[],retryAt:VECTOR_NOW+1e3});h.reads.length=0;h.enqueued.length=0;await h.subject.flushHomes(VECTOR_NOW+1e3,h.calls());const retry=projectionRequestId([first,1]);expect(await h.operation("b")).toMatchObject({retries:[{payload:{requestId:retry}}],retryAt:VECTOR_NOW+3e3});expect(h.reads.filter(id=>id===first||id===retry)).toEqual([first]);expect(h.enqueued.filter(id=>id===first||id===retry)).toEqual([retry]);await h.subject.flushHomes(VECTOR_NOW+HOUR,h.calls(request=>request.payload.requestId===first?h.readback(request,"applied"):void 0));expect(await h.operation("b")).toMatchObject({status:"applied"});});it("keeps an operation pending with the error when a read throws",async()=>{const h=await opened();await h.subject.flushHomes(VECTOR_NOW,h.calls(()=>new Error("home read down")));expect(await h.operation("b")).toMatchObject({status:"pending",error:"home read down"});});it("waits while a Bot has an intent with no conclusion, without blocking another Bot, and flushes it after the intent concludes",async()=>{const h=await opened();await h.subject.change(state=>{state.team.bots.b.readyRevision="2";});const turn=await h.subject.commit({scope:h.subject.scope,commandId:"busy-b",command:{kind:"input",botId:"b",key:"busy",request:"Work",sender:"owner"}});const turnId=turn.disposition.value;await h.subject.sync();expect(await h.subject.intent(turnId)).toBeDefined();await h.subject.flushHomes(VECTOR_NOW,h.calls(request=>h.readback(request,"applied")));expect(await h.operation("b")).toMatchObject({status:"pending"});expect(await h.operation("c")).toMatchObject({status:"applied"});expect(h.reads.filter(id=>id===projectionRequestId(["b","2"]))).toEqual([]);await h.subject.concludeIntent(turnId,"succeeded");await h.subject.flushHomes(VECTOR_NOW+HOUR,h.calls(request=>h.readback(request,"applied")));expect(await h.operation("b")).toMatchObject({status:"applied"});});it("reads no later operation of a Bot while its oldest pending one is not settled, and flushes it once that one settles",async()=>{const h=await opened();const second=projectionRequestId(["b","3"]);await h.subject.change(state=>{pendingBot(state,"b");state.team.homeOperations.at(-1).request.payload.requestId=second;});const first=(await h.operation("b",0)).request.payload.requestId;await h.subject.flushHomes(VECTOR_NOW,h.calls(request=>request.payload.requestId===second?h.readback(request,"applied"):void 0));expect(await h.operation("b",0)).toMatchObject({status:"pending"});expect(await h.operation("b",1)).toMatchObject({status:"pending"});expect(h.reads).not.toContain(second);await h.subject.flushHomes(VECTOR_NOW+HOUR,h.calls(request=>request.payload.requestId===first||request.payload.requestId===second?h.readback(request,"applied"):void 0));expect(await h.operation("b",0)).toMatchObject({status:"applied"});await h.subject.flushHomes(VECTOR_NOW+2*HOUR,h.calls(request=>h.readback(request,"applied")));expect(await h.operation("b",1)).toMatchObject({status:"applied"});});});}var FINAL_BODY="Final answer";var replyToken=key=>`secret-${key}`;var DIRECT={kind:"direct",id:"main"};var accepted=platformMessageId=>({result:"accepted",platformMessageId});function scripted(...results){const calls=[];const send=async input3=>{calls.push(structuredClone(input3));const result=results[Math.min(calls.length,results.length)-1];if(result==="hang")return new Promise(()=>{});if(result instanceof Error)throw result;return result};return {calls,send}}function deliveryVectors(name,open){describe(`delivery contract: ${name}`,()=>{it("1. sends a reply-route delivery once, with the token only in the route, and settles it accepted",async()=>{const port=scripted(accepted("p1")),subject=await open(port);await subject.publish("in1");await subject.drain();const[row]=await subject.deliveries();expect(row).toMatchObject({body:FINAL_BODY,channel:"fake",conversation:DIRECT,route:{kind:"reply",inboundId:inboundKey({channel:"fake",conversation:DIRECT,platformMessageId:"in1"})},state:"accepted",attempts:1,platformMessageId:"p1"});expect(port.calls).toEqual([{deliveryId:row.id,body:FINAL_BODY,route:{kind:"reply",channel:"fake",inboundId:"in1",token:replyToken("in1"),expiresAt:expect.any(Number)}}]);},6e4);it("2. backs a retryable rejection off by its wait, and the third attempt stops",async()=>{const port=scripted({result:"rejected",code:"429",retryable:true,retryAfterMs:5e3}),subject=await open(port);await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"pending",attempts:1,code:"429",nextAttemptAt:subject.now()+5e3}]);await subject.advance(4999);expect(port.calls).toHaveLength(1);await subject.advance(1);expect(port.calls).toHaveLength(2);await subject.advance(5e3);expect(port.calls).toHaveLength(3);expect(await subject.deliveries()).toMatchObject([{state:"rejected",attempts:3,code:"429"}]);await subject.advance(6e4);expect(port.calls).toHaveLength(3);},6e4);it("3. stops at a rejection that is not retryable",async()=>{const port=scripted({result:"rejected",code:"permission_denied",retryable:false}),subject=await open(port);await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"rejected",attempts:1,code:"permission_denied"}]);await subject.advance(12e4);expect(port.calls).toHaveLength(1);},6e4);it("4. rejects a retryable rejection whose wait is over 60 s",async()=>{const port=scripted({result:"rejected",code:"429",retryable:true,retryAfterMs:60001}),subject=await open(port);await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"rejected",attempts:1,code:"429"}]);await subject.advance(12e4);expect(port.calls).toHaveLength(1);},6e4);it.each([["send_timeout","hang"],["send_failed",new Error("connection lost after write")]])("5. leaves a send that ends in %s unknown, and never sends it again by itself",async(code,outcome)=>{const port=scripted(outcome),subject=await open(port);await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"unknown",attempts:1,code}]);await subject.advance(12e4);expect(port.calls).toHaveLength(1);},6e4);it.each(["accepted","absent"])("6. settles an unknown delivery from a readback of %s",async result=>{const port=scripted(new Error("receipt lost"),accepted("p2")),read=[];const subject=await open({send:port.send,readback:async id=>{read.push(id);return result}});await subject.publish("in1");await subject.drain();const[row]=await subject.deliveries();expect(read).toContain(row.id);expect(row).toMatchObject(result==="accepted"?{state:"accepted",attempts:1}:{state:"pending",attempts:1,nextAttemptAt:subject.now()+1e3});await subject.advance(1e3);expect(port.calls).toHaveLength(result==="absent"?2:1);expect(await subject.deliveries()).toMatchObject([{state:"accepted",attempts:result==="absent"?2:1}]);},6e4);it("7. turns a send claim that its Host never settled into unknown (interrupted), and sends it no more",async()=>{const port=scripted(accepted("late")),subject=await open(port);subject.crashOnNextSend();await subject.publish("in1");await subject.advance(subject.recoveryMs);expect(await subject.deliveries()).toMatchObject([{state:"unknown",attempts:1,code:"interrupted"}]);await subject.advance(12e4);expect(port.calls).toHaveLength(1);},6e4);it("8. refuses a pending reply after its route expired, and sends the push fallback",async()=>{const port=scripted({result:"rejected",code:"503",retryable:true,retryAfterMs:2e4},accepted("pushed"));const subject=await open(port),push=await subject.enablePush("direct-target");await subject.publish("in1",{replyMs:1e4});expect(port.calls.map(call=>call.route.kind)).toEqual(["reply"]);await subject.advance(2e4);await subject.drain();const rows=await subject.deliveries();expect(rows).toMatchObject([{route:{kind:"reply"},state:"rejected",attempts:1,code:"reply_route_expired"},{route:{kind:"push",pushRouteId:push},body:FINAL_BODY,state:"accepted",attempts:1,platformMessageId:"pushed"}]);expect(port.calls.map(call=>call.route.kind)).toEqual(["reply","push"]);expect(port.calls[1]).toMatchObject({deliveryId:rows[1].id,route:{kind:"push",id:push,target:"direct-target"}});},6e4);it("9. rejects the pending deliveries of a revoked push route",async()=>{const port=scripted({result:"rejected",code:"503",retryable:true,retryAfterMs:2e4});const subject=await open(port),push=await subject.enablePush("direct-target");await subject.publish("in1",{replyMs:null});expect(await subject.deliveries()).toMatchObject([{route:{kind:"push",pushRouteId:push},state:"pending",attempts:1}]);await subject.revokePush(push);expect(await subject.deliveries()).toMatchObject([{state:"rejected",attempts:1,code:"push_route_revoked"}]);await subject.advance(6e4);expect(port.calls).toHaveLength(1);},6e4);it("10. accepts an unknown delivery from a verified echo",async()=>{const port=scripted(new Error("receipt lost")),subject=await open(port);await subject.publish("in1");const[row]=await subject.deliveries();expect(row).toMatchObject({state:"unknown",attempts:1});await subject.echo(row.id,"echoed");expect(await subject.deliveries()).toMatchObject([{id:row.id,state:"accepted",attempts:1,platformMessageId:"echoed"}]);await subject.advance(12e4);expect(port.calls).toHaveLength(1);},6e4);it("11. gives a manual resend of an unknown delivery a new id, and sends it",async()=>{const port=scripted(new Error("receipt lost"),accepted("again")),reads=[];let absent=false;const subject=await open({send:port.send,readback:async id=>{reads.push(id);return absent?"absent":"unsupported"}});await subject.enablePush("direct-target");await subject.publish("in1",{replyMs:null});const[old]=await subject.deliveries();absent=true;const held=subject.holdNextReadback();await subject.advance(6e4);absent=false;await subject.advance(subject.recoveryMs);const next=await subject.resend(old.id);expect(next).not.toBe(old.id);const readCount=reads.length;await held.release();await subject.advance(6e4);await subject.advance(1e3);expect(await subject.deliveries()).toMatchObject([{id:old.id,state:"unknown",attempts:1},{id:next,resendOf:old.id,state:"accepted",attempts:1,platformMessageId:"again"}]);expect(port.calls.map(call=>call.deliveryId)).toEqual([old.id,next]);expect(reads).toHaveLength(readCount);},6e4);it("12. drops the stored reply token once its route expires",async()=>{const port=scripted({result:"rejected",code:"503",retryable:true,retryAfterMs:2e4}),subject=await open(port);await subject.publish("in1",{replyMs:1e4});expect(await subject.stored()).toContain(replyToken("in1"));await subject.advance(1e4);const inbound=Object.values((await subject.state()).channel.inbounds)[0];expect(inbound.reply).toBeDefined();expect(inbound.reply.token).toBeUndefined();expect(await subject.stored()).not.toContain(replyToken("in1"));},6e4);it("13. keeps the reply token out of every projection and every channel call field except the send route",async()=>{const port=scripted(new Error("receipt lost"),accepted("again")),read=[];const subject=await open({send:port.send,readback:async id=>{read.push(id);return "absent"}});await subject.publish("in1");await subject.drain();await subject.advance(1e3);expect(port.calls).toHaveLength(2);for(const call of port.calls){expect(call.route).toMatchObject({kind:"reply",token:replyToken("in1")});expect(JSON.stringify({...call,route:void 0})).not.toContain(replyToken("in1"));}expect(JSON.stringify(read)).not.toContain(replyToken("in1"));const projections=await subject.projections();expect(projections.length).toBeGreaterThan(0);expect(JSON.stringify(projections)).not.toContain(replyToken("in1"));},6e4);it("14. accepts a delivery from a verified echo that arrives while its send is held, and keeps the echo",async()=>{const port=scripted(accepted("sent")),subject=await open(port);const held=subject.holdNextSend();await subject.publish("in1");const[row]=await subject.deliveries();expect(row).toMatchObject({state:"sending",attempts:1});await subject.echo(row.id,"echoed");expect(await subject.deliveries()).toMatchObject([{id:row.id,state:"accepted",attempts:1,platformMessageId:"echoed"}]);await held.release();expect(await subject.deliveries()).toMatchObject([{id:row.id,state:"accepted",attempts:1,platformMessageId:"echoed"}]);expect(port.calls).toHaveLength(1);},6e4);it("15. ignores a held send that completes after another Host recovered its claim",async()=>{const port=scripted(accepted("late")),subject=await open(port);const held=subject.holdNextSend();await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"sending",attempts:1}]);await subject.advance(subject.recoveryMs);expect(await subject.deliveries()).toMatchObject([{state:"unknown",attempts:1,code:"interrupted"}]);await held.release();const[row]=await subject.deliveries();expect(row).toMatchObject({state:"unknown",attempts:1,code:"interrupted"});expect(row.platformMessageId).toBeUndefined();await subject.advance(12e4);expect(port.calls).toHaveLength(1);},6e4);it("16. drops the stored reply token once the delivery of its closed root settles",async()=>{const port=scripted(accepted("p1")),subject=await open(port);const held=subject.holdNextSend();await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"sending"}]);expect(await subject.stored()).toContain(replyToken("in1"));await held.release();expect(await subject.deliveries()).toMatchObject([{state:"accepted"}]);const inbound=Object.values((await subject.state()).channel.inbounds)[0];expect(inbound.reply).toMatchObject({inboundId:"in1"});expect(inbound.reply.token).toBeUndefined();expect(await subject.stored()).not.toContain(replyToken("in1"));},6e4);it("17. rejects an uncertain delivery whose readback is absent after its third attempt (attempts_exhausted)",async()=>{const port=scripted(new Error("receipt lost"));const subject=await open({send:port.send,readback:async()=>"absent"});await subject.publish("in1");await subject.drain();expect(await subject.deliveries()).toMatchObject([{state:"pending",attempts:1,nextAttemptAt:subject.now()+1e3}]);await subject.advance(1e3);await subject.drain();expect(await subject.deliveries()).toMatchObject([{state:"pending",attempts:2,nextAttemptAt:subject.now()+2e3}]);await subject.advance(2e3);await subject.drain();expect(await subject.deliveries()).toMatchObject([{state:"rejected",attempts:3,code:"attempts_exhausted"}]);await subject.advance(6e4);expect(port.calls).toHaveLength(3);},6e4);it("18. ignores a readback result for an earlier attempt that arrives after a later attempt went unknown",async()=>{const port=scripted(new Error("receipt lost"));let found="unsupported";const subject=await open({send:port.send,readback:async()=>found});await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"unknown",attempts:1}]);found="absent";const held=subject.holdNextReadback();await subject.advance(6e4);await subject.advance(6e4);expect(await subject.deliveries()).toMatchObject([{state:"pending",attempts:1}]);found="unsupported";await subject.advance(1e3);expect(await subject.deliveries()).toMatchObject([{state:"unknown",attempts:2}]);await held.release();const[row]=await subject.deliveries();expect(row).toMatchObject({state:"unknown",attempts:2});expect(row.nextAttemptAt).toBeUndefined();await subject.advance(6e4);expect(port.calls).toHaveLength(2);},6e4);it("19. ignores a held send of attempt 1 that completes while attempt 2 is sending",async()=>{const port=scripted(accepted("late"),accepted("p2"));const subject=await open({send:port.send,readback:async()=>"absent"});const first=subject.holdNextSend();await subject.publish("in1");await subject.advance(subject.recoveryMs);expect(await subject.deliveries()).toMatchObject([{state:"pending",attempts:1}]);const second=subject.holdNextSend();await subject.advance(1e3);expect(await subject.deliveries()).toMatchObject([{state:"sending",attempts:2}]);await first.release();const[row]=await subject.deliveries();expect(row).toMatchObject({state:"sending",attempts:2});expect(row.platformMessageId).toBeUndefined();await second.release();expect(await subject.deliveries()).toMatchObject([{state:"accepted",attempts:2,platformMessageId:"p2"}]);expect(port.calls).toHaveLength(2);},6e4);});}async function submitResult(input3,outcome,signal){const server=input3.mcpServers?.byokagentresult;if(!server)throw new Error("result-document fixture did not receive byokagentresult");signal.throwIfAborted();const child=spawn(server.command,[...server.args??[]],{env:{...process.env,...server.env},stdio:["pipe","pipe","pipe"]});const lines=createInterface({input:child.stdout});let nextId=0;const pending=new Map;const ended=new Promise(resolve=>child.once("close",()=>resolve()));const abort=()=>{for(const request2 of pending.values())request2.reject(new Error("result helper closed"));pending.clear();};signal.addEventListener("abort",abort,{once:true});child.on("error",error=>{for(const request2 of pending.values())request2.reject(error);pending.clear();});child.on("exit",()=>{for(const request2 of pending.values())request2.reject(new Error("result helper exited before response"));pending.clear();});child.stderr.resume();lines.on("line",line=>{const response=JSON.parse(line);if(response.id===void 0)return;const request2=pending.get(response.id);if(!request2)return;pending.delete(response.id);if(response.error)request2.reject(new Error(response.error.message));else request2.resolve(response.result);});const request=(method,params)=>new Promise((resolve,reject)=>{signal.throwIfAborted();const id=++nextId;pending.set(id,{resolve,reject});child.stdin.write(JSON.stringify({jsonrpc:"2.0",id,method,params})+"\n");});try{await request("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"example-stub",version:"1"}});child.stdin.write(JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})+"\n");return await request("tools/call",{name:"submit_result",arguments:outcome})}finally{signal.removeEventListener("abort",abort);lines.close();try{child.kill("SIGKILL");}catch{}await ended;}}var ResultStubSession=class{constructor(input3){this.input=input3;}input;sessionRef=randomUUID();interrupted=false;closed=false;steered=0;followedUp=0;resultAbort=new AbortController;finishing=new Set;closing;pending=[];failure;wake;events={[Symbol.asyncIterator]:async function*(){while(!this.closed){if(this.failure)throw this.failure;const next=this.pending.shift();if(next){yield next;continue}await new Promise(resolve=>{this.wake=resolve;});}}.bind(this)};emit(event){this.pending.push(event);this.wake?.();this.wake=void 0;}finish(document,submit=true,text=JSON.stringify(document)){if(this.closed)return Promise.resolve();const finishing=(async()=>{if(submit&&this.input.mcpServers?.byokagentresult)await submitResult(this.input,document,this.resultAbort.signal);if(this.closed)return;this.emit({type:"progress",text});this.emit({type:"turn_end"});})().catch(error=>{if(!this.closed){this.failure=error;this.wake?.();this.wake=void 0;}}).finally(()=>{this.finishing.delete(finishing);});this.finishing.add(finishing);return finishing}fail(){this.failure=new Error("stub failed");this.wake?.();this.wake=void 0;}async steer(){this.steered+=1;}async followUp(){this.followedUp+=1;}async interrupt(){this.interrupted=true;}evidence(){return {decodeDropped:0,unmappedFrames:0,syntheticToolResults:0}}close(){if(this.closing)return this.closing;this.closed=true;this.wake?.();this.wake=void 0;this.resultAbort.abort();let timer;this.closing=Promise.race([Promise.all([...this.finishing]).then(()=>{}),new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new RuntimeDisposalFailure({stage:"quiescence",reason:"result helper did not close"})),1e3);})]).finally(()=>{clearTimeout(timer);this.closing=void 0;});return this.closing}};var ResultStubAdapter=class{descriptor=freezeRuntimeAdapterDescriptor({id:"pi",supportsDispatchSelection:true,requiresMcpToolsetToolObservation:true,capabilities:{steer:false,resume:false,mcpToolsets:true,approvalInteractive:false}});sessions=new Map;starts=[];rejectNext=false;runtimeEnvironment(){return buildRuntimeEnvironment({base:"allowlist"})}async detect(){return {kind:"available",version:"0.0.0"}}async prepare(_input){if(this.rejectNext){this.rejectNext=false;return {kind:"reject",reason:"stub declined",retryable:true}}return {kind:"prepared",operation:{start:async input3=>{const session=new ResultStubSession(input3);this.starts.push(input3);this.sessions.set(input3.manifest.taskId,session);return session}}}}};async function waitForReady(daemon,timeoutMs=5e3){const deadline=Date.now()+timeoutMs;for(;;){const{lifecycle}=daemon.status();if(lifecycle.phase==="running"&&lifecycle.connection==="open")return;if(Date.now()>=deadline)throw new Error(`daemon not ready within ${timeoutMs} ms: ${JSON.stringify(lifecycle)}`);await new Promise(resolve=>setTimeout(resolve,25));}}async function openLTestHost(options){const deviceCredentials=options.deviceCredentials;if(deviceCredentials===void 0)throw new TypeError("openLTestHost requires deviceCredentials");const root=await mkdtemp(path.join(tmpdir(),"lth-"));const productId="host-core-test";const ledgerPath=path.join(root,"host.sqlite");const ledger=new HostLedger(ledgerPath,`product:${productId}`,options.ledgerOptions);const server=createByokServer({productId,storage:{kind:"sqlite",path:path.join(root,"server.sqlite")},longPollHoldMs:100,agentMessage:options.agentMessage,wake:{consume:options.consume}});const http=serve({fetch:server.hono.fetch,port:0,hostname:"127.0.0.1"});if(!http.listening)await new Promise(resolve=>http.once("listening",resolve));const address=http.address();if(!address||typeof address==="string")throw new Error("Missing HTTP address");const adapter=options.adapter??new ResultStubAdapter;const config={productId,productName:"Host Core",localAgentRelease:{version:"0.0.0-test"},serverUrl:`http://127.0.0.1:${address.port}`,storeDir:path.join(root,"sdk"),agentHome:{hostStorageRoot:path.join(root,"homes")},agentEgress:{policy}};const daemon=createDaemonWithAdapters(config,[adapter],{deviceCredentials});const pairing=await server.pairing.createPairingCode({productId});const{deviceId}=await daemon.pair(pairing.code);await daemon.start();await waitForReady(daemon);let closed=false;return {root,ledgerPath,server,ledger,deviceId,adapter,async close(){if(closed)return;closed=true;await daemon.stop();await server.close();ledger.close();await new Promise((resolve,reject)=>{http.close(error=>error?reject(error):resolve());if("closeAllConnections"in http)http.closeAllConnections();});await rm(root,{recursive:true,force:true});}}}var RETENTION_NOW=1e4;var LIMITS={contextTurnLimit:1,handoff:{recentBytes:200,earlyBytes:0,totalBytes:1024}};var input2=key=>({kind:"input",botId:"main",key,request:"Hello",sender:"owner"});function settledRoot(state,id){state.turns[id]={id,root:id,botId:"main",source:"user",request:id,hop:0,status:"succeeded",conclusion:"succeeded",reported:true,authority:"owner"};state.budgets[id]={continuation:0,delegation:0};state.questions[`${id}:q`]={id:`${id}:q`,turnId:id,value:{question:"Go?",answerKind:"text"},answer:"yes"};state.cards[`${id}:c`]={id:`${id}:c`,turnId:id,action:{action:"send_message",summary:"Send",draft:{text:"hi"}},state:"expired",expiresAt:0,decisionReported:true};state.rejected.push({botId:"main",taskId:`${id}:task`,action:"delegate",reason:"hop_limit",consumedBy:id});(state.wouldDo??={})[`${id}:w`]=wouldDo(`${id}:w`,id,"create_routine");}var wouldDo=(id,turnId,action)=>({id,botId:"main",turnId,taskId:`${turnId}:task`,action,index:0,at:0,detail:null});function clearSeed(state){delete state.turns.t1;delete state.budgets.t1;delete state.schemas.t1;delete state.questions.q1;delete state.cards.c1;}var settle2=async work=>work();var delegation=()=>({id:"d",root:"r1",fromBotId:"main",fromTurnId:"r1",fromTaskId:"r1:task",index:0,toBotId:"main",request:"",hop:1,chainTurnIds:[],batch:"b",status:"running",revision:0});var inputBatch=state=>({id:"r1",botId:"main",key:"k",inputIds:[],bytes:0,openedAt:0,sealAt:0,state,revision:2});function room(state,round,seat){state.team.rooms.room={id:"room",name:"Room",members:["main"],visibleFrom:{main:0},mode:"mention",announcement:"",messages:[]};state.team.rounds.round={id:"round",root:"r1",roomId:"room",input:"{}",seats:["seat"],limit:5,counts:{main:1},...round};state.team.seats.seat={id:"seat",roundId:"round",botId:"main",status:"post",late:false,...seat};}function delivery(state,row){state.replies["r1:task"]={turnId:"r1",messageId:"m",contentHash:"h",contentType:"text/markdown",acceptedAt:0};state.channel={inbounds:{},pushRoutes:{},deliveries:{x:{id:"x",taskId:"r1:task",turnId:"r1",messageId:"m",body:"b",conversation:{kind:"direct",id:"main"},channel:"fake",route:{kind:"push",pushRouteId:"p"},state:row,attempts:0}}};}function retentionVectors(name,open){describe(`retention contract: ${name}`,()=>{const request=(subject,commandId,command)=>({scope:subject.scope,commandId,command});const retain=(subject,roots,fields={},limits=LIMITS)=>settle2(()=>subject.retain({acknowledgedRoots:roots,now:RETENTION_NOW,retentionMs:MIN_TOMBSTONE_RETENTION_MS,...fields},limits));const refused=async(subject,run,check)=>{const before=await subject.stored();let error;try{await run();}catch(cause){error=cause;}check(error);expect(await subject.stored()).toBe(before);};const opened=async()=>{const subject=await open();await subject.change(state=>{clearSeed(state);settledRoot(state,"r1");settledRoot(state,"r2");});return subject};it("moves a settled root out of the state and counts a repeated root harmlessly",async()=>{const subject=await opened();const result=await retain(subject,["r1"]);expect(result).toMatchObject({archivedRoots:1,alreadyArchivedRoots:0});expect(result.archivedRows).toBeGreaterThanOrEqual(5);expect(result.afterBytes).toBeLessThan(result.beforeBytes);const state=await subject.state();expect(state.turns.r1).toBeUndefined();expect(state.budgets.r1).toBeUndefined();expect(state.questions["r1:q"]).toBeUndefined();expect(state.cards["r1:c"]).toBeUndefined();expect(state.rejected.map(row=>row.consumedBy)).toEqual(["r2"]);expect(Object.keys(state.wouldDo??{})).toEqual(["r2:w"]);expect(await subject.archived("wouldDo","r1:w")).toMatchObject({turnId:"r1"});expect(state.turns.r2).toBeDefined();expect(await retain(subject,["r1"])).toMatchObject({archivedRoots:0,alreadyArchivedRoots:1});});it("archives a replaced unknown delivery with its settled root",async()=>{const subject=await opened();await subject.change(state=>{delivery(state,"unknown");const old=state.channel.deliveries.x;state.channel.deliveries.replacement={...old,id:"replacement",state:"accepted",resendOf:old.id};});expect(await retain(subject,["r1"])).toMatchObject({archivedRoots:1});expect((await subject.state()).channel?.deliveries).toEqual({});expect(await subject.archived("deliveries","x")).toMatchObject({state:"unknown"});expect(await subject.archived("deliveries","replacement")).toMatchObject({state:"accepted",resendOf:"x"});});it("refuses a short retention, an unknown root and a room seat, and changes nothing",async()=>{const subject=await opened();await refused(subject,()=>retain(subject,["r1"],{retentionMs:MIN_TOMBSTONE_RETENTION_MS-1}),error=>expect(error.message).toBe("Retention must be at least seven days"));await refused(subject,()=>retain(subject,["r1","missing"]),error=>expect(error.message).toBe("Acknowledged root not found"));await subject.change(state=>{state.team.rooms.room={id:"room",name:"Room",members:["main"],visibleFrom:{main:0},mode:"mention",announcement:"",messages:[]};state.team.rounds.round={id:"round",root:"round",roomId:"room",input:"{}",seats:["seat"],limit:5,counts:{main:1},closed:true};state.team.seats.seat={id:"seat",roundId:"round",botId:"main",status:"post",released:true,late:false};});await refused(subject,()=>retain(subject,["seat"]),error=>{expect(error).toBeInstanceOf(RetentionRefused);expect(error).toMatchObject({code:"seat_root",root:"seat",roundRoot:"round",message:"Retention refused: The Turn is a room seat of root round"});});await subject.change(state=>{delete state.wouldDo["r1:w"].turnId;});await refused(subject,()=>retain(subject,["r2"]),error=>expect(error).toMatchObject({code:"would_do_unsupported_old"}));});it("refuses each root that is still in use, and changes nothing",async()=>{const cases=[["an open Turn",state=>{state.turns.r1.status="processing";delete state.turns.r1.conclusion;},"A Turn of the root is not concluded"],["an open question",state=>{delete state.questions["r1:q"].answer;},"A question of the root is unanswered"],["a pending card",state=>{state.cards["r1:c"].state="pending";},"A card of the root is not settled"],["an unreported card",state=>{delete state.cards["r1:c"].decisionReported;},"A card of the root is not settled"],["a delegation without a verdict",state=>{state.delegations.d=delegation();},"A delegation of the root is unresolved"],["a reserved unit",state=>{state.units.u={id:"u",root:"r1",state:"reserved"};},"A budget unit of the root is reserved"],["a late chain Turn",state=>{state.delegations.d={...delegation(),verdict:"answered",status:"resolved",lateTurnId:"late"};},"A delegation of the root is unresolved"],["an undelivered cancel",state=>{state.delegations.d={...delegation(),verdict:"cancelled",status:"resolved",cancel:{requestedAt:0,targetTurnId:"r1",delivered:false}};},"A delegation of the root is unresolved"],["an unreleased delegation batch",state=>{state.delegations.d={...delegation(),verdict:"answered",status:"resolved"};state.batches.b={id:"b",delegationIds:["d"],slots:[]};},"A delegation batch of the root is not released"],["an open input batch",state=>{state.inputBatches={r1:inputBatch("open")};},"The input batch of the root is not settled"],["an unprojected input batch",state=>{state.inputBatches={r1:{...inputBatch("sealed"),revision:1}};},"The input batch of the root is not settled"],["an open round",state=>{room(state,{closed:false},{released:true});},"A round of the root is open"],["an unreleased seat",state=>{room(state,{closed:true},{released:false});},"A room seat of the root is not released"],["a pending delivery",state=>{delivery(state,"pending");},"A delivery of the root is not settled"],["an unknown delivery",state=>{delivery(state,"unknown");},"A delivery of the root is not settled"],["a live reply route",state=>{state.channel={pushRoutes:{},deliveries:{},inbounds:{i:{id:"i",root:"r1",conversation:{kind:"direct",id:"main"},channel:"fake",sequence:1,reply:{kind:"reply",channel:"fake",inboundId:"i",token:"secret",expiresAt:RETENTION_NOW+1}}}};},"An inbound reply route of the root is live"],["the newest card",state=>{state.cards["r1:c2"]={...state.cards["r1:c"],id:"r1:c2"};},"The root is in the ContextPack window of its Bot"],["the newest question",state=>{state.questions["r1:q2"]={...state.questions["r1:q"],id:"r1:q2"};},"The root is in the ContextPack window of its Bot"],["the ContextPack window",()=>{},"The root is in the ContextPack window of its Bot",{...LIMITS,contextTurnLimit:2}],["a Turn older than the Turn limit but still in the pack",()=>{},"The root is in the ContextPack window of its Bot",{contextTurnLimit:1,handoff:{recentBytes:4096,earlyBytes:0,totalBytes:8192}}]];for(const[label,edit,reason,limits]of cases){const subject2=await opened();await subject2.change(edit);await refused(subject2,()=>retain(subject2,["r1"],{},limits??LIMITS),error=>{expect(error,label).toBeInstanceOf(RetentionRefused);expect(error.message,label).toBe(`Retention refused: ${reason}`);expect(error.code,label).toBe("protected_root");});}const subject=await opened();await refused(subject,()=>retain(subject,["r2"]),error=>expect(error.message).toBe("Retention refused: The root is in the ContextPack window of its Bot"));});it("keeps a seat speech delivery with its round root, though it has no reply record",async()=>{const subject=await opened();await subject.change(state2=>{room(state2,{closed:true},{released:true});state2.turns.seat={...state2.turns.r1,id:"seat",root:"seat",source:"room_slot"};state2.channel={inbounds:{},pushRoutes:{},deliveries:{s:{id:"s",taskId:"seat:task",turnId:"seat",messageId:"speech:seat",body:"b",conversation:{kind:"direct",id:"main"},channel:"fake",route:{kind:"push",pushRouteId:"p"},state:"pending",attempts:0}}};settledRoot(state2,"r3");state2.wouldDo["seat:w"]=wouldDo("seat:w","seat","room_call");});await refused(subject,()=>retain(subject,["r1"]),error=>expect(error.message).toBe("Retention refused: A delivery of the root is not settled"));await subject.change(state2=>{state2.channel.deliveries.s.state="accepted";});expect(await retain(subject,["r1"])).toMatchObject({archivedRoots:1});const state=await subject.state();expect(state.turns.seat).toBeUndefined();expect(state.channel.deliveries.s).toBeUndefined();expect(Object.keys(state.wouldDo??{}).sort()).toEqual(["r2:w","r3:w"]);});it("moves the room messages of archived roots outside the window, and keeps what each member sees",async()=>{const limits={...LIMITS,contextTurnLimit:2};const message=id=>({id,from:"main",text:id,late:false});const subject=await opened();await subject.change(state2=>{settledRoot(state2,"r3");room(state2,{closed:true},{released:true});Object.assign(state2.team.rooms.room,{members:["main","b"],visibleFrom:{main:1,b:4},messages:["old","round","live","seat","old2","old3"].map(message)});state2.team.rounds.live={id:"live",root:"live",roomId:"room",input:"{}",seats:["live:seat"],limit:5,counts:{main:1},closed:false};state2.team.seats["live:seat"]={id:"live:seat",roundId:"live",botId:"main",status:"queued",released:false,late:false};});const seen=state2=>{const{historyWindow:_window,...context}=roomContext(state2.team,{id:"live:seat"},limits.contextTurnLimit);return context};const before=seen(await subject.state());expect(await retain(subject,["r1"],{},limits)).toMatchObject({archivedRoots:1});const state=await subject.state();expect(state.team.rooms.room.messages.map(row=>row.id)).toEqual(["live","old2","old3"]);expect(state.team.rooms.room.visibleFrom).toEqual({main:0,b:1});expect(seen(state)).toEqual(before);for(const id of ["old","round","seat"])expect(await subject.archived("roomMessages",id),id).toEqual(message(id));expect(await subject.archived("roomMessages","live")).toBeUndefined();});it("replays a moved command record, and refuses a retired Turn id at admission until the end",async()=>{const subject=await opened();const first=await subject.commit(request(subject,"i1",input2("k1")));const turnId=hash(["user","main","k1"]);await subject.change(state=>{Object.assign(state.turns[turnId],{status:"succeeded",conclusion:"succeeded",reported:true});settledRoot(state,"r3");});expect(await retain(subject,[turnId])).toMatchObject({archivedRoots:1,archivedCommands:1});expect((await subject.state()).commands?.i1).toBeUndefined();expect(await subject.commit(request(subject,"i1",input2("k1")))).toEqual(first);for(let attempt=0;attempt<2;attempt++){await refused(subject,()=>settle2(()=>subject.commit(request(subject,"i2",input2("k1")))),error=>{expect(error).toBeInstanceOf(RetiredIdentityError);expect(error).toMatchObject({code:"retired_identity",namespace:"turn",id:turnId});});}expect(await retain(subject,[],{now:RETENTION_NOW+MIN_TOMBSTONE_RETENTION_MS})).toMatchObject({expiredCommands:1});await refused(subject,()=>settle2(()=>subject.commit(request(subject,"i1",input2("k1")))),error=>expect(error).toBeInstanceOf(RetiredIdentityError));});it("keeps the pack without the Turns that can still freeze, and not more",async()=>{const queued=status=>state=>{state.cards={};state.questions={};state.turns.q={id:"q",root:"q",botId:"main",source:"user",request:"later",hop:0,status,authority:"owner"};};for(const status of ["queued","blocked"]){const subject2=await opened();await subject2.change(queued(status));await refused(subject2,()=>retain(subject2,["r2"]),error=>expect(error.message,status).toBe("Retention refused: The root is in the ContextPack window of its Bot"));expect(await retain(subject2,["r1"])).toMatchObject({archivedRoots:1});}const subject=await opened();await subject.change(queued("processing"));expect(await retain(subject,["r2"])).toMatchObject({archivedRoots:1});});it("protects what a queued Turn reads when totalBytes is under recentBytes + earlyBytes",async()=>{const handoff={recentBytes:1e3,earlyBytes:1e3,totalBytes:1100};const subject=await opened();await subject.change(state=>{state.cards={};state.questions={};for(const[id,size]of [...Array.from({length:10},(_,n)=>[`a${n}`,100]),["big",3e3]]){settledRoot(state,id);state.cards={};state.questions={};state.turns[id].request="x".repeat(size);}for(const id of ["q1","q2"])state.turns[id]={id,root:id,botId:"main",source:"user",request:"later",hop:0,status:"queued",authority:"owner"};});await refused(subject,()=>retain(subject,["a9"],{},{contextTurnLimit:1,handoff}),error=>expect(error.message).toBe("Retention refused: The root is in the ContextPack window of its Bot"));expect(await retain(subject,["a0"],{},{contextTurnLimit:1,handoff})).toMatchObject({archivedRoots:1});});it("refuses the id of a retired batch member when it returns as a Turn",async()=>{const subject=await opened();const first=hash(["user","main","kx"]),member=hash(["user","main","ky"]);const row=(id,key)=>({id,key,botId:"main",request:key,bytes:2,sender:"owner",authority:"owner",receivedAt:0,batchId:first});await subject.change(state=>{settledRoot(state,first);state.turns[first].inputIds=[first,member];state.inputs={[first]:row(first,"kx"),[member]:row(member,"ky")};state.inputBatches={[first]:{...inputBatch("sealed"),id:first,key:"kx",inputIds:[first,member]}};settledRoot(state,"r3");});expect(await retain(subject,[first])).toMatchObject({archivedRoots:1});await refused(subject,()=>settle2(()=>subject.commit(request(subject,"iy",input2("ky")))),error=>{expect(error).toBeInstanceOf(RetiredIdentityError);expect(error).toMatchObject({code:"retired_identity",namespace:"turn",id:member});});});it("refuses a retired round id at admission",async()=>{const subject=await opened();await subject.change(state=>{state.team.rooms.room={id:"room",name:"Room",members:["main"],visibleFrom:{main:0},mode:"mention",announcement:"",messages:[]};});const command={kind:"room_input",key:"k1",roomId:"room",text:"Hello",mentions:[]};const round=(await subject.commit(request(subject,"ri1",command))).disposition;expect(round.outcome).toBe("accepted");const roundId=round.value;expect(await retain(subject,[roundId])).toMatchObject({archivedRoots:1});await refused(subject,()=>settle2(()=>subject.commit(request(subject,"ri2",command))),error=>{expect(error).toBeInstanceOf(RetiredIdentityError);expect(error).toMatchObject({namespace:"round",id:roundId});});});it("keeps the record of a command whose root is still in the state",async()=>{const subject=await opened();await subject.commit(request(subject,"i1",input2("k1")));await retain(subject,["r1"]);expect(Object.keys((await subject.state()).commands??{})).toEqual(["i1"]);});});}var PROMPT="Daily report";var settle3=async work=>work();function daily(now){return {minute:0,hour:(new Date(now).getUTCHours()+12)%24,tz:"UTC"}}var slotAfter=(schedule,after)=>nextRoutineOccurrence(schedule,after);var occurrenceKey=(id,version,kind,plannedAt)=>hash([id,version,{kind,plannedAt}]);var routineTurn=key=>`occurrence:${key}`;function routineVectors(name,open){describe(`routine contract: ${name}`,()=>{async function created(subject,key="plan",prompt=PROMPT){const schedule=daily(subject.now()),turn=await subject.input(key,"Plan a routine");await subject.start(turn);await subject.finish(turn,json({create_routine:[{localId:"new_routine_1",schedule,prompt}]}));return {id:hash([taskId(turn,0),"create_routine",0]),schedule,turn}}async function due(subject,id,late=0){const slot=(await settle3(()=>subject.routine(id))).nextAt;subject.at(slot+late);await subject.fire(id);return slot}const newest=async(subject,id)=>routineTurn((await settle3(()=>subject.occurrences(id))).at(-1).key);async function blocker(subject,key="hold"){const turn=await subject.input(key,"Hold the queue");await subject.start(turn);return turn}const hold=(subject,held)=>subject.change(state=>{state.team.bots.main.readyRevision=held?"held":state.team.bots.main.revision;});it("creates a routine through an outcome action, and the next Turn's frozen instruction lists it",async()=>{const subject=await open(),at=subject.now();const{id,schedule}=await created(subject);expect(await subject.routine(id)).toEqual({id,version:1,pending:null,lifecycle:"active",status:"ok",nextAt:slotAfter(schedule,at-1),calendarErrors:0});const next=await subject.input("next","What is planned?");const instruction=(await subject.intent(next)).instruction;expect(instruction).toContain(id);expect(instruction).toContain(PROMPT);},6e4);it("fires on time as scheduled and late as catch_up, with the K4 occurrence keys and the routine Turn",async()=>{const subject=await open(),{id,schedule}=await created(subject);const first=await due(subject,id,ROUTINE_LATE_AFTER_MS),firstAt=subject.now();await subject.start(await newest(subject,id));const second=await due(subject,id,ROUTINE_LATE_AFTER_MS+1),secondAt=subject.now();const[one,two]=[occurrenceKey(id,1,"scheduled",first),occurrenceKey(id,1,"catch_up",second)];expect(await subject.occurrences(id)).toEqual([{key:one,routineId:id,version:1,trigger:{kind:"scheduled",plannedAt:first},recordedAt:firstAt,nextAt:second,executionSuperseded:false,promoted:true,conclusion:null},{key:two,routineId:id,version:1,trigger:{kind:"catch_up",plannedAt:second},recordedAt:secondAt,nextAt:slotAfter(schedule,secondAt),executionSuperseded:false,promoted:true,conclusion:null}]);expect((await subject.state()).turns[routineTurn(two)]).toMatchObject({id:routineTurn(two),root:routineTurn(two),botId:"main",source:"routine",request:PROMPT,hop:0,authority:"owner",status:"processing"});expect(await subject.intent(routineTurn(two))).toMatchObject({key:routineTurn(two),source:"routine",waitUntil:secondAt+ROUTINE_WAIT_MS,retryUntil:slotAfter(schedule,secondAt),conclusion:null});expect((await subject.intent(routineTurn(two))).instruction).toContain(PROMPT);expect(await subject.routine(id)).toMatchObject({nextAt:slotAfter(schedule,secondAt),status:"ok"});},6e4);it("supersedes an untried promoted intent at a new slot, and keeps a running one with retry_until at the first later slot",async()=>{const subject=await open(),{id,schedule}=await created(subject);await due(subject,id);const running=await newest(subject,id);await subject.start(running);await due(subject,id);const untried=await newest(subject,id),second=subject.now();expect(await subject.intent(running)).toMatchObject({tried:true,retryUntil:second,conclusion:null});expect(await subject.intent(untried)).toMatchObject({tried:false,conclusion:null});await due(subject,id);const now=subject.now(),latest=await newest(subject,id);expect(await subject.intent(running)).toMatchObject({tried:true,retryUntil:second,conclusion:null});expect(await subject.intent(untried)).toMatchObject({tried:false,conclusion:"superseded"});expect(await subject.intent(latest)).toMatchObject({tried:false,retryUntil:slotAfter(schedule,now),conclusion:null});expect((await subject.occurrences(id)).map(row=>row.conclusion)).toEqual([null,"superseded",null]);const turns=(await subject.state()).turns;expect([running,untried,latest].map(turn=>[turns[turn].status,turns[turn].conclusion])).toEqual([["processing",void 0],["failed","superseded"],["processing",void 0]]);},6e4);it("marks an unpromoted occurrence executionSuperseded at a new slot, and its later promotion settles superseded",async()=>{const subject=await open(),{id,schedule}=await created(subject);await hold(subject,true);await due(subject,id);const stale=await newest(subject,id);await due(subject,id);const fresh=await newest(subject,id),now=subject.now();expect((await subject.occurrences(id)).map(row=>[row.promoted,row.executionSuperseded,row.conclusion])).toEqual([[false,true,null],[false,false,null]]);expect(await subject.intent(stale)).toBeUndefined();await hold(subject,false);await subject.sync();expect(await subject.intent(stale)).toMatchObject({source:"routine",conclusion:"superseded",tried:false});expect(await subject.intent(fresh)).toMatchObject({conclusion:null,retryUntil:slotAfter(schedule,now)});expect((await subject.occurrences(id)).map(row=>[row.promoted,row.conclusion])).toEqual([[true,"superseded"],[true,null]]);expect((await subject.state()).turns[stale]).toMatchObject({status:"failed",conclusion:"superseded"});},6e4);describe("stages a version while an occurrence is open, and switches when it concludes",()=>{async function switched(subject,id,schedule,conclude,conclusion){const turn=await newest(subject,id);await subject.update({routineId:id,prompt:"Version 2"});expect(await subject.routine(id)).toMatchObject({version:1,pending:2});await conclude(turn);expect((await subject.occurrences(id)).at(-1).conclusion).toBe(conclusion);expect(await subject.routine(id)).toMatchObject({version:2,pending:null,lifecycle:"active",nextAt:slotAfter(schedule,subject.now())});}it("after the routine Turn succeeds",async()=>{const subject=await open(),{id,schedule}=await created(subject);await due(subject,id);await subject.start(await newest(subject,id));await switched(subject,id,schedule,turn=>subject.finish(turn,{}),"succeeded");},6e4);it("after the owner cancels the queued routine Turn",async()=>{const subject=await open(),{id,schedule}=await created(subject);await blocker(subject);await due(subject,id);expect(await subject.intent(await newest(subject,id))).toMatchObject({tried:false,conclusion:null});await switched(subject,id,schedule,turn=>subject.cancelTurn(turn),"cancelled");},6e4);it("after the owner cancels the routine Turn before its promotion",async()=>{const subject=await open(),{id,schedule}=await created(subject);await hold(subject,true);await due(subject,id);await switched(subject,id,schedule,turn=>subject.cancelTurn(turn),"cancelled");expect((await subject.occurrences(id)).at(-1).promoted).toBe(false);},6e4);});it("pauses: removes the successor retry_until and the slot, then resumes on the current version",async()=>{const subject=await open(),{id,schedule}=await created(subject);const slot=await due(subject,id);const turn=await newest(subject,id);await subject.start(turn);expect(await subject.intent(turn)).toMatchObject({retryUntil:slotAfter(schedule,slot)});await subject.lifecycle(id,"paused");expect(await subject.routine(id)).toMatchObject({lifecycle:"paused",nextAt:null});expect(await subject.intent(turn)).toMatchObject({retryUntil:null,conclusion:null});await subject.lifecycle(id,"active");expect(await subject.routine(id)).toMatchObject({lifecycle:"active",version:1,nextAt:slotAfter(schedule,subject.now())});expect(await subject.intent(turn)).toMatchObject({retryUntil:null});await due(subject,id,1);expect(await subject.intent(turn)).toMatchObject({retryUntil:subject.now(),conclusion:null});},6e4);it("completes a routine through cancel_routine, and keeps at most eight open routines per owner",async()=>{const subject=await open(),ids=[];for(let n=0;n<8;n++)ids.push((await created(subject,`plan-${n}`)).id);const ninth=await created(subject,"plan-8");expect(await subject.routine(ninth.id)).toBeUndefined();expect((await subject.state()).rejected.at(-1)).toMatchObject({action:"create_routine",reason:"Routine limit is 8",taskId:taskId(ninth.turn,0)});const cancel=await subject.input("cancel","Stop the first routine");await subject.start(cancel);await subject.finish(cancel,{cancel_routine:[{routineId:ids[0]}]});expect(await subject.routine(ids[0])).toMatchObject({lifecycle:"completed",nextAt:null,pending:null});const tenth=await created(subject,"plan-9");expect(await subject.routine(tenth.id)).toMatchObject({lifecycle:"active",version:1});},12e4);it("ends a routine of an archived owner only with Main Bot authority, and the ended routine has no later slot",async()=>{const subject=await open(),at=subject.now();await subject.change(state=>{state.team.bots.helper={...structuredClone(state.team.bots.main),id:"helper",name:"Helper",mainBot:false};});const id=await subject.addRoutine("helper",daily(at)),slot=(await subject.routine(id)).nextAt;expect(await subject.reserved(id)).toEqual([slot]);await subject.change(state=>{archiveBot(state.team,"helper");});await expect(subject.lifecycle(id,"completed")).rejects.toThrow("Routine is unavailable to this Bot");await subject.change(state=>{state.team.bots.main.mainBot=false;});await expect(subject.end(id)).rejects.toThrow("Main Bot role required");expect(await subject.routine(id)).toMatchObject({lifecycle:"active",nextAt:slot});await subject.change(state=>{state.team.bots.main.mainBot=true;});await subject.end(id);expect(await subject.routine(id)).toEqual({id,version:1,pending:null,lifecycle:"completed",status:"ok",nextAt:null,calendarErrors:0});expect(await subject.reserved(id)).toEqual([]);await expect(subject.end(id)).rejects.toThrow("No open Bot routine has this id");},6e4);it("concludes the occurrence cancelled when its routine Turn is cancelled before promotion",async()=>{const subject=await open(),{id}=await created(subject);await hold(subject,true);await due(subject,id);const turn=await newest(subject,id);await subject.cancelTurn(turn);expect((await subject.occurrences(id)).map(row=>[row.promoted,row.conclusion])).toEqual([[false,"cancelled"]]);expect(await subject.intent(turn)).toBeUndefined();expect((await subject.state()).turns[turn]).toMatchObject({status:"failed",conclusion:"cancelled"});},6e4);it("refuses a slot whose routine Turn id retention retired, and records no occurrence",async()=>{const subject=await open(),id=await subject.addRoutine("main",daily(subject.now())),slot=(await subject.routine(id)).nextAt;await subject.retire(routineTurn(occurrenceKey(id,1,"scheduled",slot)));subject.at(slot);await expect(subject.fire(id)).rejects.toThrow(RetiredIdentityError);expect(await subject.occurrences(id)).toEqual([]);});});}
15
+ var policy={policyRevision:"k4-v1",activity:{delivery:"latest-value",maxCoalesceMs:250,maxEventBytes:262144},reliable:{maxPendingEventsPerAgent:16,maxPendingBytesPerAgent:4096,maxPendingBytesPerTenant:16384},transfers:{workspace:"disabled",transcript:"disabled",artifact:"disabled"}};function template(deviceId,agentId="main"){return {deviceId,payload:{target:{lane:"harness",harnessId:"pi",selection:{mode:"device-default"}},session:{mode:"fresh"},instruction:"Return the test result through submit_result.",agentRef:{agentId,profileRevision:"1"},egressPolicy:policy,terminalProjection:{mode:"result-document",contract:"host-core-test-v1",schema:{type:"object",additionalProperties:false,required:["text"],properties:{text:{type:"string"}}}}}}}var noPublish=()=>{};var VECTOR_NOW=1e3;function seedCollaboration(state,team="local"){state.team.bots.main={id:"main",name:"Main",role:"Team owner",persona:"",model:"default",mainBot:true,archived:false,revision:"1",readyRevision:"1",execution:template("device","main"),autonomy:"auto"};state.turns.t1={id:"t1",root:"t1",botId:"main",source:"user",request:"Work",hop:0,status:"processing",authority:"owner"};state.budgets.t1={continuation:0,delegation:0};state.schemas.t1=outcomeSchema("main",state,state.turns.t1);state.questions.q1={id:"q1",turnId:"t1",value:{question:"Go?",answerKind:"text"}};state.cards.c1={id:"c1",turnId:"t1",action:{action:"send_message",summary:"Send",draft:{text:"hi"}},state:"pending",expiresAt:0};if(team==="external")state.team.external={revision:1};if(team==="rooms")state.team.external={revision:1,rooms:true};}var input=(key,request="Hello")=>({kind:"input",botId:"main",key,request,sender:"owner"});var settle=async work=>work();var teamError=async work=>{try{await work();}catch(cause){return cause instanceof TeamModeError?cause.code:cause}return "no error"};function commitVectors({describe,it,expect},name,open){describe(`commit contract: ${name}`,()=>{const request=(subject,commandId,command,expectedRevision)=>({scope:subject.scope,commandId,command,...expectedRevision===void 0?{}:{expectedRevision}});const conflict=async(subject,req,code,message)=>{const before=await subject.stored();let error;try{await subject.commit(req);}catch(cause){error=cause;}expect(error).toBeInstanceOf(CommitConflict);expect(error.code).toBe(code);if(message)expect(error.message).toBe(message);expect(await subject.stored()).toBe(before);};it("commits a new command once and returns the same result to a replay",async()=>{const subject=await open(),first=await subject.commit(request(subject,"i1",input("k1")));expect(first).toEqual({revision:1,disposition:{outcome:"accepted",value:hash(["user","main","k1"])},outbox:[]});const stored=await subject.stored();expect(await subject.commit(request(subject,"i1",input("k1")))).toEqual(first);expect(await subject.stored()).toBe(stored);});it("replays with the original expected revision after the head moved",async()=>{const subject=await open(),first=await subject.commit(request(subject,"i1",input("k1"),0));expect((await subject.commit(request(subject,"i2",input("k2")))).revision).toBe(2);expect(await subject.commit(request(subject,"i1",input("k1"),0))).toEqual(first);});it("refuses the same command id with other content, and keeps the existing error text",async()=>{const subject=await open();await subject.commit(request(subject,"i1",input("k1")));await conflict(subject,request(subject,"i1",input("k1","Other")),"identity_conflict","Input identity conflict");await subject.commit(request(subject,"a1",{kind:"answer",questionId:"q1",answer:"Yes"}));await conflict(subject,request(subject,"a1",{kind:"answer",questionId:"q1",answer:"No"}),"identity_conflict","Answer identity conflict");});it("decides on the head without an expected revision, and refuses a stale explicit revision",async()=>{const subject=await open();expect((await subject.commit(request(subject,"i1",input("k1")))).revision).toBe(1);await conflict(subject,request(subject,"i2",input("k2"),0),"stale_revision");expect((await subject.commit(request(subject,"i2",input("k2"),1))).revision).toBe(2);});it("refuses a commit for another scope",async()=>{const subject=await open();await conflict(subject,{...request(subject,"i1",input("k1")),scope:`${subject.scope}:other`},"scope_mismatch");});it("keeps no revision, record or outbox row when the decision throws",async()=>{const subject=await open(),before=await subject.stored();await expect(settle(()=>subject.commit(request(subject,"i1",{...input("k1"),botId:"absent"})))).rejects.toThrow("Bot is archived or absent");expect(await subject.stored()).toBe(before);expect((await subject.commit(request(subject,"i1",input("k1")))).revision).toBe(1);});it("commits a refused disposition and replays it",async()=>{const subject=await open(),decide={kind:"decide",cardId:"c1",decision:"confirmed"};const first=await subject.commit(request(subject,"d1",decide));expect(first).toEqual({revision:1,disposition:{outcome:"refused",reasonCode:"card_expired",reason:"Card expired"},outbox:[]});expect(await subject.commit(request(subject,"d1",decide))).toEqual(first);await conflict(subject,request(subject,"d1",{...decide,decision:"rejected"}),"identity_conflict","Card expired");});it("applies a keyless command at each call, adds 1 each time and keeps no record (#739 6a)",async()=>{const subject=await open(),command={kind:"set_main_bot",botId:"main",mainBot:true};await subject.commit(request(subject,"i1",input("k1")));expect(await subject.commit(request(subject,"m1",command))).toEqual({revision:2,disposition:{outcome:"accepted"},outbox:[]});expect((await subject.commit(request(subject,"m1",command))).revision).toBe(3);expect(Object.keys((await subject.state()).commands??{})).toEqual(["i1"]);});it("protects a keyless retry only with an explicit expected revision",async()=>{const subject=await open(),command={kind:"set_main_bot",botId:"main",mainBot:false};expect((await subject.commit(request(subject,"m1",command,0))).revision).toBe(1);await conflict(subject,request(subject,"m1",command,0),"stale_revision");expect((await subject.commit(request(subject,"m1",command,1))).revision).toBe(2);});it("keys each record by its own command id, also for `constructor` and `__proto__`",async()=>{const subject=await open();for(const[index,id]of ["constructor","toString","__proto__"].entries()){const first=await subject.commit(request(subject,id,input(`k${index}`)));expect(first.revision).toBe(index+1);const stored=await subject.stored();expect(await subject.commit(request(subject,id,input(`k${index}`)))).toEqual(first);expect(await subject.stored()).toBe(stored);}});const main={id:"main",name:"Main",role:"Team owner",mainBot:true};const team=(revision,...bots)=>[hash(["team",revision]),{kind:"team_snapshot",snapshot:{revision,bots:bots.map(bot=>({name:bot.id,role:"Helper",persona:"",model:"default",mainBot:false,...bot}))}}];const withRooms=([id,command],rooms)=>[id,{...command,snapshot:{...command.snapshot,rooms}}];it("applies a newer team snapshot: archives a missing Bot, adds a new one and queues a projection for a changed one (#739 Q4c)",async()=>{const subject=await open("external");await subject.commit(request(subject,...team(2,main,{id:"b2"})));expect(await subject.commit(request(subject,...team(3,{...main,persona:"New"})))).toEqual({revision:2,disposition:{outcome:"accepted"},outbox:[]});const state=await subject.state();expect(state.team.external).toEqual({revision:3});expect(state.team.bots.b2).toMatchObject({archived:true,mainBot:false,revision:"1",readyRevision:null});expect(state.team.bots.main).toMatchObject({archived:false,mainBot:true,persona:"New",revision:"2",readyRevision:null});expect(state.team.homeOperations.map(op=>[op.botId,op.request.payload.agentRef.profileRevision])).toEqual([["b2","1"],["main","2"]]);});it("replays a team revision with the same Bots in any order, and refuses other Bots for it",async()=>{const subject=await open("external"),first=await subject.commit(request(subject,...team(2,main,{id:"b2"})));const stored=await subject.stored();expect(await subject.commit(request(subject,...team(2,{id:"b2"},main)))).toEqual(first);expect(await subject.stored()).toBe(stored);await conflict(subject,request(subject,...team(2,main)),"identity_conflict","Team snapshot identity conflict");});it("refuses a team revision that is not newer with stale_team, after a replay check",async()=>{const subject=await open("external"),applied=await subject.commit(request(subject,...team(2,main)));await subject.commit(request(subject,...team(4,main)));expect(await subject.commit(request(subject,...team(2,main)))).toEqual(applied);expect(await subject.commit(request(subject,...team(3,main)))).toEqual({revision:3,disposition:{outcome:"refused",reasonCode:"stale_team",reason:"stale_team: team revision 3 is not newer than 4"},outbox:[]});expect((await subject.commit(request(subject,...team(1,main)))).disposition).toMatchObject({reasonCode:"stale_team"});expect((await subject.state()).team.external).toEqual({revision:4});});it("changes nothing for an invalid team snapshot, a returning archived Bot or setMainBot in external mode",async()=>{const subject=await open("external"),before=await subject.stored();await expect(settle(()=>subject.commit(request(subject,...team(2,main,main))))).rejects.toThrow("Duplicate team snapshot Bot");for(const id of ["__proto__","constructor","team/helper","CON","tab here","x".repeat(300)]){await expect(settle(()=>subject.commit(request(subject,...team(2,main,{id}))))).rejects.toThrow("Invalid team snapshot Bot id");}await expect(settle(()=>subject.commit(request(subject,...team(2,main,{id:"b2",persona:"x".repeat(7e4)}))))).rejects.toThrow("Team snapshot Bot projection is too large");await expect(settle(()=>subject.commit(request(subject,...team(2,main,{id:"b2",participation:"active"}))))).rejects.toThrow(/^Invalid team snapshot Bot$/);expect(await teamError(()=>subject.commit(request(subject,"m1",{kind:"set_main_bot",botId:"main",mainBot:false})))).toBe("external_team");expect(await subject.stored()).toBe(before);await subject.commit(request(subject,...team(2,main,{id:"b2"})));await subject.commit(request(subject,...team(3,main)));const archived=await subject.stored();await expect(settle(()=>subject.commit(request(subject,...team(4,main,{id:"b2"}))))).rejects.toThrow("An archived Bot cannot return");expect(await subject.stored()).toBe(archived);const execution=(await subject.state()).team.bots.main.execution;await subject.commit(request(subject,...team(4,{...main,model:"absent"})));expect((await subject.state()).team.bots.main).toMatchObject({model:"absent",revision:"2",execution:{...execution,payload:{...execution.payload,agentRef:{agentId:"main",profileRevision:"2"}}}});});it("refuses a team snapshot for a local team",async()=>{const subject=await open(),before=await subject.stored();await expect(settle(()=>subject.commit(request(subject,...team(1,main))))).rejects.toThrow("Team snapshots need the external team mode");expect(await subject.stored()).toBe(before);});it("creates an owner room with the Host room id: a replay returns the first result, other fields conflict (#1321)",async()=>{const subject=await open(),fields={name:"Macro",members:["main"]};const create=(roomId,commandId=hash(["create_room",roomId]))=>request(subject,commandId,{kind:"create_room",roomId,fields});const first=await subject.commit(create("macro"));expect(first).toEqual({revision:1,disposition:{outcome:"accepted"},outbox:[]});const stored=await subject.stored();expect(await subject.commit(create("macro"))).toEqual(first);expect(await subject.stored()).toBe(stored);await conflict(subject,{...create("macro"),command:{kind:"create_room",roomId:"macro",fields:{...fields,name:"Other"}}},"identity_conflict","Room identity conflict");expect((await subject.state()).team.rooms.macro).toEqual({id:"macro",name:"Macro",members:["main"],mode:"mention",announcement:"",visibleFrom:{main:0},messages:[]});const round=await subject.commit(request(subject,"r1",{kind:"room_input",key:"m1",roomId:"macro",text:"Hello",mentions:["main"]}));expect((await subject.state()).team.rounds[round.disposition.value]).toMatchObject({roomId:"macro"});await expect(settle(()=>subject.commit(create("macro","other")))).rejects.toThrow("Room already exists");for(const id of ["a:b","constructor"])await expect(settle(()=>subject.commit(create(id)))).rejects.toThrow("Invalid room id");});it("writes the rooms of a team snapshot in the external rooms mode as a whole (#1321)",async()=>{const subject=await open("rooms"),bots=[main,{id:"b2"},{id:"b3"}];await subject.commit(request(subject,...withRooms(team(2,...bots),[{id:"r",name:"R",members:["main","b2"],admin:"b2",announcement:"Hi",memberMentions:"ignore"}])));expect((await subject.state()).team.rooms.r).toEqual({id:"r",name:"R",members:["main","b2"],admin:"b2",mode:"mention",announcement:"Hi",memberMentions:"ignore",visibleFrom:{main:0,b2:0},messages:[]});await subject.commit(request(subject,"r1",{kind:"room_input",key:"m1",roomId:"r",text:"Hello",mentions:[]}));await subject.commit(request(subject,...withRooms(team(3,...bots),[{id:"r",name:"R",members:["main","b3"]}])));expect((await subject.state()).team.rooms.r).toEqual({id:"r",name:"R",members:["main","b3"],mode:"mention",announcement:"",visibleFrom:{main:0,b3:1},messages:[expect.objectContaining({text:"Hello"})]});});it("refuses local room management and a snapshot whose rooms do not match the mode, and changes nothing (#1321)",async()=>{const subject=await open("rooms"),before=await subject.stored();const commands=[{kind:"create_room",roomId:"r",fields:{name:"R",members:["main"]}},{kind:"update_room",roomId:"r",update:{name:"S"}},{kind:"set_room_member_mentions",roomId:"r",memberMentions:"ignore"}];for(const command of commands)expect(await teamError(()=>subject.commit(request(subject,command.kind,command)))).toBe("external_rooms");await expect(settle(()=>subject.commit(request(subject,...team(2,main))))).rejects.toThrow("A team snapshot needs rooms in the external rooms mode");for(const field of [{mode:null},{mode:""},{mode:0},{mode:false},{mode:"admin"},{admin:""}]){await expect(settle(()=>subject.commit(request(subject,...withRooms(team(2,main),[{id:"r",name:"R",members:["main"],...field}]))))).rejects.toThrow(/^Invalid team snapshot room$/);}expect(await subject.stored()).toBe(before);const local=await open("external"),stored=await local.stored();await expect(settle(()=>local.commit(request(local,...withRooms(team(2,main),[]))))).rejects.toThrow("Snapshot rooms need the external rooms mode");expect(await local.stored()).toBe(stored);});it("records an observing Bot's create_routine once as a would-do row and creates no routine (#1229)",async()=>{const subject=await open(),document={create_routine:[{localId:"new_routine_1",schedule:{hour:9,minute:0,tz:"UTC"},prompt:"Daily report"}]};await subject.commit(request(subject,"observe",{kind:"set_autonomy",botId:"main",autonomy:"observe"}));const first=await subject.commit(request(subject,"task-1",{kind:"outcome",turnId:"t1",taskId:"task-1",document}));const replay=await subject.commit(request(subject,"task-1",{kind:"outcome",turnId:"t1",taskId:"task-1",document}));const state=await subject.state();expect(wouldDoRows(state)).toEqual([expect.objectContaining({botId:"main",action:"create_routine",index:0})]);expect(first.outbox).toEqual([{kind:"projection",id:`would-do:${wouldDoRows(state)[0].id}`}]);if(replay.revision===first.revision)expect(replay).toEqual(first);expect(state.rejected).toEqual([]);});it("returns the outbox rows that the commit wrote",async()=>{const subject=await open(),card=hash(["task-1","confirmable_action",0]);const result=await subject.commit(request(subject,"task-1",{kind:"outcome",turnId:"t1",taskId:"task-1",document:{confirmable_action:[{action:"send_message",summary:"Send",draft:{text:"hello"}}]}}));expect(result).toEqual({revision:1,disposition:{outcome:"accepted"},outbox:[{kind:"projection",id:`card:${card}`}]});});});}var SYNC_OPTIONS={now:VECTOR_NOW,models:["default"],readOnlyToolsets:[],limits:{turnLimit:12,contextMaxBytes:32768,instructionMaxBytes:65536},historyMode:false,routines:[]};function seedSync(state){Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.cards.c1.expiresAt=Number.MAX_SAFE_INTEGER;state.turns.q1={id:"q1",root:"q1",botId:"main",source:"user",request:"First",hop:0,status:"queued",authority:"owner"};state.turns.q2={id:"q2",root:"q1",botId:"main",source:"continuation",request:"Next",hop:0,status:"queued",authority:"owner"};}var NO_FACTS={intent:()=>void 0,executionStarted:()=>false,retired:()=>void 0};function syncVectors({describe,it,expect},name,open){describe(`sync contract: ${name}`,()=>{const seeded=async()=>{const subject=await open();await subject.change(seedSync);return subject};it("stores the frozen intent input as the rule returns it, with no command record and no revision change",async()=>{const subject=await seeded(),before=await subject.state();const expected=structuredClone(before),step=syncTurn(expected,expected.turns.q1,NO_FACTS,SYNC_OPTIONS,()=>{});await subject.sync();const after=await subject.state();expect(step).toMatchObject({kind:"freeze"});expect(await subject.intent("q1")).toEqual(step.input);expect(await subject.intent("q1")).toMatchObject({key:"q1",source:"user",waitUntil:VECTOR_NOW+OFFER_WAIT_MS,execution:{payload:{terminalProjection:{mode:"result-document",contract:BOT_TURN_OUTCOME_CONTRACT,schema:after.schemas.q1}}}});expect(await subject.intent("q2")).toMatchObject({key:"q2",source:"bot"});expect(await subject.intent("t1")).toBeUndefined();expect([after.turns.q1.status,after.turns.q2.status]).toEqual(["processing","processing"]);expect([after.revision,after.commands]).toEqual([before.revision,before.commands]);});it("changes no stored byte at a second sync",async()=>{const subject=await seeded();await subject.sync();const stored=await subject.stored();await subject.sync();expect(await subject.stored()).toBe(stored);});it("keeps the expected revision of a client valid across a sync",async()=>{const subject=await seeded(),revision=(await subject.state()).revision??0;await subject.sync();const result=await subject.commit({scope:subject.scope,commandId:"i1",command:input("k1"),expectedRevision:revision});expect(result.revision).toBe(revision+1);});it("writes the report of a concluded intent to the outbox once, at the same revision",async()=>{const subject=await seeded();await subject.sync();await subject.concludeIntent("q1","succeeded");const revision=(await subject.state()).revision;expect(await subject.projection("bot-turn:q1")).toEqual([]);await subject.sync();expect(await subject.projection("bot-turn:q1")).toEqual([expect.objectContaining({owner:"main",id:"q1",status:"succeeded",conclusion:"succeeded"})]);const after=await subject.state();expect([after.turns.q1.status,after.turns.q1.reported,after.revision]).toEqual(["succeeded",true,revision]);const stored=await subject.stored();await subject.sync();expect(await subject.stored()).toBe(stored);});});}function settlementSteps(expect,open){const settled=async(subject,now=VECTOR_NOW,timers)=>{for(let round=0;round<5;round++){const before=await subject.stored();await subject.settle(now,timers);if(await subject.stored()===before)return}throw new Error("The sync does not settle")};let commands=0;const commit=async(subject,command)=>{const result=await subject.commit({scope:subject.scope,commandId:`settle-${++commands}`,command});if(result.disposition.outcome!=="accepted")throw new Error(`Refused ${command.kind}: ${JSON.stringify(result.disposition)}`);return result.disposition.value};const owner=async(subject,key,document)=>{const turnId=await commit(subject,{kind:"input",botId:"main",key,request:key,sender:"owner"});await settled(subject);await commit(subject,{kind:"outcome",turnId,taskId:taskId(turnId,0),document});await subject.terminal(turnId,"task.complete",{document});await subject.conclude(turnId,"succeeded");await settled(subject);return turnId};const delegated=async()=>{const subject=await open();await subject.change(state=>{Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.team.bots.b={...state.team.bots.main,id:"b",name:"B",role:"Reviewer",mainBot:false,execution:template("device","b")};});const root=await owner(subject,"r1",{delegate:[{to:"b",request:"Check"}]});const id=hash([taskId(root,0),"delegate",0]);expect(await subject.intent(id)).toMatchObject({key:id});return {subject,root,id,delegation:async()=>(await subject.state()).delegations[id]}};return {settled,commit,owner,delegated}}function settlementVectors({describe,it,expect},name,open){describe(`settlement contract: ${name}`,()=>{const TIMERS={cancelGraceMs:1e3,uncertainAfterMs:5e3};const{settled,commit,owner,delegated}=settlementSteps(expect,open);const unit=(state,id)=>state.units[hash([id,"B"])].state;const ends=[["a failed terminal",async(subject,id)=>{await subject.terminal(id,"task.fail",{});await subject.conclude(id,"failed");},{verdict:"failed"},"spent"],["a busy decline",async(subject,id)=>{await subject.terminal(id,"task.decline",{code:"agent_home_writer_busy"});await subject.conclude(id,"declined");},{verdict:"failed",reason:"busy"},"released"],["a decline with no code",async(subject,id)=>{await subject.terminal(id,"task.decline",{});await subject.conclude(id,"declined");},{verdict:"failed",reason:"busy"},"released"],["another decline",async(subject,id)=>{await subject.terminal(id,"task.decline",{code:"model_unavailable"});await subject.conclude(id,"declined");},{verdict:"failed",reason:"model_unavailable"},"released"],["an expiry",async(subject,id)=>{await subject.conclude(id,"expired");},{verdict:"expired"},"released"],["a cancel that raced the wait deadline",async(subject,id)=>{await subject.conclude(id,"cancelled","expired");},{verdict:"expired",reason:"claim_raced_deadline"},"released"],["a cancel",async(subject,id)=>{await subject.conclude(id,"cancelled","cancelled");},{verdict:"cancelled",reason:"user_cancelled"},"released"]];for(const[end,conclude,verdict,units]of ends){it(`gives ${end} of the chain end its verdict, and spends or releases the unit`,async()=>{const{subject,id,delegation:delegation2}=await delegated();await conclude(subject,id);await settled(subject);const state=await subject.state(),d=await delegation2();expect(d).toMatchObject({...verdict,status:"resolved",replyTurnId:hash(["bot_reply",id])});if(!verdict.reason)expect(d.reason).toBeUndefined();expect(unit(state,id)).toBe(units);expect(state.turns[d.replyTurnId]).toMatchObject({source:"bot_reply",botId:"main",replies:[expect.objectContaining(verdict)]});});}it("spends the unit at the first claim, and the delegation runs",async()=>{const{subject,id,delegation:delegation2,root:chain}=await delegated();const root=(await delegation2()).root,before=(await subject.state()).budgets[root];await subject.claim(id);await settled(subject);const state=await subject.state();expect(unit(state,id)).toBe("spent");expect(state.budgets[root]).toMatchObject({reserved:before.reserved-1,delegation:before.delegation+1});expect(await delegation2()).toMatchObject({status:"running",claimed:{turnId:id,at:VECTOR_NOW}});expect(await subject.projection(`delegation:${id}:2`)).toEqual([expect.objectContaining({root:chain,status:"running"})]);});it("takes a decline terminal as no start, and any other terminal as a start",async()=>{const declined=await delegated();await declined.subject.terminal(declined.id,"task.decline",{code:"model_unavailable"});await settled(declined.subject);expect(unit(await declined.subject.state(),declined.id)).toBe("reserved");expect((await declined.delegation()).status).not.toBe("running");const failed=await delegated();await failed.subject.terminal(failed.id,"task.fail",{});await settled(failed.subject);expect(unit(await failed.subject.state(),failed.id)).toBe("spent");expect(await failed.delegation()).toMatchObject({status:"running"});});it("refuses a delegation whose target Bot was archived (target_archived), once its target concluded",async()=>{const{subject,id,delegation:delegation2}=await delegated();await subject.change(state=>{state.team.bots.b.archived=true;});await settled(subject);expect(await delegation2()).toMatchObject({cancel:{reason:"target_archived",targetTurnId:id}});await subject.conclude(id,"cancelled","cancelled");await settled(subject);expect(await delegation2()).toMatchObject({verdict:"refused",reason:"target_archived",status:"resolved"});});it("suspends a Bot by team snapshot: its work ends, it takes no new work, and a later snapshot restores it (#1319)",async()=>{const{subject,id,delegation:delegation2}=await delegated();const snapshot=(revision,b)=>({kind:"team_snapshot",snapshot:{revision,bots:[{id:"main",name:"Main",role:"Team owner",persona:"",model:"default",mainBot:true},{id:"b",name:"B",role:"Reviewer",persona:"",model:"default",mainBot:false,...b}]}});const input3=(botId,key)=>({kind:"input",botId,key,request:key,sender:"owner"});const targets=async turnId=>(await subject.state()).schemas[turnId].properties.delegate.items.properties.to.enum;await subject.change(state=>{state.team.external={revision:1};state.team.bots.b.autonomy="auto";state.turns.qb={id:"qb",root:"qb",botId:"b",source:"user",request:"Later",hop:0,status:"queued",authority:"owner"};state.questions.qb={id:"qb",turnId:id,value:{question:"Go?",answerKind:"text"}};state.team.rooms.r={id:"r",...roomFields(state.team,{name:"Room",members:["main","b"]}),messages:[]};});const before=(await subject.state()).team.bots.b;await commit(subject,snapshot(2,{participation:"suspended"}));await settled(subject);expect((await subject.state()).turns.qb).toMatchObject({status:"failed",conclusion:"cancelled"});expect(await delegation2()).toMatchObject({cancel:{reason:"target_suspended",targetTurnId:id}});await subject.conclude(id,"cancelled","cancelled");await settled(subject);expect(await delegation2()).toMatchObject({verdict:"refused",reason:"target_suspended",status:"resolved"});const stored=await subject.stored();for(const command of [input3("b","kb"),{kind:"answer",questionId:"qb",answer:"Yes"}]){expect(await teamError(()=>subject.commit({scope:subject.scope,commandId:`refused-${command.kind}`,command}))).toBe("bot_suspended");}expect(await subject.stored()).toBe(stored);const own=await commit(subject,input3("main","k2"));const round=await commit(subject,{kind:"room_input",key:"m1",roomId:"r",text:"Hello",mentions:"all"});await settled(subject);expect(await targets(own)).toEqual(["main"]);const team=(await subject.state()).team,seat=team.rounds[round].seats[0];expect(team.rounds[round].seats.map(id2=>team.seats[id2].botId)).toEqual(["main"]);await subject.change(state=>{state.team.rounds[round].closed=true;state.team.bots.main.autonomy="auto";const turn=state.turns[seat]={id:seat,root:round,source:"room_slot",botId:"main",request:"Hello",hop:0,status:"succeeded",conclusion:"succeeded",reported:true,authority:"bot"};const{participation:_,...b}=state.team.bots.b;state.schemas[seat]=outcomeSchema("main",{...state,team:{...state.team,bots:{...state.team.bots,b}}},turn);});await commit(subject,{kind:"outcome",turnId:seat,taskId:taskId(seat,0),document:{speech:{kind:"post",text:"Over to b"},room_call:{members:["b"]}}});const called=await subject.state();expect(called.rejected).toContainEqual(expect.objectContaining({action:"room_call",reason:"bot_suspended: Bot b is not participating"}));expect(Object.keys(called.team.rounds)).toEqual(Object.keys(team.rounds));await commit(subject,snapshot(3,{}));const after=(await subject.state()).team.bots.b;expect(after.participation).toBeUndefined();expect([after.revision,after.readyRevision,after.autonomy]).toEqual([before.revision,before.readyRevision,"auto"]);const restored=await commit(subject,input3("b","kb")),next=await commit(subject,input3("main","k3"));await settled(subject);expect(await subject.intent(restored)).toMatchObject({key:restored});expect(await targets(next)).toEqual(["main","b"]);});it("archives a room that a rooms-mode snapshot no longer lists: its seats are removed, a started seat's speech is audit only (#1321)",async()=>{const subject=await open();const bots=[{id:"main",name:"Main",role:"Team owner",persona:"",model:"default",mainBot:true},{id:"b",name:"B",role:"Reviewer",persona:"",model:"default",mainBot:false}];const snapshot=(revision,rooms)=>({kind:"team_snapshot",snapshot:{revision,bots,rooms}});const room2={id:"r",name:"Room",members:["main","b"]};await subject.change(state=>{state.team.external={revision:1,rooms:true};Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.team.bots.b={...state.team.bots.main,id:"b",name:"B",role:"Reviewer",mainBot:false,execution:template("device","b")};});await commit(subject,snapshot(2,[room2]));const round=await commit(subject,{kind:"room_input",key:"m1",roomId:"r",text:"Hello",mentions:["b","main"]});await settled(subject);const[started,waiting]=(await subject.state()).team.rounds[round].seats;await subject.claim(started);await settled(subject);await commit(subject,snapshot(3,[]));await settled(subject);const team=(await subject.state()).team;expect(team.rooms.r).toMatchObject({archived:true,members:[],visibleFrom:{}});expect([team.seats[started],team.seats[waiting]]).toMatchObject([{botId:"b",status:"removed",released:true},{botId:"main",status:"removed",released:true}]);expect(team.rounds[round].closed).toBe(true);await commit(subject,{kind:"outcome",turnId:started,taskId:taskId(started,0),document:{speech:{kind:"post",text:"Late"}}});const after=await subject.state();expect(after.audit).toContain(`Outcome audit only: ${taskId(started,0)}`);expect(after.team.rooms.r.messages.map(message=>message.id)).toEqual([round]);await expect(commit(subject,{kind:"room_input",key:"m2",roomId:"r",text:"Again",mentions:[]})).rejects.toThrow("Room is archived");const stored=await subject.stored();await expect(commit(subject,snapshot(4,[room2]))).rejects.toThrow("An archived room cannot return");expect(await subject.stored()).toBe(stored);});it("shows a cancel with no conclusion as uncertain once the cancel grace passed",async()=>{const{subject,id,delegation:delegation2}=await delegated();await subject.submit(id);await subject.change(state=>{state.team.bots.b.archived=true;});await settled(subject,VECTOR_NOW,TIMERS);await settled(subject,VECTOR_NOW+TIMERS.cancelGraceMs-1,TIMERS);expect((await delegation2()).status).not.toBe("uncertain");await settled(subject,VECTOR_NOW+TIMERS.cancelGraceMs,TIMERS);expect(await delegation2()).toMatchObject({status:"uncertain",uncertainSince:VECTOR_NOW+TIMERS.cancelGraceMs});expect(await delegation2()).not.toHaveProperty("verdict");});const uncertainClaim=async()=>{const h=await delegated();await h.subject.claim(h.id);await settled(h.subject,VECTOR_NOW,TIMERS);await settled(h.subject,VECTOR_NOW+TIMERS.uncertainAfterMs-1,TIMERS);expect((await h.delegation()).status).toBe("running");await settled(h.subject,VECTOR_NOW+TIMERS.uncertainAfterMs,TIMERS);expect(await h.delegation()).toMatchObject({status:"uncertain",uncertainSince:VECTOR_NOW+TIMERS.uncertainAfterMs});return h};it("shows a claimed chain end with no conclusion as uncertain once uncertainAfterMs passed",async()=>{await uncertainClaim();});it("writes a terminal that comes after the verdict to the audit list only, once",async()=>{const{subject,id,delegation:delegation2}=await uncertainClaim();await commit(subject,{kind:"abandon_delegation",delegationId:id});expect(await delegation2()).toMatchObject({verdict:"abandoned",lateTurnId:id});await subject.conclude(id,"cancelled","cancelled");await settled(subject,VECTOR_NOW+TIMERS.uncertainAfterMs,TIMERS);const state=await subject.state();expect(state.audit.filter(line=>line.includes(id))).toEqual([`Delegation terminal after verdict: ${id} ${taskId(id,0)}`]);expect(state.delegations[id]).not.toHaveProperty("lateTurnId");expect(state.delegations[id]).toMatchObject({verdict:"abandoned"});});for(const tried of [false,true]){it(`resolves a Main Bot cancel of ${tried?"a tried":"an untried"} target from a later owner Turn's outcome once the target concluded`,async()=>{const{subject,id,delegation:delegation2}=await delegated();if(tried)await subject.submit(id);await owner(subject,"r2",{cancel_delegation:[{delegationId:id}]});expect(await delegation2()).toMatchObject({cancel:{reason:"main_bot_cancelled",targetTurnId:id}});if(tried){const open2=await delegation2();expect(open2).not.toHaveProperty("verdict");expect(open2.status).not.toBe("uncertain");}await subject.conclude(id,"cancelled","cancelled");await settled(subject);expect(await delegation2()).toMatchObject({verdict:"cancelled",reason:"main_bot_cancelled",status:"resolved"});});}});}function replyVectors({describe,it,expect},name,open){describe(`reply check contract: ${name}`,()=>{const TIMERS={cancelGraceMs:1e3,uncertainAfterMs:5e3};const{settled,commit,delegated}=settlementSteps(expect,open);const pending=async()=>{const h=await delegated();await commit(h.subject,{kind:"outcome",turnId:h.id,taskId:taskId(h.id,0),document:{}});await h.subject.terminal(h.id,"task.complete",{document:{}});await h.subject.conclude(h.id,"succeeded");await settled(h.subject);expect(await h.delegation()).toMatchObject({status:"reply_pending",checks:0,nextCheckAt:VECTOR_NOW,pendingSince:VECTOR_NOW});const reads=[];const reader=readback=>async(...args)=>{reads.push(args);if(readback instanceof Error)throw readback;return readback};return {...h,reads,reader}};const projected=async h=>h.subject.projection(`delegation:${h.id}:${(await h.delegation()).revision}`);for(const[read,readback]of [["a pending read",{}],["a read that throws",new Error("down")]]){it(`answers a delegation whose reply body the Host holds, after ${read}`,async()=>{const h=await pending();await h.subject.change(state=>{state.replies[taskId(h.id,0)]={turnId:h.id,messageId:"m1",contentHash:"sha256:m1",contentType:"text/markdown",acceptedAt:VECTOR_NOW,body:"Done"};});await h.subject.checkReplies(VECTOR_NOW,h.reader(readback));expect(h.reads).toEqual([[taskId(h.id,0),"device",template("device","b").payload.agentRef]]);const d=await h.delegation();expect(d).toMatchObject({verdict:"answered",status:"resolved",reply:taskId(h.id,0),replyTurnId:hash(["bot_reply",h.id])});expect(d).not.toHaveProperty("nextCheckAt");expect(await projected(h)).toEqual([expect.objectContaining({status:"resolved",verdict:"answered"})]);});}for(const[read,readback]of [["no message",void 0],["a refused message",{disposition:{outcome:"refused"}}]]){it(`fails a delegation whose readback has ${read} (no_reply)`,async()=>{const h=await pending();await h.subject.checkReplies(VECTOR_NOW,h.reader(readback));expect(await h.delegation()).toMatchObject({verdict:"failed",reason:"no_reply",status:"resolved",replyTurnId:hash(["bot_reply",h.id])});});}it("holds a delegation whose message is held, with no verdict and no next check",async()=>{const h=await pending();await h.subject.checkReplies(VECTOR_NOW,h.reader({disposition:{outcome:"held"}}));const d=await h.delegation();expect(d.status).toBe("reply_held");expect(d).not.toHaveProperty("verdict");expect(d).not.toHaveProperty("nextCheckAt");expect(await projected(h)).toEqual([expect.objectContaining({status:"reply_held"})]);});it("checks a pending readback again with backoff, not before its time, and shows it as uncertain once uncertainAfterMs passed",async()=>{const h=await pending(),read=h.reader({});await h.subject.checkReplies(VECTOR_NOW,read,TIMERS);expect(await h.delegation()).toMatchObject({status:"reply_pending",checks:1,nextCheckAt:VECTOR_NOW+1e3});await h.subject.checkReplies(VECTOR_NOW+999,read,TIMERS);expect(h.reads).toHaveLength(1);await h.subject.checkReplies(VECTOR_NOW+1e3,read,TIMERS);expect(await h.delegation()).toMatchObject({status:"reply_pending",checks:2,nextCheckAt:VECTOR_NOW+3e3});await h.subject.checkReplies(VECTOR_NOW+TIMERS.uncertainAfterMs,read,TIMERS);const d=await h.delegation();expect(d).toMatchObject({status:"uncertain",uncertainSince:VECTOR_NOW+TIMERS.uncertainAfterMs,checks:3,nextCheckAt:VECTOR_NOW+TIMERS.uncertainAfterMs+4e3});expect(d).not.toHaveProperty("verdict");expect(h.reads).toHaveLength(3);});for(const[read,readback]of [["a read that throws",new Error("down")],["an accepted message with no Host record",{disposition:{outcome:"accepted"}}]]){it(`checks again after ${read}`,async()=>{const h=await pending();await h.subject.checkReplies(VECTOR_NOW,h.reader(readback));const d=await h.delegation();expect(d).toMatchObject({status:"reply_pending",checks:1,nextCheckAt:VECTOR_NOW+1e3});expect(d).not.toHaveProperty("verdict");});}});}var COALESCE_POLICY={windowMs:1e3,maxItems:2,maxBytes:8192};function coalesceVectors({describe,it,expect},name,open){describe(`coalesce contract: ${name}`,()=>{const user=key=>hash(["user","main",key]);const busy=async policy2=>{const subject=await open(policy2);await subject.change(state=>{Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.turns.q1={id:"q1",root:"q1",botId:"main",source:"user",request:"First",hop:0,status:"queued",authority:"owner"};});await subject.sync(VECTOR_NOW);return subject};const send=async(subject,key)=>{const result=await subject.commit({scope:subject.scope,commandId:key,command:input(key,`Say ${key}`)});expect(result.disposition.outcome).toBe("accepted");return result.disposition.value};const projected=(subject,batch,revision)=>subject.projection(`input-batch:${batch}:${revision}`);it("answers inputs to a busy Bot with one open batch, and projects its revision 1 at the next sync",async()=>{const subject=await busy(COALESCE_POLICY),batch=user("k1");expect([await send(subject,"k1"),await send(subject,"k2")]).toEqual([batch,batch]);const state=await subject.state();expect(state.turns[batch]).toBeUndefined();expect(state.inputBatches?.[batch]).toMatchObject({state:"open",inputIds:[batch,user("k2")],openedAt:VECTOR_NOW,sealAt:VECTOR_NOW+COALESCE_POLICY.windowMs});expect(await projected(subject,batch,1)).toEqual([]);await subject.sync(VECTOR_NOW);expect(await projected(subject,batch,1)).toEqual([expect.objectContaining({owner:"main",id:batch,revision:1,state:"open",inputIds:[batch,user("k2")],sealAt:VECTOR_NOW+COALESCE_POLICY.windowMs})]);expect(await projected(subject,batch,2)).toEqual([]);});it("seals the batch at the first sync at or after its window ends, and freezes its Turn in that sync",async()=>{const subject=await busy(COALESCE_POLICY),batch=user("k1");await send(subject,"k1");await send(subject,"k2");const request=(await subject.state()).inputBatches[batch].request;await subject.sync(VECTOR_NOW+COALESCE_POLICY.windowMs-1);expect((await subject.state()).inputBatches[batch].state).toBe("open");await subject.sync(VECTOR_NOW+COALESCE_POLICY.windowMs);const state=await subject.state();expect(state.inputBatches[batch]).toMatchObject({state:"sealed",sealReason:"window"});expect(state.turns[batch]).toMatchObject({source:"user",request,authority:"owner",inputIds:[batch,user("k2")]});expect(await subject.intent(batch)).toMatchObject({key:batch,source:"user"});expect(await projected(subject,batch,2)).toEqual([expect.objectContaining({id:batch,revision:2,state:"sealed",sealReason:"window"})]);const stored=await subject.stored();await subject.sync(VECTOR_NOW+COALESCE_POLICY.windowMs);expect(await subject.stored()).toBe(stored);});it("seals a full batch at the next input, so a batch sealed before any sync projects only revision 2",async()=>{const subject=await busy(COALESCE_POLICY),batch=user("k1");await send(subject,"k1");await send(subject,"k2");expect(await send(subject,"k3")).toBe(user("k3"));expect((await subject.state()).inputBatches[batch]).toMatchObject({state:"sealed",sealReason:"items"});await subject.sync(VECTOR_NOW);expect(await projected(subject,batch,1)).toEqual([]);expect(await projected(subject,batch,2)).toEqual([expect.objectContaining({id:batch,revision:2,sealReason:"items"})]);expect(await projected(subject,user("k3"),1)).toEqual([expect.objectContaining({id:user("k3"),revision:1,state:"open"})]);});it("seals an open batch as idle once its Bot has no open Turn",async()=>{const subject=await busy(COALESCE_POLICY),batch=user("k1");await send(subject,"k1");await subject.concludeIntent("q1","succeeded");await subject.sync(VECTOR_NOW);await subject.sync(VECTOR_NOW);const state=await subject.state();expect(state.turns.q1).toMatchObject({conclusion:"succeeded"});expect(state.inputBatches[batch]).toMatchObject({state:"sealed",sealReason:"idle"});expect(await subject.intent(batch)).toMatchObject({key:batch,source:"user"});});it("keeps one Turn for each input without a policy",async()=>{const subject=await busy(void 0);expect(await send(subject,"k1")).toBe(user("k1"));const state=await subject.state();expect(state.turns[user("k1")]).toMatchObject({source:"user",request:"Say k1"});expect(state.inputBatches).toBeUndefined();});});}function cardVectors({describe,it,expect},name,open){describe(`card contract: ${name}`,()=>{const result=hash(["action_result","c1"]);const opened=async expiresAt=>{const subject=await open();await subject.change(state=>{Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.cards.c1.expiresAt=expiresAt;});return subject};const decide=async(subject,decision)=>{const done=await subject.commit({scope:subject.scope,commandId:`decide-${decision}`,command:{kind:"decide",cardId:"c1",decision}});expect(done.disposition).toEqual({outcome:"accepted"});};it("expires a pending card before the Turn steps, projects it once, and starts no Turn for it",async()=>{const subject=await opened(VECTOR_NOW+10);await subject.sync(VECTOR_NOW+9);expect((await subject.state()).cards.c1).toMatchObject({state:"pending"});expect(await subject.projection("card:c1:expired")).toEqual([]);await subject.change(state2=>{state2.turns.q1={id:"q1",root:"q1",botId:"main",source:"user",request:"First",hop:0,status:"queued",authority:"owner"};});await subject.sync(VECTOR_NOW+10);const state=await subject.state();expect(state.cards.c1).toMatchObject({state:"expired",decisionReported:true});expect(await subject.projection("card:c1:expired")).toEqual([expect.objectContaining({id:"c1",state:"expired"})]);expect(state.turns[result]).toBeUndefined();const instruction=String((await subject.intent("q1")).execution.payload.instruction);expect(instruction).toContain(`"id":"c1","turnId":"t1",`);expect(instruction).toContain(`"state":"expired","expiresAt":${VECTOR_NOW+10}`);const before=await subject.stored();await subject.sync(VECTOR_NOW+10);expect(await subject.stored()).toBe(before);});it("reports a rejected card once, and runs its action_result Turn under the root of the card's Turn",async()=>{const subject=await opened(VECTOR_NOW+6e4);await decide(subject,"rejected");await subject.sync(VECTOR_NOW);await subject.sync(VECTOR_NOW);const state=await subject.state();expect(await subject.projection("card:c1:rejected")).toEqual([expect.objectContaining({id:"c1",state:"rejected"})]);expect(state.turns[result]).toMatchObject({id:result,root:"t1",source:"action_result",botId:"main",hop:0,authority:"owner",request:JSON.stringify({cardId:"c1",state:"rejected"})});expect(await subject.intent(result)).toMatchObject({key:result});const before=await subject.stored();await subject.sync(VECTOR_NOW);expect(await subject.stored()).toBe(before);});it("holds a confirmed card until its action has a result, then reports it with the result",async()=>{const subject=await opened(VECTOR_NOW+6e4);await decide(subject,"confirmed");await subject.sync(VECTOR_NOW);expect(await subject.projection("card:c1:confirmed")).toEqual([]);expect((await subject.state()).turns[result]).toBeUndefined();await subject.change(state=>{Object.assign(state.cards.c1,{result:{sent:true},conclusion:"succeeded"});});await subject.sync(VECTOR_NOW);expect(await subject.projection("card:c1:confirmed")).toEqual([expect.objectContaining({id:"c1",state:"confirmed",result:{sent:true}})]);expect((await subject.state()).turns[result]).toMatchObject({source:"action_result",request:JSON.stringify({cardId:"c1",state:"confirmed",conclusion:"succeeded",result:{sent:true}})});});});}function seedRoom(state){Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.cards.c1.expiresAt=Number.MAX_SAFE_INTEGER;state.team.bots.b={...state.team.bots.main,id:"b",name:"B",role:"Reviewer",mainBot:false,execution:template("device","b")};state.team.rooms.r={id:"r",...roomFields(state.team,{name:"Room",members:["main","b"]}),messages:[]};roomInput(state.team,"m1","r","Hello",["b","main"],noPublish);}function roomVectors({describe,it,expect},name,open){describe(`room contract: ${name}`,()=>{const opened=async()=>{const subject=await open();await subject.change(seedRoom);const round=Object.values((await subject.state()).team.rounds)[0];const seats=async()=>{const team=(await subject.state()).team;return round.seats.map(id=>team.seats[id])};return {subject,round,first:round.seats[0],second:round.seats[1],seats}};it("queues the first seat as a room_slot Turn with Bot authority, and freezes it in the same sync",async()=>{const{subject,round,first,second,seats}=await opened();await subject.sync(VECTOR_NOW);expect(await seats()).toMatchObject([{botId:"b",status:"queued",released:false,deadline:VECTOR_NOW+ROOM_GRACE_MS},{botId:"main",status:"waiting",released:false}]);const state=await subject.state();expect(state.turns[first]).toMatchObject({id:first,root:first,source:"room_slot",botId:"b",hop:0,authority:"bot",request:JSON.stringify({roomId:"r",roundId:round.id,request:"Hello",requestFrom:"user"})});expect(await subject.intent(first)).toMatchObject({key:first,source:"bot"});expect(state.turns[second]).toBeUndefined();const before=await subject.stored();await subject.sync(VECTOR_NOW);expect(await subject.stored()).toBe(before);});it("cancels an unclaimed seat at its deadline as busy, and queues the next seat",async()=>{const{subject,round,first,second,seats}=await opened(),deadline=VECTOR_NOW+ROOM_GRACE_MS;await subject.sync(VECTOR_NOW);await subject.sync(deadline-1);expect((await seats())[0]).toMatchObject({status:"queued",released:false});expect(await subject.cancelReason(first)).toBeUndefined();await subject.sync(deadline);expect(await seats()).toMatchObject([{status:"busy",released:true},{status:"queued",released:false,deadline:deadline+ROOM_GRACE_MS}]);expect(await subject.cancelReason(first)).toBe("cancelled");expect(await subject.projection(`room-seat:r:${first}`)).toEqual([{roomId:"r",root:round.id,roundId:round.id,seatId:first,botId:"b",status:"busy",late:false}]);expect(await subject.projection(`room-root:r:${round.id}`)).toEqual([]);expect((await subject.state()).turns[second]).toMatchObject({source:"room_slot",botId:"main",authority:"bot"});expect(await subject.intent(second)).toMatchObject({key:second,source:"bot"});});it("releases a claimed seat as late at its running deadline, with no cancel, and queues the next seat",async()=>{const{subject,first,seats}=await opened(),started=VECTOR_NOW+5;await subject.sync(VECTOR_NOW);await subject.claim(first);await subject.sync(started);expect((await seats())[0]).toMatchObject({status:"running",released:false,startedAt:started,deadline:started+ROOM_GRACE_MS});await subject.sync(started+ROOM_GRACE_MS);expect(await seats()).toMatchObject([{status:"late",late:true,released:true},{status:"queued",released:false}]);expect(await subject.cancelReason(first)).toBeUndefined();});it("releases a seat whose Turn concluded with no speech as failed, and queues the next seat",async()=>{const{subject,first,seats}=await opened();await subject.sync(VECTOR_NOW);await subject.concludeIntent(first,"failed");await subject.sync(VECTOR_NOW+1);expect(await seats()).toMatchObject([{status:"failed",released:true,reason:"failed"},{status:"queued",released:false}]);});it("removes the admitted seat of a Bot that left the room, cancels its work, and queues the next seat",async()=>{const{subject,first,second,seats}=await opened();await subject.sync(VECTOR_NOW);await subject.change(state=>{state.team.rooms.r.members=["main"];});await subject.sync(VECTOR_NOW+1);expect(await seats()).toMatchObject([{status:"removed",released:true},{status:"queued",released:false}]);expect(await subject.cancelReason(first)).toBe("cancelled");expect((await subject.state()).turns[second]).toMatchObject({source:"room_slot",botId:"main"});});it("runs the room step again when a Turn step releases a seat, so the next seat gets its Turn in the same sync",async()=>{const{subject,round,seats}=await opened();await subject.change(state=>{state.team.rooms.r.messages[0].text="x".repeat(7e4);});await subject.sync(VECTOR_NOW);expect(await seats()).toMatchObject([{status:"blocked",released:true},{status:"blocked",released:true}]);expect((await subject.state()).team.rounds[round.id]).toMatchObject({closed:true});for(const[seatId,botId]of [[round.seats[0],"b"],[round.seats[1],"main"]]){expect(await subject.projection(`room-seat:r:${seatId}`)).toEqual([expect.objectContaining({root:round.id,seatId,botId,status:"blocked"})]);}expect(await subject.projection(`room-root:r:${round.id}`)).toEqual([{roomId:"r",root:round.id,seats:round.seats}]);});it("fails the unadmitted seat Turn of a Bot that left the room with cancelled",async()=>{const{subject,second,seats}=await opened();await subject.change(state=>{state.turns[second]={id:second,root:second,source:"room_slot",request:"{}",botId:"main",hop:0,authority:"bot",status:"queued"};state.team.rooms.r.members=["b"];});await subject.sync(VECTOR_NOW);expect((await seats())[1]).toMatchObject({status:"removed",released:true});expect((await subject.state()).turns[second]).toMatchObject({status:"failed",conclusion:"cancelled"});expect(await subject.intent(second)).toBeUndefined();});});}function deviceVectors({describe,it,expect},name,open){describe(`device observation contract: ${name}`,()=>{const{settled,commit,delegated}=settlementSteps(expect,open);const offline=new Map([["device",false]]),online=new Map([["device",true]]);const opened=async()=>{const h=await delegated();const subject=h.subject;const projected=async()=>subject.projection(`delegation:${h.id}:${(await h.delegation()).revision}`);const unchanged=async devices=>{const before=await subject.stored();await subject.observeDevices(devices);expect(await subject.stored()).toBe(before);};return {...h,subject,projected,unchanged}};it("shows a delivered offer that no device claimed as waiting_device while its device is offline, and queued again once it connects",async()=>{const h=await opened();expect((await h.delegation()).status).toBe("queued");await h.subject.deliver(h.id,"offered");await h.subject.observeDevices(offline);expect((await h.delegation()).status).toBe("waiting_device");expect(await h.projected()).toEqual([expect.objectContaining({status:"waiting_device"})]);await h.unchanged(offline);await h.unchanged(new Map);await h.unchanged(new Map([["other",true]]));await h.subject.observeDevices(online);expect((await h.delegation()).status).toBe("queued");expect(await h.projected()).toEqual([expect.objectContaining({status:"queued"})]);});it("changes nothing before the offer is delivered: no submit, an uncertain submit, or a delivery with no attempt read",async()=>{const h=await opened();await h.unchanged(offline);await h.subject.submit(h.id);await h.unchanged(offline);await h.subject.deliver(h.id);await h.unchanged(offline);});it("changes nothing once a device claimed the offer, by its attempt or by the claim fact",async()=>{const h=await opened();await h.subject.deliver(h.id,"running");await h.unchanged(offline);await h.subject.deliver(h.id,"offered");await h.subject.claim(h.id);await settled(h.subject);expect((await h.delegation()).status).toBe("running");await h.unchanged(offline);});it("changes nothing for a delegation with a cancel or a verdict",async()=>{const cancelled=await opened();await cancelled.subject.deliver(cancelled.id,"offered");await commit(cancelled.subject,{kind:"cancel_delegation",delegationId:cancelled.id});expect((await cancelled.delegation()).cancel).toBeDefined();await cancelled.unchanged(offline);const failed=await opened();await failed.subject.deliver(failed.id,"offered");await failed.subject.observeDevices(offline);await failed.subject.conclude(failed.id,"failed");await settled(failed.subject);expect(await failed.delegation()).toMatchObject({verdict:"failed"});await failed.unchanged(online);});});}function cardCallVectors({describe,it,expect},name,open){describe(`card call contract: ${name}`,()=>{const result=hash(["action_result","c1"]);const opened=async()=>{const subject=await open();await subject.change(state=>{Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});state.cards.c1.expiresAt=VECTOR_NOW+6e4;});const decide=async decision=>{const done=await subject.commit({scope:subject.scope,commandId:`decide-${decision}`,command:{kind:"decide",cardId:"c1",decision}});expect(done.disposition).toEqual({outcome:"accepted"});await subject.sync(VECTOR_NOW);};const calls=[];const connector=value=>async(id,action,draft)=>{calls.push([id,action,draft]);if(value instanceof Error)throw value;return value};const unchanged=async step=>{const before=await subject.stored();await subject.callCards(step);expect(await subject.stored()).toBe(before);};return {subject,decide,calls,connector,unchanged}};it("calls the connector once for a confirmed card, writes its result, and the next sync reports it with its action_result Turn",async()=>{const h=await opened();await h.decide("confirmed");await h.subject.callCards(h.connector({sent:true}));expect(h.calls).toEqual([["c1","send_message",{text:"hi"}]]);expect((await h.subject.state()).cards.c1).toMatchObject({state:"confirmed",result:{sent:true},conclusion:"succeeded"});await h.unchanged(h.connector({sent:false}));expect(h.calls).toHaveLength(1);await h.subject.sync(VECTOR_NOW);expect(await h.subject.projection("card:c1:confirmed")).toEqual([expect.objectContaining({id:"c1",result:{sent:true}})]);expect((await h.subject.state()).turns[result]).toMatchObject({source:"action_result",request:JSON.stringify({cardId:"c1",state:"confirmed",conclusion:"succeeded",result:{sent:true}})});});it("writes a connector error, cut to 1024 characters, with a failed conclusion",async()=>{const h=await opened();await h.decide("confirmed");await h.subject.callCards(h.connector(new Error("x".repeat(2e3))));expect((await h.subject.state()).cards.c1).toMatchObject({error:"x".repeat(1024),conclusion:"failed"});expect((await h.subject.state()).cards.c1).not.toHaveProperty("result");await h.subject.sync(VECTOR_NOW);expect((await h.subject.state()).turns[result]).toMatchObject({source:"action_result",request:JSON.stringify({cardId:"c1",state:"confirmed",conclusion:"failed",error:"x".repeat(1024)})});});it("writes a result that is not JSON as an error",async()=>{const h=await opened();await h.decide("confirmed");await h.subject.callCards(h.connector(void 0));expect((await h.subject.state()).cards.c1).toMatchObject({error:expect.any(String),conclusion:"failed"});});it("calls nothing for a pending or a rejected card",async()=>{const h=await opened();await h.unchanged(h.connector({sent:true}));await h.decide("rejected");await h.unchanged(h.connector({sent:true}));expect(h.calls).toEqual([]);});});}function homeVectors({describe,it,expect},name,open){describe(`Agent home flush contract: ${name}`,()=>{const HOUR=36e5;const pendingBot=(state,bot)=>{state.team.bots[bot]={...state.team.bots.main,id:bot,name:bot,mainBot:false,revision:"2",readyRevision:"1",execution:template("device",bot)};const sequence=++state.sequence;state.team.homeOperations.push({sequence,botId:bot,status:"pending",retries:[],request:{deviceId:"device",payload:{requestId:projectionRequestId([bot,"2"]),agentRef:{agentId:bot,profileRevision:"2"},projectionHash:`sha256:${bot}`,projection:{schemaVersion:"bot-profile.v1",name:bot,role:"Member",persona:"",model:"default"}}}});return sequence};const opened=async()=>{const subject=await open();const sequences={};await subject.change(state=>{Object.assign(state.turns.t1,{status:"succeeded",conclusion:"succeeded",reported:true});for(const bot of ["b","c"])sequences[bot]=pendingBot(state,bot);});const operation=async(bot,index=0)=>(await subject.state()).team.homeOperations.filter(op=>op.botId===bot)[index];const reads=[],enqueued=[];const calls=(answer=()=>void 0)=>({read:async request=>{reads.push(request.payload.requestId);const value=answer(request);if(value instanceof Error)throw value;return value},enqueue:async request=>{enqueued.push(request.payload.requestId);}});const readback=(request,status)=>({deviceId:request.deviceId,agentRef:request.payload.agentRef,requestId:request.payload.requestId,projectionHash:request.payload.projectionHash,status});return {subject,sequences,operation,reads,enqueued,calls,readback}};for(const status of ["applied","idempotent"]){it(`applies an operation whose readback is ${status}, readies its Bot at that revision, and reads it no more`,async()=>{const h=await opened();await h.subject.flushHomes(VECTOR_NOW,h.calls(request=>h.readback(request,status)));expect(await h.operation("b")).toMatchObject({status:"applied"});expect((await h.subject.state()).team.bots.b).toMatchObject({revision:"2",readyRevision:"2"});expect(h.enqueued).toEqual([]);const reads=h.reads.length,before=await h.subject.stored();await h.subject.flushHomes(VECTOR_NOW+HOUR,h.calls(request=>h.readback(request,status)));expect(h.reads).toHaveLength(reads);expect(await h.subject.stored()).toBe(before);});}it("fails an operation whose readback is terminal and not applied, and publishes persona-failed",async()=>{const h=await opened();await h.subject.flushHomes(VECTOR_NOW,h.calls(request=>h.readback(request,"conflict")));expect(await h.operation("b")).toMatchObject({status:"failed",error:"conflict"});expect((await h.subject.state()).team.bots.b).toMatchObject({readyRevision:"1"});expect(await h.subject.projection(`persona-failed:${h.sequences.b}`)).toEqual([{owner:"b",revision:"2",reason:"conflict",recoverable:true}]);});it("keeps an operation pending with the error when a readback is for another request, and enqueues nothing",async()=>{const h=await opened();await h.subject.flushHomes(VECTOR_NOW,h.calls(request=>({...h.readback(request,"applied"),projectionHash:"sha256:other"})));expect(await h.operation("b")).toMatchObject({status:"pending",error:"Home readback identity conflict"});expect(h.enqueued).toEqual([]);});it("enqueues the first request with no terminal, then once retryAt has passed a retry with the next request id and a backoff",async()=>{const h=await opened();const first=(await h.operation("b")).request.payload.requestId;await h.subject.flushHomes(VECTOR_NOW,h.calls());expect(h.enqueued).toContain(first);expect(await h.operation("b")).toMatchObject({status:"pending",retries:[],retryAt:VECTOR_NOW+1e3});h.reads.length=0;h.enqueued.length=0;await h.subject.flushHomes(VECTOR_NOW+1e3,h.calls());const retry=projectionRequestId([first,1]);expect(await h.operation("b")).toMatchObject({retries:[{payload:{requestId:retry}}],retryAt:VECTOR_NOW+3e3});expect(h.reads.filter(id=>id===first||id===retry)).toEqual([first]);expect(h.enqueued.filter(id=>id===first||id===retry)).toEqual([retry]);await h.subject.flushHomes(VECTOR_NOW+HOUR,h.calls(request=>request.payload.requestId===first?h.readback(request,"applied"):void 0));expect(await h.operation("b")).toMatchObject({status:"applied"});});it("keeps an operation pending with the error when a read throws",async()=>{const h=await opened();await h.subject.flushHomes(VECTOR_NOW,h.calls(()=>new Error("home read down")));expect(await h.operation("b")).toMatchObject({status:"pending",error:"home read down"});});it("waits while a Bot has an intent with no conclusion, without blocking another Bot, and flushes it after the intent concludes",async()=>{const h=await opened();await h.subject.change(state=>{state.team.bots.b.readyRevision="2";});const turn=await h.subject.commit({scope:h.subject.scope,commandId:"busy-b",command:{kind:"input",botId:"b",key:"busy",request:"Work",sender:"owner"}});const turnId=turn.disposition.value;await h.subject.sync();expect(await h.subject.intent(turnId)).toBeDefined();await h.subject.flushHomes(VECTOR_NOW,h.calls(request=>h.readback(request,"applied")));expect(await h.operation("b")).toMatchObject({status:"pending"});expect(await h.operation("c")).toMatchObject({status:"applied"});expect(h.reads.filter(id=>id===projectionRequestId(["b","2"]))).toEqual([]);await h.subject.concludeIntent(turnId,"succeeded");await h.subject.flushHomes(VECTOR_NOW+HOUR,h.calls(request=>h.readback(request,"applied")));expect(await h.operation("b")).toMatchObject({status:"applied"});});it("reads no later operation of a Bot while its oldest pending one is not settled, and flushes it once that one settles",async()=>{const h=await opened();const second=projectionRequestId(["b","3"]);await h.subject.change(state=>{pendingBot(state,"b");state.team.homeOperations.at(-1).request.payload.requestId=second;});const first=(await h.operation("b",0)).request.payload.requestId;await h.subject.flushHomes(VECTOR_NOW,h.calls(request=>request.payload.requestId===second?h.readback(request,"applied"):void 0));expect(await h.operation("b",0)).toMatchObject({status:"pending"});expect(await h.operation("b",1)).toMatchObject({status:"pending"});expect(h.reads).not.toContain(second);await h.subject.flushHomes(VECTOR_NOW+HOUR,h.calls(request=>request.payload.requestId===first||request.payload.requestId===second?h.readback(request,"applied"):void 0));expect(await h.operation("b",0)).toMatchObject({status:"applied"});await h.subject.flushHomes(VECTOR_NOW+2*HOUR,h.calls(request=>h.readback(request,"applied")));expect(await h.operation("b",1)).toMatchObject({status:"applied"});});});}var FINAL_BODY="Final answer";var replyToken=key=>`secret-${key}`;var DIRECT={kind:"direct",id:"main"};var accepted=platformMessageId=>({result:"accepted",platformMessageId});function scripted(...results){const calls=[];const send=async input3=>{calls.push(structuredClone(input3));const result=results[Math.min(calls.length,results.length)-1];if(result==="hang")return new Promise(()=>{});if(result instanceof Error)throw result;return result};return {calls,send}}function deliveryVectors({describe,it,expect},name,open){describe(`delivery contract: ${name}`,()=>{it("1. sends a reply-route delivery once, with the token only in the route, and settles it accepted",async()=>{const port=scripted(accepted("p1")),subject=await open(port);await subject.publish("in1");await subject.drain();const[row]=await subject.deliveries();expect(row).toMatchObject({body:FINAL_BODY,channel:"fake",conversation:DIRECT,route:{kind:"reply",inboundId:inboundKey({channel:"fake",conversation:DIRECT,platformMessageId:"in1"})},state:"accepted",attempts:1,platformMessageId:"p1"});expect(port.calls).toEqual([{deliveryId:row.id,body:FINAL_BODY,route:{kind:"reply",channel:"fake",inboundId:"in1",token:replyToken("in1"),expiresAt:expect.any(Number)}}]);},6e4);it("2. backs a retryable rejection off by its wait, and the third attempt stops",async()=>{const port=scripted({result:"rejected",code:"429",retryable:true,retryAfterMs:5e3}),subject=await open(port);await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"pending",attempts:1,code:"429",nextAttemptAt:subject.now()+5e3}]);await subject.advance(4999);expect(port.calls).toHaveLength(1);await subject.advance(1);expect(port.calls).toHaveLength(2);await subject.advance(5e3);expect(port.calls).toHaveLength(3);expect(await subject.deliveries()).toMatchObject([{state:"rejected",attempts:3,code:"429"}]);await subject.advance(6e4);expect(port.calls).toHaveLength(3);},6e4);it("3. stops at a rejection that is not retryable",async()=>{const port=scripted({result:"rejected",code:"permission_denied",retryable:false}),subject=await open(port);await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"rejected",attempts:1,code:"permission_denied"}]);await subject.advance(12e4);expect(port.calls).toHaveLength(1);},6e4);it("4. rejects a retryable rejection whose wait is over 60 s",async()=>{const port=scripted({result:"rejected",code:"429",retryable:true,retryAfterMs:60001}),subject=await open(port);await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"rejected",attempts:1,code:"429"}]);await subject.advance(12e4);expect(port.calls).toHaveLength(1);},6e4);it.each([["send_timeout","hang"],["send_failed",new Error("connection lost after write")]])("5. leaves a send that ends in %s unknown, and never sends it again by itself",async(code,outcome)=>{const port=scripted(outcome),subject=await open(port);await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"unknown",attempts:1,code}]);await subject.advance(12e4);expect(port.calls).toHaveLength(1);},6e4);it.each(["accepted","absent"])("6. settles an unknown delivery from a readback of %s",async result=>{const port=scripted(new Error("receipt lost"),accepted("p2")),read=[];const subject=await open({send:port.send,readback:async id=>{read.push(id);return result}});await subject.publish("in1");await subject.drain();const[row]=await subject.deliveries();expect(read).toContain(row.id);expect(row).toMatchObject(result==="accepted"?{state:"accepted",attempts:1}:{state:"pending",attempts:1,nextAttemptAt:subject.now()+1e3});await subject.advance(1e3);expect(port.calls).toHaveLength(result==="absent"?2:1);expect(await subject.deliveries()).toMatchObject([{state:"accepted",attempts:result==="absent"?2:1}]);},6e4);it("7. turns a send claim that its Host never settled into unknown (interrupted), and sends it no more",async()=>{const port=scripted(accepted("late")),subject=await open(port);subject.crashOnNextSend();await subject.publish("in1");await subject.advance(subject.recoveryMs);expect(await subject.deliveries()).toMatchObject([{state:"unknown",attempts:1,code:"interrupted"}]);await subject.advance(12e4);expect(port.calls).toHaveLength(1);},6e4);it("8. refuses a pending reply after its route expired, and sends the push fallback",async()=>{const port=scripted({result:"rejected",code:"503",retryable:true,retryAfterMs:2e4},accepted("pushed"));const subject=await open(port),push=await subject.enablePush("direct-target");await subject.publish("in1",{replyMs:1e4});expect(port.calls.map(call=>call.route.kind)).toEqual(["reply"]);await subject.advance(2e4);await subject.drain();const rows=await subject.deliveries();expect(rows).toMatchObject([{route:{kind:"reply"},state:"rejected",attempts:1,code:"reply_route_expired"},{route:{kind:"push",pushRouteId:push},body:FINAL_BODY,state:"accepted",attempts:1,platformMessageId:"pushed"}]);expect(port.calls.map(call=>call.route.kind)).toEqual(["reply","push"]);expect(port.calls[1]).toMatchObject({deliveryId:rows[1].id,route:{kind:"push",id:push,target:"direct-target"}});},6e4);it("9. rejects the pending deliveries of a revoked push route",async()=>{const port=scripted({result:"rejected",code:"503",retryable:true,retryAfterMs:2e4});const subject=await open(port),push=await subject.enablePush("direct-target");await subject.publish("in1",{replyMs:null});expect(await subject.deliveries()).toMatchObject([{route:{kind:"push",pushRouteId:push},state:"pending",attempts:1}]);await subject.revokePush(push);expect(await subject.deliveries()).toMatchObject([{state:"rejected",attempts:1,code:"push_route_revoked"}]);await subject.advance(6e4);expect(port.calls).toHaveLength(1);},6e4);it("10. accepts an unknown delivery from a verified echo",async()=>{const port=scripted(new Error("receipt lost")),subject=await open(port);await subject.publish("in1");const[row]=await subject.deliveries();expect(row).toMatchObject({state:"unknown",attempts:1});await subject.echo(row.id,"echoed");expect(await subject.deliveries()).toMatchObject([{id:row.id,state:"accepted",attempts:1,platformMessageId:"echoed"}]);await subject.advance(12e4);expect(port.calls).toHaveLength(1);},6e4);it("11. gives a manual resend of an unknown delivery a new id, and sends it",async()=>{const port=scripted(new Error("receipt lost"),accepted("again")),reads=[];let absent=false;const subject=await open({send:port.send,readback:async id=>{reads.push(id);return absent?"absent":"unsupported"}});await subject.enablePush("direct-target");await subject.publish("in1",{replyMs:null});const[old]=await subject.deliveries();absent=true;const held=subject.holdNextReadback();await subject.advance(6e4);absent=false;await subject.advance(subject.recoveryMs);const next=await subject.resend(old.id);expect(next).not.toBe(old.id);const readCount=reads.length;await held.release();await subject.advance(6e4);await subject.advance(1e3);expect(await subject.deliveries()).toMatchObject([{id:old.id,state:"unknown",attempts:1},{id:next,resendOf:old.id,state:"accepted",attempts:1,platformMessageId:"again"}]);expect(port.calls.map(call=>call.deliveryId)).toEqual([old.id,next]);expect(reads).toHaveLength(readCount);},6e4);it("12. drops the stored reply token once its route expires",async()=>{const port=scripted({result:"rejected",code:"503",retryable:true,retryAfterMs:2e4}),subject=await open(port);await subject.publish("in1",{replyMs:1e4});expect(await subject.stored()).toContain(replyToken("in1"));await subject.advance(1e4);const inbound=Object.values((await subject.state()).channel.inbounds)[0];expect(inbound.reply).toBeDefined();expect(inbound.reply.token).toBeUndefined();expect(await subject.stored()).not.toContain(replyToken("in1"));},6e4);it("13. keeps the reply token out of every projection and every channel call field except the send route",async()=>{const port=scripted(new Error("receipt lost"),accepted("again")),read=[];const subject=await open({send:port.send,readback:async id=>{read.push(id);return "absent"}});await subject.publish("in1");await subject.drain();await subject.advance(1e3);expect(port.calls).toHaveLength(2);for(const call of port.calls){expect(call.route).toMatchObject({kind:"reply",token:replyToken("in1")});expect(JSON.stringify({...call,route:void 0})).not.toContain(replyToken("in1"));}expect(JSON.stringify(read)).not.toContain(replyToken("in1"));const projections=await subject.projections();expect(projections.length).toBeGreaterThan(0);expect(JSON.stringify(projections)).not.toContain(replyToken("in1"));},6e4);it("14. accepts a delivery from a verified echo that arrives while its send is held, and keeps the echo",async()=>{const port=scripted(accepted("sent")),subject=await open(port);const held=subject.holdNextSend();await subject.publish("in1");const[row]=await subject.deliveries();expect(row).toMatchObject({state:"sending",attempts:1});await subject.echo(row.id,"echoed");expect(await subject.deliveries()).toMatchObject([{id:row.id,state:"accepted",attempts:1,platformMessageId:"echoed"}]);await held.release();expect(await subject.deliveries()).toMatchObject([{id:row.id,state:"accepted",attempts:1,platformMessageId:"echoed"}]);expect(port.calls).toHaveLength(1);},6e4);it("15. ignores a held send that completes after another Host recovered its claim",async()=>{const port=scripted(accepted("late")),subject=await open(port);const held=subject.holdNextSend();await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"sending",attempts:1}]);await subject.advance(subject.recoveryMs);expect(await subject.deliveries()).toMatchObject([{state:"unknown",attempts:1,code:"interrupted"}]);await held.release();const[row]=await subject.deliveries();expect(row).toMatchObject({state:"unknown",attempts:1,code:"interrupted"});expect(row.platformMessageId).toBeUndefined();await subject.advance(12e4);expect(port.calls).toHaveLength(1);},6e4);it("16. drops the stored reply token once the delivery of its closed root settles",async()=>{const port=scripted(accepted("p1")),subject=await open(port);const held=subject.holdNextSend();await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"sending"}]);expect(await subject.stored()).toContain(replyToken("in1"));await held.release();expect(await subject.deliveries()).toMatchObject([{state:"accepted"}]);const inbound=Object.values((await subject.state()).channel.inbounds)[0];expect(inbound.reply).toMatchObject({inboundId:"in1"});expect(inbound.reply.token).toBeUndefined();expect(await subject.stored()).not.toContain(replyToken("in1"));},6e4);it("17. rejects an uncertain delivery whose readback is absent after its third attempt (attempts_exhausted)",async()=>{const port=scripted(new Error("receipt lost"));const subject=await open({send:port.send,readback:async()=>"absent"});await subject.publish("in1");await subject.drain();expect(await subject.deliveries()).toMatchObject([{state:"pending",attempts:1,nextAttemptAt:subject.now()+1e3}]);await subject.advance(1e3);await subject.drain();expect(await subject.deliveries()).toMatchObject([{state:"pending",attempts:2,nextAttemptAt:subject.now()+2e3}]);await subject.advance(2e3);await subject.drain();expect(await subject.deliveries()).toMatchObject([{state:"rejected",attempts:3,code:"attempts_exhausted"}]);await subject.advance(6e4);expect(port.calls).toHaveLength(3);},6e4);it("18. ignores a readback result for an earlier attempt that arrives after a later attempt went unknown",async()=>{const port=scripted(new Error("receipt lost"));let found="unsupported";const subject=await open({send:port.send,readback:async()=>found});await subject.publish("in1");expect(await subject.deliveries()).toMatchObject([{state:"unknown",attempts:1}]);found="absent";const held=subject.holdNextReadback();await subject.advance(6e4);await subject.advance(6e4);expect(await subject.deliveries()).toMatchObject([{state:"pending",attempts:1}]);found="unsupported";await subject.advance(1e3);expect(await subject.deliveries()).toMatchObject([{state:"unknown",attempts:2}]);await held.release();const[row]=await subject.deliveries();expect(row).toMatchObject({state:"unknown",attempts:2});expect(row.nextAttemptAt).toBeUndefined();await subject.advance(6e4);expect(port.calls).toHaveLength(2);},6e4);it("19. ignores a held send of attempt 1 that completes while attempt 2 is sending",async()=>{const port=scripted(accepted("late"),accepted("p2"));const subject=await open({send:port.send,readback:async()=>"absent"});const first=subject.holdNextSend();await subject.publish("in1");await subject.advance(subject.recoveryMs);expect(await subject.deliveries()).toMatchObject([{state:"pending",attempts:1}]);const second=subject.holdNextSend();await subject.advance(1e3);expect(await subject.deliveries()).toMatchObject([{state:"sending",attempts:2}]);await first.release();const[row]=await subject.deliveries();expect(row).toMatchObject({state:"sending",attempts:2});expect(row.platformMessageId).toBeUndefined();await second.release();expect(await subject.deliveries()).toMatchObject([{state:"accepted",attempts:2,platformMessageId:"p2"}]);expect(port.calls).toHaveLength(2);},6e4);});}async function submitResult(input3,outcome,signal){const server=input3.mcpServers?.byokagentresult;if(!server)throw new Error("result-document fixture did not receive byokagentresult");signal.throwIfAborted();const child=spawn(server.command,[...server.args??[]],{env:{...process.env,...server.env},stdio:["pipe","pipe","pipe"]});const lines=createInterface({input:child.stdout});let nextId=0;const pending=new Map;const ended=new Promise(resolve=>child.once("close",()=>resolve()));const abort=()=>{for(const request2 of pending.values())request2.reject(new Error("result helper closed"));pending.clear();};signal.addEventListener("abort",abort,{once:true});child.on("error",error=>{for(const request2 of pending.values())request2.reject(error);pending.clear();});child.on("exit",()=>{for(const request2 of pending.values())request2.reject(new Error("result helper exited before response"));pending.clear();});child.stderr.resume();lines.on("line",line=>{const response=JSON.parse(line);if(response.id===void 0)return;const request2=pending.get(response.id);if(!request2)return;pending.delete(response.id);if(response.error)request2.reject(new Error(response.error.message));else request2.resolve(response.result);});const request=(method,params)=>new Promise((resolve,reject)=>{signal.throwIfAborted();const id=++nextId;pending.set(id,{resolve,reject});child.stdin.write(JSON.stringify({jsonrpc:"2.0",id,method,params})+"\n");});try{await request("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"example-stub",version:"1"}});child.stdin.write(JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})+"\n");return await request("tools/call",{name:"submit_result",arguments:outcome})}finally{signal.removeEventListener("abort",abort);lines.close();try{child.kill("SIGKILL");}catch{}await ended;}}var ResultStubSession=class{constructor(input3){this.input=input3;}input;sessionRef=randomUUID();interrupted=false;closed=false;steered=0;followedUp=0;resultAbort=new AbortController;finishing=new Set;closing;pending=[];failure;wake;events={[Symbol.asyncIterator]:async function*(){while(!this.closed){if(this.failure)throw this.failure;const next=this.pending.shift();if(next){yield next;continue}await new Promise(resolve=>{this.wake=resolve;});}}.bind(this)};emit(event){this.pending.push(event);this.wake?.();this.wake=void 0;}finish(document,submit=true,text=JSON.stringify(document)){if(this.closed)return Promise.resolve();const finishing=(async()=>{if(submit&&this.input.mcpServers?.byokagentresult)await submitResult(this.input,document,this.resultAbort.signal);if(this.closed)return;this.emit({type:"progress",text});this.emit({type:"turn_end"});})().catch(error=>{if(!this.closed){this.failure=error;this.wake?.();this.wake=void 0;}}).finally(()=>{this.finishing.delete(finishing);});this.finishing.add(finishing);return finishing}fail(){this.failure=new Error("stub failed");this.wake?.();this.wake=void 0;}async steer(){this.steered+=1;}async followUp(){this.followedUp+=1;}async interrupt(){this.interrupted=true;}evidence(){return {decodeDropped:0,unmappedFrames:0,syntheticToolResults:0}}close(){if(this.closing)return this.closing;this.closed=true;this.wake?.();this.wake=void 0;this.resultAbort.abort();let timer;this.closing=Promise.race([Promise.all([...this.finishing]).then(()=>{}),new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new RuntimeDisposalFailure({stage:"quiescence",reason:"result helper did not close"})),1e3);})]).finally(()=>{clearTimeout(timer);this.closing=void 0;});return this.closing}};var ResultStubAdapter=class{descriptor=freezeRuntimeAdapterDescriptor({id:"pi",selectionModes:["device-default"],requiresMcpToolsetToolObservation:true,capabilities:{steer:false,resume:false,mcpToolsets:true,approvalInteractive:false}});sessions=new Map;starts=[];rejectNext=false;runtimeEnvironment(){return buildRuntimeEnvironment({base:"allowlist"})}async detect(){return {kind:"available",version:"0.0.0"}}async prepare(_input){if(this.rejectNext){this.rejectNext=false;return {kind:"reject",reason:"stub declined",retryable:true}}return {kind:"prepared",operation:{start:async input3=>{const session=new ResultStubSession(input3);this.starts.push(input3);this.sessions.set(input3.manifest.taskId,session);return session}}}}};async function waitForReady(daemon,timeoutMs=5e3){const deadline=Date.now()+timeoutMs;for(;;){const{lifecycle}=daemon.status();if(lifecycle.phase==="running"&&lifecycle.connection==="open")return;if(Date.now()>=deadline)throw new Error(`daemon not ready within ${timeoutMs} ms: ${JSON.stringify(lifecycle)}`);await new Promise(resolve=>setTimeout(resolve,25));}}async function openLTestHost(options){const deviceCredentials=options.deviceCredentials;if(deviceCredentials===void 0)throw new TypeError("openLTestHost requires deviceCredentials");const root=await mkdtemp(path.join(tmpdir(),"lth-"));const productId="host-core-test";const ledgerPath=path.join(root,"host.sqlite");const ledger=new HostLedger(ledgerPath,`product:${productId}`,options.ledgerOptions);const server=createByokServer({productId,storage:{kind:"sqlite",path:path.join(root,"server.sqlite")},longPollHoldMs:100,agentMessage:options.agentMessage,wake:{consume:options.consume}});const http=serve({fetch:server.hono.fetch,port:0,hostname:"127.0.0.1"});if(!http.listening)await new Promise(resolve=>http.once("listening",resolve));const address=http.address();if(!address||typeof address==="string")throw new Error("Missing HTTP address");const adapter=options.adapter??new ResultStubAdapter;const config={productId,productName:"Host Core",localAgentRelease:{version:"0.0.0-test"},serverUrl:`http://127.0.0.1:${address.port}`,storeDir:path.join(root,"sdk"),agentHome:{hostStorageRoot:path.join(root,"homes")},agentEgress:{policy}};const daemon=createDaemonWithAdapters(config,[adapter],{deviceCredentials});const pairing=await server.pairing.createPairingCode({productId});const{deviceId}=await daemon.pair(pairing.code);await daemon.start();await waitForReady(daemon);let closed=false;return {root,ledgerPath,server,ledger,deviceId,adapter,async close(){if(closed)return;closed=true;await daemon.stop();await server.close();ledger.close();await new Promise((resolve,reject)=>{http.close(error=>error?reject(error):resolve());if("closeAllConnections"in http)http.closeAllConnections();});await rm(root,{recursive:true,force:true});}}}var RETENTION_NOW=1e4;var LIMITS={contextTurnLimit:1,handoff:{recentBytes:200,earlyBytes:0,totalBytes:1024}};var input2=key=>({kind:"input",botId:"main",key,request:"Hello",sender:"owner"});function settledRoot(state,id){state.turns[id]={id,root:id,botId:"main",source:"user",request:id,hop:0,status:"succeeded",conclusion:"succeeded",reported:true,authority:"owner"};state.budgets[id]={continuation:0,delegation:0};state.questions[`${id}:q`]={id:`${id}:q`,turnId:id,value:{question:"Go?",answerKind:"text"},answer:"yes"};state.cards[`${id}:c`]={id:`${id}:c`,turnId:id,action:{action:"send_message",summary:"Send",draft:{text:"hi"}},state:"expired",expiresAt:0,decisionReported:true};state.rejected.push({botId:"main",taskId:`${id}:task`,action:"delegate",reason:"hop_limit",consumedBy:id});(state.wouldDo??={})[`${id}:w`]=wouldDo(`${id}:w`,id,"create_routine");}var wouldDo=(id,turnId,action)=>({id,botId:"main",turnId,taskId:`${turnId}:task`,action,index:0,at:0,detail:null});function clearSeed(state){delete state.turns.t1;delete state.budgets.t1;delete state.schemas.t1;delete state.questions.q1;delete state.cards.c1;}var settle2=async work=>work();var delegation=()=>({id:"d",root:"r1",fromBotId:"main",fromTurnId:"r1",fromTaskId:"r1:task",index:0,toBotId:"main",request:"",hop:1,chainTurnIds:[],batch:"b",status:"running",revision:0});var inputBatch=state=>({id:"r1",botId:"main",key:"k",inputIds:[],bytes:0,openedAt:0,sealAt:0,state,revision:2});function room(state,round,seat){state.team.rooms.room={id:"room",name:"Room",members:["main"],visibleFrom:{main:0},mode:"mention",announcement:"",messages:[]};state.team.rounds.round={id:"round",root:"r1",roomId:"room",input:"{}",seats:["seat"],limit:5,counts:{main:1},...round};state.team.seats.seat={id:"seat",roundId:"round",botId:"main",status:"post",late:false,...seat};}function delivery(state,row){state.replies["r1:task"]={turnId:"r1",messageId:"m",contentHash:"h",contentType:"text/markdown",acceptedAt:0};state.channel={inbounds:{},pushRoutes:{},deliveries:{x:{id:"x",taskId:"r1:task",turnId:"r1",messageId:"m",body:"b",conversation:{kind:"direct",id:"main"},channel:"fake",route:{kind:"push",pushRouteId:"p"},state:row,attempts:0}}};}function retentionVectors({describe,it,expect},name,open){describe(`retention contract: ${name}`,()=>{const request=(subject,commandId,command)=>({scope:subject.scope,commandId,command});const retain=(subject,roots,fields={},limits=LIMITS)=>settle2(()=>subject.retain({acknowledgedRoots:roots,now:RETENTION_NOW,retentionMs:MIN_TOMBSTONE_RETENTION_MS,...fields},limits));const refused=async(subject,run,check)=>{const before=await subject.stored();let error;try{await run();}catch(cause){error=cause;}check(error);expect(await subject.stored()).toBe(before);};const opened=async()=>{const subject=await open();await subject.change(state=>{clearSeed(state);settledRoot(state,"r1");settledRoot(state,"r2");});return subject};it("moves a settled root out of the state and counts a repeated root harmlessly",async()=>{const subject=await opened();const result=await retain(subject,["r1"]);expect(result).toMatchObject({archivedRoots:1,alreadyArchivedRoots:0});expect(result.archivedRows).toBeGreaterThanOrEqual(5);expect(result.afterBytes).toBeLessThan(result.beforeBytes);const state=await subject.state();expect(state.turns.r1).toBeUndefined();expect(state.budgets.r1).toBeUndefined();expect(state.questions["r1:q"]).toBeUndefined();expect(state.cards["r1:c"]).toBeUndefined();expect(state.rejected.map(row=>row.consumedBy)).toEqual(["r2"]);expect(Object.keys(state.wouldDo??{})).toEqual(["r2:w"]);expect(await subject.archived("wouldDo","r1:w")).toMatchObject({turnId:"r1"});expect(state.turns.r2).toBeDefined();expect(await retain(subject,["r1"])).toMatchObject({archivedRoots:0,alreadyArchivedRoots:1});});it("archives a replaced unknown delivery with its settled root",async()=>{const subject=await opened();await subject.change(state=>{delivery(state,"unknown");const old=state.channel.deliveries.x;state.channel.deliveries.replacement={...old,id:"replacement",state:"accepted",resendOf:old.id};});expect(await retain(subject,["r1"])).toMatchObject({archivedRoots:1});expect((await subject.state()).channel?.deliveries).toEqual({});expect(await subject.archived("deliveries","x")).toMatchObject({state:"unknown"});expect(await subject.archived("deliveries","replacement")).toMatchObject({state:"accepted",resendOf:"x"});});it("refuses a short retention, an unknown root and a room seat, and changes nothing",async()=>{const subject=await opened();await refused(subject,()=>retain(subject,["r1"],{retentionMs:MIN_TOMBSTONE_RETENTION_MS-1}),error=>expect(error.message).toBe("Retention must be at least seven days"));await refused(subject,()=>retain(subject,["r1","missing"]),error=>expect(error.message).toBe("Acknowledged root not found"));await subject.change(state=>{state.team.rooms.room={id:"room",name:"Room",members:["main"],visibleFrom:{main:0},mode:"mention",announcement:"",messages:[]};state.team.rounds.round={id:"round",root:"round",roomId:"room",input:"{}",seats:["seat"],limit:5,counts:{main:1},closed:true};state.team.seats.seat={id:"seat",roundId:"round",botId:"main",status:"post",released:true,late:false};});await refused(subject,()=>retain(subject,["seat"]),error=>{expect(error).toBeInstanceOf(RetentionRefused);expect(error).toMatchObject({code:"seat_root",root:"seat",roundRoot:"round",message:"Retention refused: The Turn is a room seat of root round"});});await subject.change(state=>{delete state.wouldDo["r1:w"].turnId;});await refused(subject,()=>retain(subject,["r2"]),error=>expect(error).toMatchObject({code:"would_do_unsupported_old"}));});it("refuses each root that is still in use, and changes nothing",async()=>{const cases=[["an open Turn",state=>{state.turns.r1.status="processing";delete state.turns.r1.conclusion;},"A Turn of the root is not concluded"],["an open question",state=>{delete state.questions["r1:q"].answer;},"A question of the root is unanswered"],["a pending card",state=>{state.cards["r1:c"].state="pending";},"A card of the root is not settled"],["an unreported card",state=>{delete state.cards["r1:c"].decisionReported;},"A card of the root is not settled"],["a delegation without a verdict",state=>{state.delegations.d=delegation();},"A delegation of the root is unresolved"],["a reserved unit",state=>{state.units.u={id:"u",root:"r1",state:"reserved"};},"A budget unit of the root is reserved"],["a late chain Turn",state=>{state.delegations.d={...delegation(),verdict:"answered",status:"resolved",lateTurnId:"late"};},"A delegation of the root is unresolved"],["an undelivered cancel",state=>{state.delegations.d={...delegation(),verdict:"cancelled",status:"resolved",cancel:{requestedAt:0,targetTurnId:"r1",delivered:false}};},"A delegation of the root is unresolved"],["an unreleased delegation batch",state=>{state.delegations.d={...delegation(),verdict:"answered",status:"resolved"};state.batches.b={id:"b",delegationIds:["d"],slots:[]};},"A delegation batch of the root is not released"],["an open input batch",state=>{state.inputBatches={r1:inputBatch("open")};},"The input batch of the root is not settled"],["an unprojected input batch",state=>{state.inputBatches={r1:{...inputBatch("sealed"),revision:1}};},"The input batch of the root is not settled"],["an open round",state=>{room(state,{closed:false},{released:true});},"A round of the root is open"],["an unreleased seat",state=>{room(state,{closed:true},{released:false});},"A room seat of the root is not released"],["a pending delivery",state=>{delivery(state,"pending");},"A delivery of the root is not settled"],["an unknown delivery",state=>{delivery(state,"unknown");},"A delivery of the root is not settled"],["a live reply route",state=>{state.channel={pushRoutes:{},deliveries:{},inbounds:{i:{id:"i",root:"r1",conversation:{kind:"direct",id:"main"},channel:"fake",sequence:1,reply:{kind:"reply",channel:"fake",inboundId:"i",token:"secret",expiresAt:RETENTION_NOW+1}}}};},"An inbound reply route of the root is live"],["the newest card",state=>{state.cards["r1:c2"]={...state.cards["r1:c"],id:"r1:c2"};},"The root is in the ContextPack window of its Bot"],["the newest question",state=>{state.questions["r1:q2"]={...state.questions["r1:q"],id:"r1:q2"};},"The root is in the ContextPack window of its Bot"],["the ContextPack window",()=>{},"The root is in the ContextPack window of its Bot",{...LIMITS,contextTurnLimit:2}],["a Turn older than the Turn limit but still in the pack",()=>{},"The root is in the ContextPack window of its Bot",{contextTurnLimit:1,handoff:{recentBytes:4096,earlyBytes:0,totalBytes:8192}}]];for(const[label,edit,reason,limits]of cases){const subject2=await opened();await subject2.change(edit);await refused(subject2,()=>retain(subject2,["r1"],{},limits??LIMITS),error=>{expect(error,label).toBeInstanceOf(RetentionRefused);expect(error.message,label).toBe(`Retention refused: ${reason}`);expect(error.code,label).toBe("protected_root");});}const subject=await opened();await refused(subject,()=>retain(subject,["r2"]),error=>expect(error.message).toBe("Retention refused: The root is in the ContextPack window of its Bot"));});it("keeps a seat speech delivery with its round root, though it has no reply record",async()=>{const subject=await opened();await subject.change(state2=>{room(state2,{closed:true},{released:true});state2.turns.seat={...state2.turns.r1,id:"seat",root:"seat",source:"room_slot"};state2.channel={inbounds:{},pushRoutes:{},deliveries:{s:{id:"s",taskId:"seat:task",turnId:"seat",messageId:"speech:seat",body:"b",conversation:{kind:"direct",id:"main"},channel:"fake",route:{kind:"push",pushRouteId:"p"},state:"pending",attempts:0}}};settledRoot(state2,"r3");state2.wouldDo["seat:w"]=wouldDo("seat:w","seat","room_call");});await refused(subject,()=>retain(subject,["r1"]),error=>expect(error.message).toBe("Retention refused: A delivery of the root is not settled"));await subject.change(state2=>{state2.channel.deliveries.s.state="accepted";});expect(await retain(subject,["r1"])).toMatchObject({archivedRoots:1});const state=await subject.state();expect(state.turns.seat).toBeUndefined();expect(state.channel.deliveries.s).toBeUndefined();expect(Object.keys(state.wouldDo??{}).sort()).toEqual(["r2:w","r3:w"]);});it("moves the room messages of archived roots outside the window, and keeps what each member sees",async()=>{const limits={...LIMITS,contextTurnLimit:2};const message=id=>({id,from:"main",text:id,late:false});const subject=await opened();await subject.change(state2=>{settledRoot(state2,"r3");room(state2,{closed:true},{released:true});Object.assign(state2.team.rooms.room,{members:["main","b"],visibleFrom:{main:1,b:4},messages:["old","round","live","seat","old2","old3"].map(message)});state2.team.rounds.live={id:"live",root:"live",roomId:"room",input:"{}",seats:["live:seat"],limit:5,counts:{main:1},closed:false};state2.team.seats["live:seat"]={id:"live:seat",roundId:"live",botId:"main",status:"queued",released:false,late:false};});const seen=state2=>{const{historyWindow:_window,...context}=roomContext(state2.team,{id:"live:seat"},limits.contextTurnLimit);return context};const before=seen(await subject.state());expect(await retain(subject,["r1"],{},limits)).toMatchObject({archivedRoots:1});const state=await subject.state();expect(state.team.rooms.room.messages.map(row=>row.id)).toEqual(["live","old2","old3"]);expect(state.team.rooms.room.visibleFrom).toEqual({main:0,b:1});expect(seen(state)).toEqual(before);for(const id of ["old","round","seat"])expect(await subject.archived("roomMessages",id),id).toEqual(message(id));expect(await subject.archived("roomMessages","live")).toBeUndefined();});it("replays a moved command record, and refuses a retired Turn id at admission until the end",async()=>{const subject=await opened();const first=await subject.commit(request(subject,"i1",input2("k1")));const turnId=hash(["user","main","k1"]);await subject.change(state=>{Object.assign(state.turns[turnId],{status:"succeeded",conclusion:"succeeded",reported:true});settledRoot(state,"r3");});expect(await retain(subject,[turnId])).toMatchObject({archivedRoots:1,archivedCommands:1});expect((await subject.state()).commands?.i1).toBeUndefined();expect(await subject.commit(request(subject,"i1",input2("k1")))).toEqual(first);for(let attempt=0;attempt<2;attempt++){await refused(subject,()=>settle2(()=>subject.commit(request(subject,"i2",input2("k1")))),error=>{expect(error).toBeInstanceOf(RetiredIdentityError);expect(error).toMatchObject({code:"retired_identity",namespace:"turn",id:turnId});});}expect(await retain(subject,[],{now:RETENTION_NOW+MIN_TOMBSTONE_RETENTION_MS})).toMatchObject({expiredCommands:1});await refused(subject,()=>settle2(()=>subject.commit(request(subject,"i1",input2("k1")))),error=>expect(error).toBeInstanceOf(RetiredIdentityError));});it("keeps the pack without the Turns that can still freeze, and not more",async()=>{const queued=status=>state=>{state.cards={};state.questions={};state.turns.q={id:"q",root:"q",botId:"main",source:"user",request:"later",hop:0,status,authority:"owner"};};for(const status of ["queued","blocked"]){const subject2=await opened();await subject2.change(queued(status));await refused(subject2,()=>retain(subject2,["r2"]),error=>expect(error.message,status).toBe("Retention refused: The root is in the ContextPack window of its Bot"));expect(await retain(subject2,["r1"])).toMatchObject({archivedRoots:1});}const subject=await opened();await subject.change(queued("processing"));expect(await retain(subject,["r2"])).toMatchObject({archivedRoots:1});});it("protects what a queued Turn reads when totalBytes is under recentBytes + earlyBytes",async()=>{const handoff={recentBytes:1e3,earlyBytes:1e3,totalBytes:1100};const subject=await opened();await subject.change(state=>{state.cards={};state.questions={};for(const[id,size]of [...Array.from({length:10},(_,n)=>[`a${n}`,100]),["big",3e3]]){settledRoot(state,id);state.cards={};state.questions={};state.turns[id].request="x".repeat(size);}for(const id of ["q1","q2"])state.turns[id]={id,root:id,botId:"main",source:"user",request:"later",hop:0,status:"queued",authority:"owner"};});await refused(subject,()=>retain(subject,["a9"],{},{contextTurnLimit:1,handoff}),error=>expect(error.message).toBe("Retention refused: The root is in the ContextPack window of its Bot"));expect(await retain(subject,["a0"],{},{contextTurnLimit:1,handoff})).toMatchObject({archivedRoots:1});});it("refuses the id of a retired batch member when it returns as a Turn",async()=>{const subject=await opened();const first=hash(["user","main","kx"]),member=hash(["user","main","ky"]);const row=(id,key)=>({id,key,botId:"main",request:key,bytes:2,sender:"owner",authority:"owner",receivedAt:0,batchId:first});await subject.change(state=>{settledRoot(state,first);state.turns[first].inputIds=[first,member];state.inputs={[first]:row(first,"kx"),[member]:row(member,"ky")};state.inputBatches={[first]:{...inputBatch("sealed"),id:first,key:"kx",inputIds:[first,member]}};settledRoot(state,"r3");});expect(await retain(subject,[first])).toMatchObject({archivedRoots:1});await refused(subject,()=>settle2(()=>subject.commit(request(subject,"iy",input2("ky")))),error=>{expect(error).toBeInstanceOf(RetiredIdentityError);expect(error).toMatchObject({code:"retired_identity",namespace:"turn",id:member});});});it("refuses a retired round id at admission",async()=>{const subject=await opened();await subject.change(state=>{state.team.rooms.room={id:"room",name:"Room",members:["main"],visibleFrom:{main:0},mode:"mention",announcement:"",messages:[]};});const command={kind:"room_input",key:"k1",roomId:"room",text:"Hello",mentions:[]};const round=(await subject.commit(request(subject,"ri1",command))).disposition;expect(round.outcome).toBe("accepted");const roundId=round.value;expect(await retain(subject,[roundId])).toMatchObject({archivedRoots:1});await refused(subject,()=>settle2(()=>subject.commit(request(subject,"ri2",command))),error=>{expect(error).toBeInstanceOf(RetiredIdentityError);expect(error).toMatchObject({namespace:"round",id:roundId});});});it("keeps the record of a command whose root is still in the state",async()=>{const subject=await opened();await subject.commit(request(subject,"i1",input2("k1")));await retain(subject,["r1"]);expect(Object.keys((await subject.state()).commands??{})).toEqual(["i1"]);});});}var PROMPT="Daily report";var settle3=async work=>work();function daily(now){return {minute:0,hour:(new Date(now).getUTCHours()+12)%24,tz:"UTC"}}var slotAfter=(schedule,after)=>nextRoutineOccurrence(schedule,after);var occurrenceKey=(id,version,kind,plannedAt)=>hash([id,version,{kind,plannedAt}]);var routineTurn=key=>`occurrence:${key}`;function routineVectors({describe,it,expect},name,open){describe(`routine contract: ${name}`,()=>{async function created(subject,key="plan",prompt=PROMPT){const schedule=daily(subject.now()),turn=await subject.input(key,"Plan a routine");await subject.start(turn);await subject.finish(turn,json({create_routine:[{localId:"new_routine_1",schedule,prompt}]}));return {id:hash([taskId(turn,0),"create_routine",0]),schedule,turn}}async function due(subject,id,late=0){const slot=(await settle3(()=>subject.routine(id))).nextAt;subject.at(slot+late);await subject.fire(id);return slot}const newest=async(subject,id)=>routineTurn((await settle3(()=>subject.occurrences(id))).at(-1).key);async function blocker(subject,key="hold"){const turn=await subject.input(key,"Hold the queue");await subject.start(turn);return turn}const hold=(subject,held)=>subject.change(state=>{state.team.bots.main.readyRevision=held?"held":state.team.bots.main.revision;});it("creates a routine through an outcome action, and the next Turn's frozen instruction lists it",async()=>{const subject=await open(),at=subject.now();const{id,schedule}=await created(subject);expect(await subject.routine(id)).toEqual({id,version:1,pending:null,lifecycle:"active",status:"ok",nextAt:slotAfter(schedule,at-1),calendarErrors:0});const next=await subject.input("next","What is planned?");const instruction=(await subject.intent(next)).instruction;expect(instruction).toContain(id);expect(instruction).toContain(PROMPT);},6e4);it("fires on time as scheduled and late as catch_up, with the K4 occurrence keys and the routine Turn",async()=>{const subject=await open(),{id,schedule}=await created(subject);const first=await due(subject,id,ROUTINE_LATE_AFTER_MS),firstAt=subject.now();await subject.start(await newest(subject,id));const second=await due(subject,id,ROUTINE_LATE_AFTER_MS+1),secondAt=subject.now();const[one,two]=[occurrenceKey(id,1,"scheduled",first),occurrenceKey(id,1,"catch_up",second)];expect(await subject.occurrences(id)).toEqual([{key:one,routineId:id,version:1,trigger:{kind:"scheduled",plannedAt:first},recordedAt:firstAt,nextAt:second,executionSuperseded:false,promoted:true,conclusion:null},{key:two,routineId:id,version:1,trigger:{kind:"catch_up",plannedAt:second},recordedAt:secondAt,nextAt:slotAfter(schedule,secondAt),executionSuperseded:false,promoted:true,conclusion:null}]);expect((await subject.state()).turns[routineTurn(two)]).toMatchObject({id:routineTurn(two),root:routineTurn(two),botId:"main",source:"routine",request:PROMPT,hop:0,authority:"owner",status:"processing"});expect(await subject.intent(routineTurn(two))).toMatchObject({key:routineTurn(two),source:"routine",waitUntil:secondAt+ROUTINE_WAIT_MS,retryUntil:slotAfter(schedule,secondAt),conclusion:null});expect((await subject.intent(routineTurn(two))).instruction).toContain(PROMPT);expect(await subject.routine(id)).toMatchObject({nextAt:slotAfter(schedule,secondAt),status:"ok"});},6e4);it("supersedes an untried promoted intent at a new slot, and keeps a running one with retry_until at the first later slot",async()=>{const subject=await open(),{id,schedule}=await created(subject);await due(subject,id);const running=await newest(subject,id);await subject.start(running);await due(subject,id);const untried=await newest(subject,id),second=subject.now();expect(await subject.intent(running)).toMatchObject({tried:true,retryUntil:second,conclusion:null});expect(await subject.intent(untried)).toMatchObject({tried:false,conclusion:null});await due(subject,id);const now=subject.now(),latest=await newest(subject,id);expect(await subject.intent(running)).toMatchObject({tried:true,retryUntil:second,conclusion:null});expect(await subject.intent(untried)).toMatchObject({tried:false,conclusion:"superseded"});expect(await subject.intent(latest)).toMatchObject({tried:false,retryUntil:slotAfter(schedule,now),conclusion:null});expect((await subject.occurrences(id)).map(row=>row.conclusion)).toEqual([null,"superseded",null]);const turns=(await subject.state()).turns;expect([running,untried,latest].map(turn=>[turns[turn].status,turns[turn].conclusion])).toEqual([["processing",void 0],["failed","superseded"],["processing",void 0]]);},6e4);it("marks an unpromoted occurrence executionSuperseded at a new slot, and its later promotion settles superseded",async()=>{const subject=await open(),{id,schedule}=await created(subject);await hold(subject,true);await due(subject,id);const stale=await newest(subject,id);await due(subject,id);const fresh=await newest(subject,id),now=subject.now();expect((await subject.occurrences(id)).map(row=>[row.promoted,row.executionSuperseded,row.conclusion])).toEqual([[false,true,null],[false,false,null]]);expect(await subject.intent(stale)).toBeUndefined();await hold(subject,false);await subject.sync();expect(await subject.intent(stale)).toMatchObject({source:"routine",conclusion:"superseded",tried:false});expect(await subject.intent(fresh)).toMatchObject({conclusion:null,retryUntil:slotAfter(schedule,now)});expect((await subject.occurrences(id)).map(row=>[row.promoted,row.conclusion])).toEqual([[true,"superseded"],[true,null]]);expect((await subject.state()).turns[stale]).toMatchObject({status:"failed",conclusion:"superseded"});},6e4);describe("stages a version while an occurrence is open, and switches when it concludes",()=>{async function switched(subject,id,schedule,conclude,conclusion){const turn=await newest(subject,id);await subject.update({routineId:id,prompt:"Version 2"});expect(await subject.routine(id)).toMatchObject({version:1,pending:2});await conclude(turn);expect((await subject.occurrences(id)).at(-1).conclusion).toBe(conclusion);expect(await subject.routine(id)).toMatchObject({version:2,pending:null,lifecycle:"active",nextAt:slotAfter(schedule,subject.now())});}it("after the routine Turn succeeds",async()=>{const subject=await open(),{id,schedule}=await created(subject);await due(subject,id);await subject.start(await newest(subject,id));await switched(subject,id,schedule,turn=>subject.finish(turn,{}),"succeeded");},6e4);it("after the owner cancels the queued routine Turn",async()=>{const subject=await open(),{id,schedule}=await created(subject);await blocker(subject);await due(subject,id);expect(await subject.intent(await newest(subject,id))).toMatchObject({tried:false,conclusion:null});await switched(subject,id,schedule,turn=>subject.cancelTurn(turn),"cancelled");},6e4);it("after the owner cancels the routine Turn before its promotion",async()=>{const subject=await open(),{id,schedule}=await created(subject);await hold(subject,true);await due(subject,id);await switched(subject,id,schedule,turn=>subject.cancelTurn(turn),"cancelled");expect((await subject.occurrences(id)).at(-1).promoted).toBe(false);},6e4);});it("pauses: removes the successor retry_until and the slot, then resumes on the current version",async()=>{const subject=await open(),{id,schedule}=await created(subject);const slot=await due(subject,id);const turn=await newest(subject,id);await subject.start(turn);expect(await subject.intent(turn)).toMatchObject({retryUntil:slotAfter(schedule,slot)});await subject.lifecycle(id,"paused");expect(await subject.routine(id)).toMatchObject({lifecycle:"paused",nextAt:null});expect(await subject.intent(turn)).toMatchObject({retryUntil:null,conclusion:null});await subject.lifecycle(id,"active");expect(await subject.routine(id)).toMatchObject({lifecycle:"active",version:1,nextAt:slotAfter(schedule,subject.now())});expect(await subject.intent(turn)).toMatchObject({retryUntil:null});await due(subject,id,1);expect(await subject.intent(turn)).toMatchObject({retryUntil:subject.now(),conclusion:null});},6e4);it("completes a routine through cancel_routine, and keeps at most eight open routines per owner",async()=>{const subject=await open(),ids=[];for(let n=0;n<8;n++)ids.push((await created(subject,`plan-${n}`)).id);const ninth=await created(subject,"plan-8");expect(await subject.routine(ninth.id)).toBeUndefined();expect((await subject.state()).rejected.at(-1)).toMatchObject({action:"create_routine",reason:"Routine limit is 8",taskId:taskId(ninth.turn,0)});const cancel=await subject.input("cancel","Stop the first routine");await subject.start(cancel);await subject.finish(cancel,{cancel_routine:[{routineId:ids[0]}]});expect(await subject.routine(ids[0])).toMatchObject({lifecycle:"completed",nextAt:null,pending:null});const tenth=await created(subject,"plan-9");expect(await subject.routine(tenth.id)).toMatchObject({lifecycle:"active",version:1});},12e4);it("ends a routine of an archived owner only with Main Bot authority, and the ended routine has no later slot",async()=>{const subject=await open(),at=subject.now();await subject.change(state=>{state.team.bots.helper={...structuredClone(state.team.bots.main),id:"helper",name:"Helper",mainBot:false};});const id=await subject.addRoutine("helper",daily(at)),slot=(await subject.routine(id)).nextAt;expect(await subject.reserved(id)).toEqual([slot]);await subject.change(state=>{archiveBot(state.team,"helper");});await expect(subject.lifecycle(id,"completed")).rejects.toThrow("Routine is unavailable to this Bot");await subject.change(state=>{state.team.bots.main.mainBot=false;});await expect(subject.end(id)).rejects.toThrow("Main Bot role required");expect(await subject.routine(id)).toMatchObject({lifecycle:"active",nextAt:slot});await subject.change(state=>{state.team.bots.main.mainBot=true;});await subject.end(id);expect(await subject.routine(id)).toEqual({id,version:1,pending:null,lifecycle:"completed",status:"ok",nextAt:null,calendarErrors:0});expect(await subject.reserved(id)).toEqual([]);await expect(subject.end(id)).rejects.toThrow("No open Bot routine has this id");},6e4);it("concludes the occurrence cancelled when its routine Turn is cancelled before promotion",async()=>{const subject=await open(),{id}=await created(subject);await hold(subject,true);await due(subject,id);const turn=await newest(subject,id);await subject.cancelTurn(turn);expect((await subject.occurrences(id)).map(row=>[row.promoted,row.conclusion])).toEqual([[false,"cancelled"]]);expect(await subject.intent(turn)).toBeUndefined();expect((await subject.state()).turns[turn]).toMatchObject({status:"failed",conclusion:"cancelled"});},6e4);it("refuses a slot whose routine Turn id retention retired, and records no occurrence",async()=>{const subject=await open(),id=await subject.addRoutine("main",daily(subject.now())),slot=(await subject.routine(id)).nextAt;await subject.retire(routineTurn(occurrenceKey(id,1,"scheduled",slot)));subject.at(slot);await expect(subject.fire(id)).rejects.toThrow(RetiredIdentityError);expect(await subject.occurrences(id)).toEqual([]);});});}
17
16
 
18
17
  export { FINAL_BODY, RETENTION_NOW, ResultStubAdapter, ResultStubSession, SYNC_OPTIONS, VECTOR_NOW, cardCallVectors, cardVectors, coalesceVectors, commitVectors, deliveryVectors, deviceVectors, homeVectors, openLTestHost, policy, replyToken, replyVectors, retentionVectors, roomVectors, routineVectors, seedCollaboration, seedRoom, settlementVectors, syncVectors, template };
19
18
  //# sourceMappingURL=testing.js.map