diff --git a/apps/app/test/account-stories.test.ts b/apps/app/test/account-stories.test.ts new file mode 100644 index 0000000000..ea98b5e8b9 --- /dev/null +++ b/apps/app/test/account-stories.test.ts @@ -0,0 +1,456 @@ +import { describe, expect, it } from "vitest"; +import * as Resident from "../gen/app__account.ts"; +import * as PlanChange from "../gen/app__account__change.ts"; +import * as GoogleLinks from "../gen/app__account__google.ts"; +import * as Outside from "../gen/app__account__outside.ts"; +import * as Plan from "../gen/app__account__plan.ts"; +import * as Provider from "../gen/app__account__provider.ts"; +import * as Records from "../gen/app__account__records.ts"; +import * as Session from "../gen/app__account__session.ts"; +import * as SignIn from "../gen/app__account__signIn.ts"; + +describe("Account story specifications", () => { + it('isolates plan changes per sign-in, marks interrupted attempts unknown on restart, and wipes on erase (spec/app/account/change.md, "Story: Keep plan changes to their sign-in")', () => { + const quotedReq = PlanChange.reviewChange(PlanChange.initial, "Pro", true, "Plus", 1, true, false); + const quoted = PlanChange.quoted(quotedReq.state, quotedReq.state.ticket, true, 2000, 50_000); + const settling = PlanChange.confirmChange(quoted.state, 10_000, true); + expect(settling.state.step).toBe("Settling"); + expect(settling.state.attempt.outcome).toBe("Sent"); + expect(PlanChange.inv(settling.state)).toBe(true); + + const restarted = PlanChange.restart(settling.state); + expect(restarted.state.step).toBe("Idle"); + expect(restarted.state.unsettled).toBe(true); + expect(restarted.state.notice).toBe("OutcomeUnknown"); + expect(restarted.out).toEqual([{ tag: "CheckPlan" }]); + expect(PlanChange.canReviewChange(restarted.state, "Pro", true, "Plus", 2, true, false)).toBe(false); + + const switched = PlanChange.reset(settling.state, 2); + expect(switched.step).toBe("Idle"); + expect(switched.unsettled).toBe(false); + expect(switched.notice).toBe("Quiet"); + expect(switched.attempt.outcome).not.toBe("Sent"); + expect(PlanChange.canConcluded(switched, settling.state.attempt.id)).toBe(false); + expect(PlanChange.inv(switched)).toBe(true); + + const erased = PlanChange.erase(settling.state); + expect(erased.step).toBe("Idle"); + expect(erased.unsettled).toBe(false); + expect(erased.notice).toBe("Quiet"); + expect(erased.attempt.id).toBe(settling.state.attempt.id + 1); + expect(PlanChange.canConcluded(erased, settling.state.attempt.id)).toBe(false); + expect(PlanChange.inv(erased)).toBe(true); + }); + + it('scopes Google links to the active sign-in, preserves links across restart, and forgets all on sign-out or erase (spec/app/account/google.md, "Story: Keep Google to its sign-in")', () => { + expect(GoogleLinks.lawSigningOutLeavesNoGoogle(true, true)).toBe(true); + expect(GoogleLinks.lawSigningOutLeavesNoGoogle(true, false)).toBe(true); + + const listed = GoogleLinks.listed( + GoogleLinks.refresh(GoogleLinks.initial, 1).state, + 1, + true, + [{ id: 1, read: true, modify: true, send: true }], + ); + expect(listed.state.links).toHaveLength(1); + expect(GoogleLinks.mayRead(listed.state, 1)).toBe(true); + + const visiting = GoogleLinks.connect(listed.state, true, true, true, 1, "ByOwner", 5_000); + expect(visiting.state.tab.open).toBe(true); + const oldTab = visiting.state.tab.number; + + const restartedSignedIn = GoogleLinks.restart(visiting.state, 1); + expect(restartedSignedIn.state.links).toHaveLength(1); + expect(restartedSignedIn.state.tab.open).toBe(false); + expect(restartedSignedIn.state.tab.orphan).toBe(true); + expect(restartedSignedIn.state.list.status).toBe("Loading"); + + const signedOut = GoogleLinks.reset(visiting.state, 0); + expect(signedOut.state.links).toEqual([]); + expect(signedOut.state.tab.open).toBe(false); + expect(signedOut.state.tab.number).toBe(oldTab); + expect(GoogleLinks.canReturned(signedOut.state, oldTab)).toBe(false); + expect(GoogleLinks.forgets(signedOut.out, 1)).toBe(true); + + const switchedSignIn = GoogleLinks.reset(listed.state, 2); + expect(switchedSignIn.state.links).toEqual([]); + expect(switchedSignIn.state.list.status).toBe("Loading"); + expect(GoogleLinks.forgets(switchedSignIn.out, 1)).toBe(true); + + const erased = GoogleLinks.erase(listed.state); + expect(erased.state.links).toEqual([]); + expect(GoogleLinks.forgets(erased.out, 1)).toBe(true); + expect(GoogleLinks.inv(erased.state)).toBe(true); + }); + + it('keeps the resident agent in review until kept records are archived or Alpha is erased (spec/app/account/index.md, "Story: Restart after a failure that kept records")', () => { + const booted = Resident.boot(Resident.initial, false); + const inReview = Resident.started(booted.state, booted.state.launch, "KeptRecords", 1_000); + expect(inReview.state.phase).toBe("Review"); + expect(inReview.out).toContainEqual({ tag: "Kept" }); + expect(Resident.seen(true, inReview.state)).toBe("SeenRecovering"); + expect(Resident.canStart(inReview.state, "ByOwner")).toBe(false); + expect(Resident.canCleared(inReview.state)).toBe(true); + + const archived = Resident.cleared(inReview.state); + expect(archived.state.phase).toBe("Starting"); + expect(archived.state.tries).toBe(0); + expect(Resident.launches(archived.out)).toBe(true); + expect(Resident.inv(archived.state)).toBe(true); + + const heldInReview = Resident.hold(inReview.state, "UpdatePause"); + expect(heldInReview.state.phase).toBe("Review"); + const archivedWhileHeld = Resident.cleared(heldInReview.state); + expect(archivedWhileHeld.state.phase).toBe("Down"); + expect(archivedWhileHeld.state.why).toBe("ForChange"); + expect(archivedWhileHeld.out).toEqual([]); + }); + + it('preserves review, update holds, and unconfirmed stops across reopen, clearing unconfirmed stops on reboot (spec/app/account/index.md, "Story: Reopen Alpha")', () => { + const booted = Resident.boot(Resident.initial, false); + const up = Resident.started(booted.state, booted.state.launch, "Came", 1_000); + const pausing = Resident.hold(up.state, "UpdatePause"); + expect(pausing.state.phase).toBe("Stopping"); + + const reopenedNoReboot = Resident.reopened(pausing.state, false); + expect(reopenedNoReboot.state.phase).toBe("Unstopped"); + expect(reopenedNoReboot.state.forUpdate).toBe(true); + expect(Resident.unbinds(reopenedNoReboot.out)).toBe(true); + + const reopenedAfterReboot = Resident.reopened(pausing.state, true); + expect(reopenedAfterReboot.state.phase).toBe("Down"); + expect(reopenedAfterReboot.state.forUpdate).toBe(true); + expect(Resident.unbinds(reopenedAfterReboot.out)).toBe(true); + + const inReview = Resident.started(booted.state, booted.state.launch, "KeptRecords", 2_000); + const reviewReopened = Resident.reopened(inReview.state, true); + expect(reviewReopened.state.phase).toBe("Review"); + expect(Resident.inv(reviewReopened.state)).toBe(true); + }); + + it('tracks browser visit numbers, single returns, timeouts, clock rollback, and orphaned restarts (spec/app/account/outside.md, "Story: Visit the browser and come back")', () => { + const first = Outside.go(Outside.novisit, 10_000); + expect(Outside.valid(first)).toBe(true); + expect(first).toEqual({ open: true, number: 1, orphan: false, at: 10_000 }); + expect(Outside.canReturn(first, 1)).toBe(true); + expect(Outside.canReturn(first, 2)).toBe(false); + + const returned = Outside.back(first); + expect(returned.open).toBe(false); + expect(Outside.canReturn(returned, 1)).toBe(false); + + const second = Outside.go(returned, 20_000); + expect(second.number).toBe(2); + expect(Outside.canReturn(second, 1)).toBe(false); + expect(Outside.overdue(second, 20_000 + 60_000, 60_000)).toBe(true); + expect(Outside.overdue(second, 19_999, 60_000)).toBe(true); + expect(Outside.overdue(second, 25_000, 60_000)).toBe(false); + + const orphan = Outside.orphaned(second); + expect(orphan.open).toBe(false); + expect(orphan.orphan).toBe(true); + expect(Outside.canReturnCold(orphan, 2)).toBe(true); + expect(Outside.canReturnCold(Outside.coldBack(orphan), 2)).toBe(false); + + expect(Outside.lawAVisitIsGivenUpInTime(1, 10_000, 60_000)).toBe(true); + expect(Outside.lawAReturnIsTakenOnce(1, 10_000)).toBe(true); + expect(Outside.lawAnOlderVisitIsNeverReturned(2, 1, 15_000)).toBe(true); + expect(Outside.lawVisitsStayWellFormed(true, 1, false, 10_000)).toBe(true); + }); + + it('retires in-flight reads so stale answers cannot alter state afterward (spec/app/account/outside.md, "Story: Stop waiting for an answer")', () => { + const retired = Outside.retire({ status: "Loading", ticket: 4 }); + expect(retired).toEqual({ status: "Failed", ticket: 4 }); + expect(Outside.retire({ status: "Loaded", ticket: 4 })).toEqual({ status: "Loaded", ticket: 4 }); + expect(Outside.lawARetiredReadTakesNoAnswer(0)).toBe(true); + expect(Outside.lawARetiredReadTakesNoAnswer(7)).toBe(true); + expect(Outside.lawTheAgentStartsNothingAndACardOnlyOpens("ByOwner")).toBe(true); + expect(Outside.lawTheAgentStartsNothingAndACardOnlyOpens("ByCard")).toBe(true); + expect(Outside.lawTheAgentStartsNothingAndACardOnlyOpens("ByAgent")).toBe(true); + }); + + it('turns Cloud AI off on a current sign-in billing refusal and gates the funding sheet accordingly (spec/app/account/plan.md, "Story: Add funds when Cloud refuses for billing")', () => { + expect(Plan.lawARefusalUnderAnEarlierSignInIsRefused("PaymentDeclined", 2)).toBe(true); + + const checking = Plan.reset(Plan.initial, 1, 1_000).state; + const member = Plan.checked(checking, checking.check.ticket, { + kind: "Signed", + tier: "Plus", + until: 500_000, + paidTo: 500_000, + ending: false, + revision: 1, + usage: 10, + }, 1, 2_000).state; + expect(Plan.aiOn(member)).toBe(true); + expect(Plan.canOpenFunding(member, 1, "ByOwner")).toBe(false); + + const refused = Plan.billingRefused(member, "AllowanceUsed", 1, 1); + expect(refused.state.standing).toBe("Declined"); + expect(refused.state.refusal).toBe("AllowanceUsed"); + expect(Plan.aiOn(refused.state)).toBe(false); + expect(Plan.canOpenFunding(refused.state, 1, "ByAgent")).toBe(false); + expect(Plan.canOpenFunding(refused.state, 1, "ByCard")).toBe(true); + + const fundingOpen = Plan.openFunding(refused.state, 1, "ByCard"); + expect(fundingOpen.funding).toBe(true); + expect(Plan.inv(fundingOpen)).toBe(true); + + const closed = Plan.closeFunding(fundingOpen); + expect(closed.funding).toBe(false); + + const admittedAgain = Plan.checked(fundingOpen, fundingOpen.check.ticket, { + kind: "Credits", + tier: "Plus", + until: 600_000, + paidTo: 0, + ending: false, + revision: 2, + usage: 10, + }, 1, 5_000).state; + expect(Plan.aiOn(admittedAgain)).toBe(true); + expect(admittedAgain.funding).toBe(false); + expect(Plan.inv(admittedAgain)).toBe(true); + }); + + it('shows Home AI-off notices once while uncovered and clears dismissal when notice meaning changes (spec/app/account/plan.md, "Story: Be told on Home when AI is off")', () => { + expect(Plan.lawACoveredHomeShowsNoNotice("Unfunded")).toBe(true); + expect(Plan.lawACoveredHomeShowsNoNotice("Grace")).toBe(true); + + const checking = Plan.reset(Plan.initial, 1, 1_000).state; + const unfunded = Plan.checked(checking, checking.check.ticket, { + kind: "NoPlan", + tier: "Plus", + until: 0, + paidTo: 0, + ending: false, + revision: 1, + usage: 0, + }, 1, 2_000).state; + + expect(Plan.homeNotice(unfunded)).toBe("NeedsPlan"); + expect(Plan.onHome(unfunded, false)).toBe(true); + expect(Plan.onHome(unfunded, true)).toBe(false); + expect(Plan.canDismissHomeNotice(unfunded)).toBe(true); + + const dismissed = Plan.dismissHomeNotice(unfunded); + expect(Plan.onHome(dismissed, false)).toBe(false); + expect(Plan.canDismissHomeNotice(dismissed)).toBe(false); + expect(Plan.inv(dismissed)).toBe(true); + + const grace = Plan.noted("Grace", dismissed); + expect(Plan.homeNotice(grace)).toBe("KeptOffline"); + expect(grace.dismissed).toBe("NoNotice"); + expect(Plan.onHome(grace, false)).toBe(true); + }); + + it('throttles visible rechecks to one minute while renewing expiring plans in the background (spec/app/account/plan.md, "Story: Keep my plan up to date")', () => { + expect(Plan.lawAHiddenAlphaIsNotRechecked(100_000, true)).toBe(true); + expect(Plan.lawAnAnswerRunningOutIsRenewedWhileHidden(100_000)).toBe(true); + + const checking = Plan.reset(Plan.initial, 1, 10_000).state; + const funded = Plan.checked(checking, checking.check.ticket, { + kind: "Signed", + tier: "Pro", + until: 200_000, + paidTo: 200_000, + ending: false, + revision: 1, + usage: 0, + }, 1, 10_000).state; + + expect(Plan.canRecheck(funded, 40_000, 1, true, true)).toBe(false); + expect(Plan.canRecheck(funded, 10_000 + Plan.recheckGap, 1, true, true)).toBe(true); + expect(Plan.canRecheck(funded, 10_000 + Plan.recheckGap, 1, false, true)).toBe(false); + + const rechecked = Plan.recheck(funded, 10_000 + Plan.recheckGap, 1, true, true); + expect(rechecked.state.check.status).toBe("Loading"); + expect(Plan.inv(rechecked.state)).toBe(true); + + expect(Plan.canRenew(funded, 200_000 - Plan.renewMargin - 1, 1)).toBe(false); + expect(Plan.canRenew(funded, 200_000 - Plan.renewMargin, 1)).toBe(true); + const renewed = Plan.renew(funded, 200_000 - Plan.renewMargin, 1); + expect(renewed.state.check.status).toBe("Loading"); + expect(Plan.inv(renewed.state)).toBe(true); + }); + + it('retains offline plan records across same-account restarts and wipes all state on erase (spec/app/account/plan.md, "Story: Keep my plan across a restart and an erase")', () => { + const checking = Plan.reset(Plan.initial, 1, 10_000).state; + const member = Plan.checked(checking, checking.check.ticket, { + kind: "Signed", + tier: "Plus", + until: 500_000, + paidTo: 500_000, + ending: false, + revision: 3, + usage: 42, + }, 1, 12_000).state; + expect(member.kept.signIn).toBe(1); + + const sameAccountRestart = Plan.restart(member, 1, 20_000); + expect(sameAccountRestart.state.standing).toBe("Checking"); + expect(sameAccountRestart.state.kept).toEqual(member.kept); + expect(sameAccountRestart.state.check.status).toBe("Loading"); + expect(Plan.inv(sameAccountRestart.state)).toBe(true); + + const otherAccountRestart = Plan.restart(member, 2, 20_000); + expect(otherAccountRestart.state.kept).toEqual(Plan.nobody); + + const erased = Plan.erase(member); + expect(erased.kept).toEqual(Plan.nobody); + expect(erased.dismissed).toBe("NoNotice"); + expect(Plan.canChecked(erased, sameAccountRestart.state.check.ticket, 1)).toBe(false); + expect(Plan.inv(erased)).toBe(true); + }); + + it('requires confirmation before switching between Cloud and own key and waits for active replies (spec/app/account/provider.md, "Story: Choose Cloud or my key")', () => { + expect(Provider.lawAChangeWaitsForAReplyInFlight("UseText")).toBe(true); + expect(Provider.lawAChangeWaitsForAReplyInFlight("UseCloud")).toBe(true); + + const asked = Provider.askReport(Provider.initial).state; + const reported = Provider.reported(asked, asked.report.ticket, true, "CloudAi", true, false, 1); + expect(Provider.canOffer(reported, "UseText", "ByAgent")).toBe(false); + expect(Provider.canOffer(reported, "UseText", "ByCard")).toBe(true); + + const offered = Provider.offer(reported, "UseText", "ByCard"); + expect(offered.choice.showing).toBe(true); + expect(Provider.canChoose(offered, true, "ByOwner", 5_000)).toBe(false); + expect(Provider.canChoose(offered, false, "ByCard", 5_000)).toBe(false); + expect(Provider.canChoose(offered, false, "ByOwner", 5_000)).toBe(true); + + const waiting = Provider.choose(offered, false, "ByOwner", 5_000); + expect(waiting.state.work).toBe("Waiting"); + expect(waiting.out).toEqual([{ tag: "HoldAgent" }]); + + const held = Provider.agentHeld(waiting.state, 6_000); + expect(held.state.work).toBe("Selecting"); + const selected = Provider.selected(held.state, held.state.ticket, true, 2); + expect(selected.state.mode).toBe("OwnKey"); + expect(Provider.ownKeyInUse(selected.state)).toBe(true); + expect(Provider.inv(selected.state)).toBe(true); + + const offeredCloud = Provider.offer(selected.state, "UseCloud", "ByOwner"); + const declined = Provider.decline(offeredCloud); + expect(declined.choice.showing).toBe(false); + expect(declined.mode).toBe("OwnKey"); + }); + + it('resets provider to undecided and flags interrupted changes on restart, clearing keys on erase (spec/app/account/provider.md, "Story: Restart or erase")', () => { + const asked = Provider.askReport(Provider.initial).state; + const reported = Provider.reported(asked, asked.report.ticket, true, "CloudAi", true, true, 1); + const offered = Provider.offer(reported, "UseText", "ByOwner"); + const waiting = Provider.choose(offered, false, "ByOwner", 3_000).state; + + const restarted = Provider.restart(waiting); + expect(restarted.state.mode).toBe("Undecided"); + expect(restarted.state.text).toBe(false); + expect(restarted.state.voice).toBe(false); + expect(restarted.state.trouble).toBe("Interrupted"); + expect(restarted.state.report.status).toBe("Loading"); + expect(Provider.inv(restarted.state)).toBe(true); + + const erased = Provider.erase(reported); + expect(erased.mode).toBe("Undecided"); + expect(erased.text).toBe(false); + expect(erased.voice).toBe(false); + expect(erased.work).toBe("Resting"); + expect(Provider.inv(erased)).toBe(true); + }); + + it('preserves unknown archive outcomes across app reopen and clears them only on a device reboot (spec/app/account/records.md, "Story: Reopen Alpha during a review")', () => { + expect(Records.lawAPhoneRestartEndsAnUnknownArchive(1, 2)).toBe(true); + + const opened = Records.opened(Records.initial).state; + const read = Records.recordsRead(opened, opened.review.ticket, true, 3); + const archiving = Records.archive(read, read.review.ticket, true, false).state; + + const sameBootReopen = Records.reopened(archiving, false, true); + expect(sameBootReopen.state.attempt.outcome).toBe("Unknown"); + expect(Records.phoneMustRestart(sameBootReopen.state)).toBe(true); + expect(sameBootReopen.state.review.status).toBe("Loading"); + const readSameBoot = Records.recordsRead(sameBootReopen.state, sameBootReopen.state.review.ticket, true, 3); + expect(Records.canArchive(readSameBoot, readSameBoot.review.ticket, true, false)).toBe(false); + + const withBoot = { ...readSameBoot, boot: 10 }; + const sameBootLaunch = Records.launched(withBoot, 10); + expect(sameBootLaunch.attempt.outcome).toBe("Unknown"); + + const rebootedLaunch = Records.launched(withBoot, 11); + expect(rebootedLaunch.boot).toBe(11); + expect(rebootedLaunch.attempt.outcome).toBe("Planned"); + expect(Records.inv(rebootedLaunch)).toBe(true); + }); + + it('clears the active sign-in, authority, notices, and in-flight work when Alpha is erased (spec/app/account/session.md, "Story: Erase Alpha")', () => { + const admitted = Session.admit(Session.initial, 7, "Email", true, false, 1_000).state; + const held = Session.agentHeld(admitted, 1_500).state; + const stored = Session.signInStored(held, held.ticket, true, false, 900_000, "https://cloud.example").state; + expect(stored.account).toBe(7); + expect(stored.created).toBe(true); + + const erased = Session.erase(stored); + expect(erased.account).toBe(0); + expect(erased.authority).toBe(""); + expect(erased.created).toBe(false); + expect(erased.known).toBe(true); + expect(erased.work).toBe("Resting"); + expect(Session.onHome(erased)).toBe(false); + expect(Session.inv(erased)).toBe(true); + }); + + it('offers email before method discovery finishes, blocks agent-initiated opens, and honors offline guards (spec/app/account/signIn.md, "Story: Choose how to sign in")', () => { + expect(SignIn.lawTheAgentOpensNoSignIn("ByAgent")).toBe(true); + expect(SignIn.lawEmailIsOfferedBeforeThePhoneAnswers(1)).toBe(true); + expect(SignIn.lawOfflineOffersNothingThatNeedsCloud("Email", "owner@example.test", 1_000)).toBe(true); + + expect(SignIn.canBegin(SignIn.initial, "ByAgent")).toBe(false); + const opened = SignIn.begin(SignIn.initial, "ByOwner"); + expect(opened.state.step).toBe("Choose"); + expect(SignIn.offered(opened.state, "Email")).toBe(true); + expect(SignIn.offered(opened.state, "Google")).toBe(false); + expect(SignIn.offered(opened.state, "Phone")).toBe(false); + + const ready = SignIn.methods(opened.state, opened.state.readiness.ticket, true, true, true); + expect(SignIn.offered(ready, "Google")).toBe(true); + expect(SignIn.offered(ready, "Phone")).toBe(true); + expect(SignIn.canSendCode(ready, "Email", "owner@example.test", 5_000, false)).toBe(false); + expect(SignIn.canSendCode(ready, "Email", "owner@example.test", 5_000, true)).toBe(true); + + const sending = SignIn.sendCode(ready, "Email", "owner@example.test", 5_000, true).state; + const atCode = SignIn.sent(sending, sending.ticket, true, 5_500); + expect(atCode.step).toBe("Code"); + expect(SignIn.inv(atCode)).toBe(true); + }); + + it('grants a fresh ten-minute window for TOTP or SMS second checks and returns to Choose on expiry (spec/app/account/signIn.md, "Story: Pass a second check")', () => { + expect(SignIn.lawASecondCheckHasItsOwnTenMinutes(10_000)).toBe(true); + + const verifying = { + ...SignIn.initial, + step: "Code" as const, + work: "Verifying" as const, + ticket: 3, + attempt: 1, + address: "owner@example.test", + expiresAt: 10_005, + }; + + const totpStep = SignIn.verified(verifying, 3, "NeedsSecond", 0, "Totp", true, 10_000).state; + expect(totpStep.step).toBe("Second"); + expect(totpStep.factor).toBe("Totp"); + expect(totpStep.expiresAt).toBe(10_000 + SignIn.secondLife); + expect(SignIn.inv(totpStep)).toBe(true); + + const smsStep = SignIn.verified(verifying, 3, "NeedsSecond", 0, "Sms", true, 10_000).state; + expect(smsStep.step).toBe("Second"); + expect(smsStep.factor).toBe("Sms"); + expect(SignIn.canCancel(smsStep)).toBe(true); + + expect(SignIn.canExpire(totpStep, totpStep.expiresAt - 1)).toBe(false); + expect(SignIn.canExpire(totpStep, totpStep.expiresAt)).toBe(true); + const expired = SignIn.expire(totpStep, totpStep.expiresAt); + expect(expired.step).toBe("Choose"); + expect(expired.trouble).toBe("TooLate"); + expect(SignIn.inv(expired)).toBe(true); + }); +}); diff --git a/apps/app/test/calendar-stories.test.ts b/apps/app/test/calendar-stories.test.ts new file mode 100644 index 0000000000..5e126caef7 --- /dev/null +++ b/apps/app/test/calendar-stories.test.ts @@ -0,0 +1,167 @@ +import { describe, expect, it } from "vitest"; +import * as Calendar from "../gen/app__calendar.ts"; +import * as AgentCalendar from "../gen/app__calendar__agent.ts"; +import * as Editor from "../gen/app__calendar__editor.ts"; +import * as ReminderReopen from "../gen/app__calendar__reminderReopen.ts"; +import * as Sharing from "../gen/app__calendar__sharing.ts"; +import * as Writing from "../gen/app__calendar__writing.ts"; + +describe("Calendar story specifications", () => { + it('allows the agent to read events and free time without approval cards while rejecting non-agent reads (spec/app/calendar/agent.md, "Story: Let the agent read my calendar")', () => { + expect(AgentCalendar.canRead(AgentCalendar.initial, "Owner")).toBe(false); + expect(AgentCalendar.canRead(AgentCalendar.initial, "World")).toBe(false); + expect(AgentCalendar.canRead(AgentCalendar.initial, "Agent")).toBe(true); + + const readEvents = AgentCalendar.read(AgentCalendar.initial, "Events", "Agent"); + expect(readEvents.state.stage).toBe("Idle"); + expect(readEvents.state.query).toBe("Events"); + expect(readEvents.state.feed.status).toBe("Loading"); + expect(readEvents.out).toEqual([{ tag: "Ask", ticket: readEvents.state.feed.ticket, query: "Events" }]); + const staleTicket = readEvents.state.feed.ticket; + expect(AgentCalendar.canRead(readEvents.state, "Agent")).toBe(true); + + const readFreeTime = AgentCalendar.read(readEvents.state, "FreeTime", "Agent"); + expect(readFreeTime.state.query).toBe("FreeTime"); + expect(readFreeTime.out).toEqual([{ tag: "Ask", ticket: readFreeTime.state.feed.ticket, query: "FreeTime" }]); + expect(AgentCalendar.canFeedAnswered(readFreeTime.state, staleTicket, "World")).toBe(false); + expect(AgentCalendar.canFeedAnswered(readFreeTime.state, readFreeTime.state.feed.ticket, "World")).toBe(true); + + const freeDone = AgentCalendar.feedAnswered(readFreeTime.state, readFreeTime.state.feed.ticket, true, "World"); + expect(freeDone.feed.status).toBe("Loaded"); + expect(freeDone.card.showing).toBe(false); + expect(AgentCalendar.inv(freeDone)).toBe(true); + }); + + it('keeps unreadable draft slots intact, avoids writing over them, and permits reset only in development builds (spec/app/calendar/editor.md, "Story: Recover a draft the phone cannot read")', () => { + expect(Editor.canSlotUnreadable(Editor.initial)).toBe(true); + const unreadable = Editor.slotUnreadable(Editor.initial); + expect(unreadable.unreadable).toBe(true); + expect(Editor.canResetSlot(unreadable, false)).toBe(false); + expect(Editor.canResetSlot(unreadable, true)).toBe(true); + + const blankFormOverCorrupt = Editor.newEvent(unreadable, 2).state; + const edited = Editor.editTitle(blankFormOverCorrupt, false); + expect(edited.kept).toBe(false); + expect(Editor.inv(edited)).toBe(true); + + const closed = Editor.close(edited); + const resetRequested = Editor.resetSlot(closed, true); + expect(resetRequested.out).toEqual([{ tag: "ResetSlot" }]); + + const failedReset = Editor.slotReset(resetRequested.state, false); + expect(failedReset.unreadable).toBe(true); + const succeededReset = Editor.slotReset(failedReset, true); + expect(succeededReset.unreadable).toBe(false); + expect(Editor.inv(succeededReset)).toBe(true); + }); + + // spec/app/calendar/editor.md, "Story: Keep each account's draft with that account" + it("closes the open draft editor when another owner signs in and isolates owner slots", () => { + const ownerOne = Editor.ownerChanged(Editor.initial, 1); + const opened = Editor.newEvent(ownerOne, 3).state; + const titled = Editor.editTitle(opened, false); + expect(titled.owner).toBe(1); + expect(titled.form).toBe("NewEvent"); + + expect(Editor.canOwnerChanged(titled, 1)).toBe(false); + expect(Editor.canOwnerChanged(titled, 2)).toBe(true); + const switched = Editor.ownerChanged(titled, 2); + expect(switched.owner).toBe(2); + expect(switched.form).toBe("NoForm"); + expect(switched.shown).toBe(false); + expect(switched.unreadable).toBe(false); + expect(Editor.inv(switched)).toBe(true); + + const saved = Editor.save(titled).state; + expect(Editor.inFlight(saved)).toBe(true); + expect(Editor.canOwnerChanged(saved, 2)).toBe(false); + }); + + it('opens Calendar on a tapped day in Timeline layout with overlays and open items cleared (spec/app/calendar/index.md, "Story: Open Calendar on the day I tapped")', () => { + const onAgenda = Calendar.chooseLayout(Calendar.initial, "Agenda").state; + const withOverlay = Calendar.openMonth(onAgenda); + expect(withOverlay.layout).toBe("Agenda"); + expect(withOverlay.overlay).toBe("MonthDialog"); + expect(Calendar.canOpenOn(withOverlay, 4)).toBe(true); + expect(Calendar.canOpenOn(withOverlay, -1)).toBe(false); + + const jumped = Calendar.openOn(withOverlay, 4); + expect(jumped.state.anchor).toBe(4); + expect(jumped.state.layout).toBe("Timeline"); + expect(jumped.state.overlay).toBe("NoOverlay"); + expect(jumped.state.open).toBe(0); + expect(jumped.state.reminder).toBe(0); + expect(Calendar.inv(jumped.state)).toBe(true); + }); + + it('holds one selected reminder in review, blocks expired confirmations, and submits only once (spec/app/calendar/reminderReopen.md, "Story: Review reopening the selected reminder without an alert")', () => { + expect(ReminderReopen.canOffer(ReminderReopen.initial, 1, "reminder-a", 1, 100, 100)).toBe(false); + expect(ReminderReopen.canOffer(ReminderReopen.initial, 1, "reminder-a", 1, 200, 50)).toBe(true); + + const offered = ReminderReopen.offer(ReminderReopen.initial, 1, "reminder-a", 1, 200, 50); + expect(offered.showing).toBe(true); + expect(ReminderReopen.canOffer(offered, 2, "reminder-b", 1, 200, 50)).toBe(false); + expect(ReminderReopen.canConfirm(offered, 200)).toBe(false); + expect(ReminderReopen.canConfirm(offered, 150)).toBe(true); + + const confirmed = ReminderReopen.confirm(offered, 150); + expect(confirmed.state.sending).toBe(true); + expect(confirmed.out).toEqual([{ + tag: "ApplyReopen", + id: 1, + reminderKey: "reminder-a", + revision: 1, + dueAt: 200, + attempt: 1, + }]); + expect(ReminderReopen.canConfirm(confirmed.state, 160)).toBe(false); + + const done = ReminderReopen.reopenAnswered(confirmed.state, 1); + expect(done.showing).toBe(false); + expect(done.sending).toBe(false); + expect(done.nextAttempt).toBe(2); + expect(ReminderReopen.inv(done)).toBe(true); + + const secondOffer = ReminderReopen.offer(done, 2, "reminder-b", 2, 250, 180); + const cancelled = ReminderReopen.cancel(secondOffer); + expect(cancelled.showing).toBe(false); + expect(ReminderReopen.inv(cancelled)).toBe(true); + }); + + it('permits agent-requested deletion only on the owner first matching Yes or exact Title reply (spec/app/calendar/sharing.md, "Story: Delete only after I said yes")', () => { + expect(Sharing.lawANoNeverDeletes(true, true)).toBe(true); + expect(Sharing.lawANoNeverDeletes(false, true)).toBe(true); + + expect(Sharing.deleteConfirmed(true, "Yes", true)).toBe(true); + expect(Sharing.deleteConfirmed(true, "Title", true)).toBe(true); + expect(Sharing.deleteConfirmed(true, "No", true)).toBe(false); + expect(Sharing.deleteConfirmed(true, "Question", true)).toBe(false); + expect(Sharing.deleteConfirmed(true, "Other", true)).toBe(false); + expect(Sharing.deleteConfirmed(false, "Yes", true)).toBe(false); + expect(Sharing.deleteConfirmed(true, "Yes", false)).toBe(false); + }); + + // spec/app/calendar/writing.md, "Story: Set an event's time with controls that never produce an impossible range" + it("clamps event start times inside the day, enforces positive durations, and sets safe default start hours", () => { + for (const minute of [0, 10, 600, 1430, 1439]) { + expect(Writing.lawStartStaysInTheDay(minute)).toBe(true); + } + expect(Writing.earlierStart(5)).toBe(0); + expect(Writing.laterStart(1430)).toBe(1439); + + expect(Writing.lawShorterEndStaysPositive(10)).toBe(true); + expect(Writing.shorterEnd(10)).toBe(1); + expect(Writing.longerEnd(30)).toBe(45); + + expect(Writing.lawDurationStaysPositive(540, 60, 500)).toBe(true); + expect(Writing.durationFor(540, 60, 500)).toBe(60); + expect(Writing.durationFor(540, 60, 540)).toBe(60); + expect(Writing.durationFor(540, 60, 630)).toBe(90); + + expect(Writing.lawDefaultStartIsAnHourOfADay(0, 14)).toBe(true); + expect(Writing.lawDefaultStartIsAnHourOfADay(0, 23)).toBe(true); + expect(Writing.lawDefaultStartIsAnHourOfADay(1, 14)).toBe(true); + expect(Writing.defaultStart(0, 14)).toEqual({ offset: 0, hour: 15 }); + expect(Writing.defaultStart(1, 14)).toEqual({ offset: 1, hour: 10 }); + }); +}); diff --git a/apps/app/test/inbox-stories.test.ts b/apps/app/test/inbox-stories.test.ts new file mode 100644 index 0000000000..cf92b94162 --- /dev/null +++ b/apps/app/test/inbox-stories.test.ts @@ -0,0 +1,256 @@ +import { describe, expect, it } from "vitest"; +import * as Mailbox from "../gen/app__inbox.ts"; +import * as Access from "../gen/app__inbox__access.ts"; +import * as Drafts from "../gen/app__inbox__drafts.ts"; +import * as Letter from "../gen/app__inbox__letter.ts"; +import * as Sending from "../gen/app__inbox__sending.ts"; +import * as Shelf from "../gen/app__inbox__shelf.ts"; + +const FULL_GRANT: Access.Grant = { read: true, send: true, modify: true }; +const READ_ONLY_GRANT: Access.Grant = { read: true, send: false, modify: false }; +const ACCOUNT_ONE: Access.Access = { account: 1, grant: FULL_GRANT }; +const DEFAULT_POLICY: Letter.Policy = { files: 5, mib: 25 }; + +describe("Inbox story specifications", () => { + it('enforces read prerequisite, separate send and change consents, and account scoping (spec/app/inbox/access.md, "Story: Do only what the grant allows")', () => { + const deeds: readonly Access.Deed[] = ["Reading", "Sending", "Changing"]; + const grants: readonly Access.Grant[] = [ + Access.noAccess, + READ_ONLY_GRANT, + { read: false, send: true, modify: true }, + { read: true, send: true, modify: false }, + { read: true, send: false, modify: true }, + FULL_GRANT, + ]; + for (const deed of deeds) { + expect(Access.lawNoAccessAllowsNothing(deed)).toBe(true); + for (const grant of grants) { + expect(Access.lawEveryDeedNeedsReading(grant, deed)).toBe(true); + expect(Access.lawSendingAndChangingAreSeparate(grant)).toBe(true); + expect(Access.lawAGrantIsNotLentToAnotherAccount({ account: 1, grant }, 2, deed)).toBe(true); + } + } + expect(Access.allows({ read: false, send: true, modify: true }, "Sending")).toBe(false); + expect(Access.allowsFor({ account: 1, grant: READ_ONLY_GRANT }, 1, "Reading")).toBe(true); + expect(Access.allowsFor({ account: 1, grant: READ_ONLY_GRANT }, 1, "Sending")).toBe(false); + expect(Access.allowsFor(ACCOUNT_ONE, 2, "Reading")).toBe(false); + }); + + it('distinguishes Owner, Agent, and World actors on inbox operation guards (spec/app/inbox/access.md, "Story: Tell who acts")', () => { + const readyLetter: Letter.Letter = { + ...Letter.blank, + id: 1, + account: 1, + recipients: 1, + revision: 1, + }; + const proposed = Sending.prepare(Sending.initial, "Send", ACCOUNT_ONE, readyLetter, true, false, "Agent"); + expect(Sending.canConfirm(proposed, 1, ACCOUNT_ONE, 1_000, "Agent")).toBe(false); + expect(Sending.canConfirm(proposed, 1, ACCOUNT_ONE, 1_000, "World")).toBe(false); + expect(Sending.canConfirm(proposed, 1, ACCOUNT_ONE, 1_000, "Owner")).toBe(true); + + const recorded = Sending.confirm(proposed, 1, ACCOUNT_ONE, 1_000, "Owner").state; + const dispatched = Sending.dispatchNow(recorded, ACCOUNT_ONE, 1, true, 1_500).state; + const unknownOutcome = Sending.replyLost(dispatched, dispatched.attempt.id).state; + expect(Sending.canReconciledDraft(unknownOutcome, "Send", 1, unknownOutcome.attempt.id, "Owner")).toBe(false); + expect(Sending.canReconciledDraft(unknownOutcome, "Send", 1, unknownOutcome.attempt.id, "Agent")).toBe(false); + expect(Sending.canReconciledDraft(unknownOutcome, "Send", 1, unknownOutcome.attempt.id, "World")).toBe(true); + }); + + it('checks an unknown send receipt once and updates or clears the draft based on receipt outcome (spec/app/inbox/drafts.md, "Story: Find out whether a send went")', () => { + const composed = Drafts.compose(Drafts.initial, "Fresh", 1, 0, false, true, 0, 0, true, DEFAULT_POLICY); + const withRecipient = Drafts.addRecipient(composed, 1_000, composed.letter.id, true); + const handed = Drafts.handedOver(withRecipient, withRecipient.letter.id, 1, "ToSend").state; + const flushedHand = Drafts.written(handed, handed.write.ticket, true, false).state; + const doubted = Drafts.ended(flushedHand, flushedHand.letter.id, 1, "Unknown", flushedHand.letter.revision, 0).state; + const settledDoubt = Drafts.written(doubted, doubted.write.ticket, true, false).state; + expect(settledDoubt.letter.doubt).toEqual({ attempt: 1, revision: flushedHand.letter.revision }); + + expect(Drafts.canCheckSent(settledDoubt, settledDoubt.letter.id, { account: 2, grant: FULL_GRANT })).toBe(false); + expect(Drafts.canCheckSent(settledDoubt, settledDoubt.letter.id, { account: 1, grant: READ_ONLY_GRANT })).toBe(true); + + const checking = Drafts.checkSent(settledDoubt, settledDoubt.letter.id, { account: 1, grant: READ_ONLY_GRANT }); + expect(checking.out).toEqual([{ + tag: "ReadSent", + ticket: checking.state.check.ticket, + draft: settledDoubt.letter.id, + account: 1, + attempt: 1, + }]); + expect(Drafts.canCheckSent(checking.state, settledDoubt.letter.id, ACCOUNT_ONE)).toBe(false); + + const rejected = Drafts.checkedSent(checking.state, checking.state.check.ticket, true, false).state; + expect(rejected.letter.doubt).toEqual(Letter.noDoubt); + expect(Drafts.canCheckSent(rejected, settledDoubt.letter.id, ACCOUNT_ONE)).toBe(false); + + const confirmed = Drafts.checkedSent(checking.state, checking.state.check.ticket, true, true).state; + expect(confirmed.open).toBe(false); + expect(Drafts.inv(confirmed)).toBe(true); + }); + + it('adopts earlier Alpha drafts onto the shelf and preserves send-status safety for unsettled records (spec/app/inbox/drafts.md, "Story: Keep the drafts the earlier Alpha kept")', () => { + expect(Drafts.lawWhatMayHaveLeftIsNeverCalledUnsent("Dispatching", "OutcomeUnknown", true)).toBe(true); + expect(Drafts.lawAnUnsettledRecordStaysUntilItsDraftCarriesIt("Dispatching", "OutcomeUnknown", true)).toBe(true); + expect(Drafts.beforeOf("Reviewing", "Prepared", false)).toBe("NotSent"); + expect(Drafts.beforeOf("Observed", "Succeeded", true)).toBe("SentAsIs"); + expect(Drafts.beforeOf("Observed", "Succeeded", false)).toBe("SentEarlier"); + expect(Drafts.beforeOf("Dispatching", "OutcomeUnknown", true)).toBe("MaybeSent"); + expect(Drafts.recordCleared("Dispatching", "OutcomeUnknown", true, false)).toBe(false); + expect(Drafts.recordCleared("Dispatching", "OutcomeUnknown", true, true)).toBe(true); + + expect(Drafts.canAdopt(Drafts.initial, 1, "Fresh", 1, 0, 0, 0, false, 7, "MaybeSent")).toBe(true); + const adopted = Drafts.adopt(Drafts.initial, 1, "Fresh", 1, 0, 0, 0, false, 7, "MaybeSent"); + expect(adopted.state.shelf.shelved).toHaveLength(1); + const draftId = adopted.state.shelf.shelved[0]; + const keptLetter = Shelf.held(adopted.state.shelf, draftId); + expect(Letter.mayHaveGone(keptLetter)).toBe(true); + expect(Drafts.inv(adopted.state)).toBe(true); + }); + + it('advances selection revisions on choose, unchoose, and select-all only against a fresh list (spec/app/inbox/index.md, "Story: Choose messages")', () => { + const signedIn = Mailbox.sessionChanged(Mailbox.initial, true).state; + const connected = Mailbox.accountsAnswered(signedIn, signedIn.accounts.ticket, true, [ + { account: 1, credential: 10, grant: FULL_GRANT }, + ]).state; + const listed = Mailbox.listed(connected, connected.list.ticket, true, "Fine", 2, 0, false, false, 2, 5_000).state; + + expect(Mailbox.canChoose(listed, 101)).toBe(true); + const oneChosen = Mailbox.choose(listed, 101); + expect(oneChosen.chosen).toContain(101); + expect(oneChosen.revision).toBe(listed.revision + 1); + + expect(Mailbox.canChooseAll(oneChosen, [101])).toBe(false); + expect(Mailbox.canChooseAll(oneChosen, [101, 102])).toBe(true); + const allChosen = Mailbox.chooseAll(oneChosen, [101, 102]); + expect(allChosen.chosen).toEqual([101, 102]); + expect(allChosen.revision).toBe(oneChosen.revision + 1); + + const unchecked = Mailbox.unchoose(allChosen, 101); + expect(unchecked.chosen).toEqual([102]); + expect(unchecked.revision).toBe(allChosen.revision + 1); + expect(Mailbox.inv(unchecked)).toBe(true); + }); + + it('reports accurate Home attention across signed-out, unconnected, fresh, stale, and unavailable states (spec/app/inbox/index.md, "Story: Tell Home what needs attention")', () => { + expect(Mailbox.attention(Mailbox.initial)).toEqual({ standing: "SignedOut", unread: 0, more: false, at: 0 }); + + const signedIn = Mailbox.sessionChanged(Mailbox.initial, true).state; + expect(Mailbox.attention(signedIn).standing).toBe("Checking"); + + const noAccounts = Mailbox.accountsAnswered(signedIn, signedIn.accounts.ticket, true, []).state; + expect(Mailbox.attention(noAccounts).standing).toBe("NotConnected"); + + const withAccount = Mailbox.accountsAnswered(signedIn, signedIn.accounts.ticket, true, [ + { account: 1, credential: 1, grant: FULL_GRANT }, + ]).state; + const freshList = Mailbox.listed(withAccount, withAccount.list.ticket, true, "Fine", 5, 1, false, false, 3, 9_000).state; + expect(Mailbox.attention(freshList)).toEqual({ standing: "Ready", unread: 3, more: true, at: 9_000 }); + + const failedRefresh = Mailbox.listed( + Mailbox.refresh(freshList).state, + freshList.list.ticket + 1, + false, + "Offline", + 0, + 0, + false, + false, + 0, + 10_000, + ).state; + expect(Mailbox.attention(failedRefresh)).toEqual({ standing: "Stale", unread: 3, more: true, at: 9_000 }); + + const firstFailed = Mailbox.listed(withAccount, withAccount.list.ticket, false, "Unreachable", 0, 0, false, false, 0, 9_000).state; + expect(Mailbox.attention(firstFailed).standing).toBe("Unavailable"); + expect(Mailbox.inv(failedRefresh)).toBe(true); + }); + + it('increments revision on every draft edit without altering attachments and restricts From-account moves to fresh unsynced drafts (spec/app/inbox/letter.md, "Story: Change a draft")', () => { + expect(Letter.lawEveryEditIsANewRevision(1, 0)).toBe(true); + expect(Letter.lawTextAddsNoAttachment(2, 4)).toBe(true); + expect(Letter.lawRepliesForwardsAndGmailDraftsKeepTheirAccount("Reply", 0)).toBe(true); + expect(Letter.lawRepliesForwardsAndGmailDraftsKeepTheirAccount("Forward", 0)).toBe(true); + expect(Letter.lawRepliesForwardsAndGmailDraftsKeepTheirAccount("Fresh", 9)).toBe(true); + + const fresh = Letter.begin(1, 1, "Fresh", 1, 0, false, 0, 0, true, DEFAULT_POLICY); + expect(Letter.canMove(fresh)).toBe(true); + const moved = Letter.movedTo(fresh, 2); + expect(moved.account).toBe(2); + expect(moved.revision).toBe(fresh.revision + 1); + + const edited = Letter.edited(moved); + expect(edited.revision).toBe(moved.revision + 1); + expect(edited.attachments).toBe(moved.attachments); + }); + + it('keeps edited sent drafts marked rather than forgetting them and resolves send doubts cleanly (spec/app/inbox/letter.md, "Story: Know what was sent")', () => { + expect(Letter.lawAnEditedDraftIsNotForgotten(2)).toBe(true); + expect(Letter.lawAFoundSendChangesTheDraft(3, 1)).toBe(true); + expect(Letter.lawOnlyAnEarlierDraftKnownUnsentIsFreeToSend("Fresh", 0, "NotSent")).toBe(true); + expect(Letter.lawOnlyAnEarlierDraftKnownUnsentIsFreeToSend("Fresh", 0, "MaybeSent")).toBe(true); + + const draft: Letter.Letter = { ...Letter.blank, id: 1, account: 1, revision: 2 }; + expect(Letter.forgettable(draft, 2)).toBe(true); + const editedAfterSend = Letter.edited(draft); + expect(Letter.forgettable(editedAfterSend, 2)).toBe(false); + + const sent = Letter.markedSent(editedAfterSend, 2); + expect(sent.sent).toBe(2); + expect(Letter.mayHaveGone(sent)).toBe(true); + + const inDoubt = Letter.doubted(draft, 5, 2); + expect(Letter.mayHaveGone(inDoubt)).toBe(true); + const clearedUnsent = Letter.notSent(inDoubt); + expect(Letter.mayHaveGone(clearedUnsent)).toBe(false); + const confirmedFound = Letter.foundSent(inDoubt); + expect(confirmedFound.sent).toBe(2); + expect(confirmedFound.revision).toBe(3); + }); + + it('forgets reviews and marks in-flight sends unknown on restart while withdrawing recorded sends on session change (spec/app/inbox/sending.md, "Story: Start over")', () => { + const letter: Letter.Letter = { ...Letter.blank, id: 1, account: 1, recipients: 1, revision: 1 }; + const prepared = Sending.prepare(Sending.initial, "Send", ACCOUNT_ONE, letter, true, false, "Owner"); + const confirmed = Sending.confirm(prepared, 1, ACCOUNT_ONE, 1_000, "Owner").state; + expect(confirmed.attempt.outcome).toBe("Recorded"); + + const switchedWhileRecorded = Sending.sessionChanged(confirmed); + expect(switchedWhileRecorded.session).toBe(confirmed.session + 1); + expect(switchedWhileRecorded.withdrawn).toBe(true); + expect(switchedWhileRecorded.review.showing).toBe(false); + expect(Sending.inv(switchedWhileRecorded)).toBe(true); + + const dispatched = Sending.dispatchNow(confirmed, ACCOUNT_ONE, 1, true, 1_500).state; + expect(dispatched.attempt.outcome).toBe("Sent"); + const restarted = Sending.restart(dispatched); + expect(restarted.state.review.showing).toBe(false); + expect(restarted.state.attempt.outcome).toBe("Unknown"); + expect(Sending.inv(restarted.state)).toBe(true); + }); + + it('preserves whole shelved drafts by id up to the shelf capacity and clears them on session change (spec/app/inbox/shelf.md, "Story: Keep drafts set aside")', () => { + expect(Shelf.lawADraftComesBackAsSetAside(2)).toBe(true); + + const first: Letter.Letter = { ...Letter.blank, id: 1, account: 1, recipients: 1, revision: 2 }; + const second: Letter.Letter = { ...Letter.blank, id: 2, account: 2, recipients: 2, invalid: 1, revision: 1 }; + expect(Shelf.whole(first)).toBe(true); + expect(Shelf.whole({ ...first, id: 0 })).toBe(false); + expect(Shelf.whole({ ...first, invalid: 2 })).toBe(false); + + const placedOne = Shelf.place(Shelf.initial, first); + const placedTwo = Shelf.place(placedOne, second); + expect(placedTwo.shelved).toEqual([1, 2]); + expect(Shelf.held(placedTwo, 1)).toEqual(first); + + const amended = Shelf.amend(placedTwo, { ...first, sent: 2 }); + expect(Shelf.held(amended, 1).sent).toBe(2); + + const taken = Shelf.take(amended, 1); + expect(taken.shelved).toEqual([2]); + + const nextSession = Shelf.sessionChanged(taken); + expect(nextSession.shelved).toEqual([]); + expect(nextSession.letters).toEqual({}); + expect(Shelf.room).toBe(50); + expect(Shelf.inv(nextSession)).toBe(true); + }); +}); diff --git a/emulators/manifest.json b/emulators/manifest.json index 677e16bed0..fcc0ca45ae 100644 --- a/emulators/manifest.json +++ b/emulators/manifest.json @@ -4,15 +4,15 @@ { "service": "anthropic", "kind": "llm", - "provider": "canned-fixture", + "provider": "vibestack-custom", "baseUrlEnv": "ANTHROPIC_BASE_URL", "docsUrl": "https://docs.anthropic.com/en/api/messages", "files": [ - "apps/app/src/account/ProviderView.tsx" + "packages/eliza-harness/src/providers/anthropic-provider.ts" ], "status": "unverified", - "contractHash": "ac3f751f4181f206683562384fbadad7c26a856ab0c1f49cd06482eb139a7006", - "notes": "BYOK Anthropic Messages API preset configured in ProviderView. Unverified against live Anthropic API; no dedicated /v1/messages emulator verified live yet." + "contractHash": "f57335e903d8eb417bbdefa557368a7db629eb5a2f7cd924d7426a9b74fcd13a", + "notes": "Stateful loopback Anthropic Messages API emulator built on vibestack/emulate (/v1/messages JSON + SSE streaming, tool_use, /v1/messages/count_tokens, /v1/models, x-vibestack-namespace isolation, FaultArmory 429/529, /__control/script). Pending live Anthropic parity capture." }, { "service": "cartesia", diff --git a/packages/eliza-harness/src/index.ts b/packages/eliza-harness/src/index.ts index d398e3aa7d..61e6078f64 100644 --- a/packages/eliza-harness/src/index.ts +++ b/packages/eliza-harness/src/index.ts @@ -2,6 +2,17 @@ export { checkout, link, prepare, prepared, required } from "./checkout.ts"; export { owned } from "./owned.ts"; export { isAlphaPackManifest, packCheckout, packWorkerDir, packagedWorkflowWorker } from "./pack.ts"; export { NotBuilt, PackNotPrepared, pinnedCheckout, pinnedPack } from "./pinned.vibe"; +export { + DEFAULT_ANTHROPIC_MODELS, + DEFAULT_ANTHROPIC_VERSION, + type AnthropicContentBlock, + type AnthropicModel, + type AnthropicProviderOptions, + type AnthropicScriptedReply, + type RecordedAnthropicMessage, + type RunningAnthropicProvider, + startAnthropicProvider, +} from "./providers/anthropic-provider.ts"; export { DEFAULT_CARTESIA_VOICE_ID, type CartesiaVoice, diff --git a/packages/eliza-harness/src/providers/anthropic-provider.ts b/packages/eliza-harness/src/providers/anthropic-provider.ts new file mode 100644 index 0000000000..d3ffc0fe63 --- /dev/null +++ b/packages/eliza-harness/src/providers/anthropic-provider.ts @@ -0,0 +1,597 @@ +import type { IncomingHttpHeaders, ServerResponse } from "node:http"; +import { + type EmulatorContext, + type FaultRule, + type ParsedRequest, + asBoolean, + asNumber, + asRecord, + asString, + createEmulatorServer, + randomToken, + sendJson, +} from "vibestack/emulate"; + +function asArray(value: unknown): unknown[] | undefined { + return Array.isArray(value) ? value : undefined; +} + +/** Default `anthropic-version` header accepted by the Anthropic Messages API. */ +export const DEFAULT_ANTHROPIC_VERSION = "2023-06-01"; + +/** Anthropic model metadata returned by `GET /v1/models` and `GET /v1/models/:id`. */ +export interface AnthropicModel { + readonly id: string; + readonly type: "model"; + readonly display_name: string; + readonly created_at: string; +} + +/** Seeded Claude models advertised by the local Anthropic emulator. */ +export const DEFAULT_ANTHROPIC_MODELS: readonly AnthropicModel[] = [ + { + id: "claude-sonnet-4-6", + type: "model", + display_name: "Claude Sonnet 4.6", + created_at: "2026-02-17T00:00:00Z", + }, + { + id: "claude-opus-4-6", + type: "model", + display_name: "Claude Opus 4.6", + created_at: "2026-02-05T00:00:00Z", + }, + { + id: "claude-haiku-4-5-20251001", + type: "model", + display_name: "Claude Haiku 4.5", + created_at: "2025-10-01T00:00:00Z", + }, +]; + +/** Content block returned inside an Anthropic Messages response. */ +export type AnthropicContentBlock = + | { readonly type: "text"; readonly text: string } + | { + readonly type: "tool_use"; + readonly id: string; + readonly name: string; + readonly input: Record; + }; + +/** Scripted turn queued via `POST /__control/script` or `defaultReplies`. */ +export type AnthropicScriptedReply = + | { readonly kind: "text"; readonly text: string; readonly stopReason?: "end_turn" | "max_tokens" } + | { + readonly kind: "tool_use"; + readonly id?: string; + readonly name: string; + readonly input: Record; + readonly text?: string; + } + | { + readonly kind: "blocks"; + readonly content: readonly AnthropicContentBlock[]; + readonly stopReason?: "end_turn" | "tool_use" | "max_tokens"; + } + | { + readonly kind: "error"; + readonly status: number; + readonly errorType: string; + readonly message: string; + readonly retryAfter?: number; + }; + +/** Recorded `POST /v1/messages` request held in emulator state for inspection. */ +export interface RecordedAnthropicMessage { + readonly seq: number; + readonly id: string; + readonly model: string; + readonly stream: boolean; + readonly maxTokens: number; + readonly system?: string; + readonly messageCount: number; + readonly toolNames: readonly string[]; + readonly lastUserText: string; + readonly stopReason: string; +} + +/** Startup configuration for {@link startAnthropicProvider}. */ +export interface AnthropicProviderOptions { + readonly port?: number; + readonly stateFile?: string; + readonly apiKey?: string; + readonly models?: readonly AnthropicModel[]; + readonly defaultReplies?: readonly AnthropicScriptedReply[]; +} + +/** Running loopback Anthropic Messages API emulator handle. */ +export interface RunningAnthropicProvider { + readonly origin: string; + readonly port: number; + readonly apiKey: string; + stop(): Promise; +} + +interface AnthropicState { + seq: number; + readonly models: AnthropicModel[]; + readonly queue: AnthropicScriptedReply[]; + readonly recorded: RecordedAnthropicMessage[]; +} + +const MAX_RECORDED = 200; + +function sendAnthropicError( + res: ServerResponse, + status: number, + errorType: string, + message: string, + retryAfter?: number, +): void { + const headers: Record = {}; + if (retryAfter !== undefined && Number.isFinite(retryAfter) && retryAfter >= 0) { + headers["retry-after"] = String(Math.ceil(retryAfter)); + } + sendJson( + res, + status, + { type: "error", error: { type: errorType, message } }, + headers, + ); +} + +function defaultAnthropicFaultBody(fault: FaultRule): unknown { + if (fault.status === 429) { + return { + type: "error", + error: { type: "rate_limit_error", message: "Number of request tokens has exceeded your per-minute rate limit." }, + }; + } + if (fault.status === 529) { + return { + type: "error", + error: { type: "overloaded_error", message: "Anthropic API is temporarily overloaded." }, + }; + } + if (fault.status === 401) { + return { + type: "error", + error: { type: "authentication_error", message: "Invalid x-api-key header." }, + }; + } + return { + type: "error", + error: { type: "api_error", message: `Injected HTTP ${String(fault.status)} error.` }, + }; +} + +function authorizedKey(headers: IncomingHttpHeaders, expectedKey: string): boolean { + const direct = headers["x-api-key"]; + if (typeof direct === "string" && direct.trim() === expectedKey) return true; + const auth = headers.authorization; + if (typeof auth === "string") { + const match = /^Bearer\s+(\S+)$/i.exec(auth.trim()); + if (match?.[1] === expectedKey) return true; + } + return false; +} + +function extractTextFromContent(content: unknown): string { + if (typeof content === "string") return content; + const blocks = asArray(content); + if (!blocks) return ""; + const parts: string[] = []; + for (const item of blocks) { + const block = asRecord(item); + if (!block) continue; + const blockType = asString(block.type); + if (blockType === "text") { + const text = asString(block.text); + if (text) parts.push(text); + } else if (blockType === "tool_result") { + const nested = extractTextFromContent(block.content); + if (nested) parts.push(nested); + } + } + return parts.join("\n").trim(); +} + +function extractSystemText(raw: unknown): string | undefined { + if (typeof raw === "string") return raw; + const text = extractTextFromContent(raw); + return text === "" ? undefined : text; +} + +function estimateTokens(text: string): number { + const trimmed = text.trim(); + if (trimmed === "") return 1; + return Math.max(1, Math.ceil(trimmed.length / 4)); +} + +function parseScriptedReply(raw: unknown): AnthropicScriptedReply | undefined { + const obj = asRecord(raw); + if (!obj) return undefined; + const kind = asString(obj.kind); + if (kind === "text") { + const text = asString(obj.text); + if (text === undefined) return undefined; + const stop = asString(obj.stopReason); + const stopReason = stop === "max_tokens" ? "max_tokens" : "end_turn"; + return { kind: "text", text, stopReason }; + } + if (kind === "tool_use") { + const name = asString(obj.name); + const input = asRecord(obj.input); + if (!name || !input) return undefined; + const id = asString(obj.id); + const text = asString(obj.text); + return { kind: "tool_use", name, input, ...(id ? { id } : {}), ...(text ? { text } : {}) }; + } + if (kind === "blocks") { + const rawBlocks = asArray(obj.content); + if (!rawBlocks || rawBlocks.length === 0) return undefined; + const content: AnthropicContentBlock[] = []; + for (const entry of rawBlocks) { + const block = asRecord(entry); + const blockType = asString(block?.type); + if (blockType === "text") { + const text = asString(block?.text); + if (text === undefined) return undefined; + content.push({ type: "text", text }); + } else if (blockType === "tool_use") { + const id = asString(block?.id) ?? randomToken("toolu_", 12); + const name = asString(block?.name); + const input = asRecord(block?.input); + if (!name || !input) return undefined; + content.push({ type: "tool_use", id, name, input }); + } else { + return undefined; + } + } + const stop = asString(obj.stopReason); + const stopReason = stop === "tool_use" || stop === "max_tokens" ? stop : "end_turn"; + return { kind: "blocks", content, stopReason }; + } + if (kind === "error") { + const status = asNumber(obj.status); + const errorType = asString(obj.errorType); + const message = asString(obj.message); + if (status === undefined || !errorType || !message) return undefined; + const retryAfter = asNumber(obj.retryAfter); + return { + kind: "error", + status, + errorType, + message, + ...(retryAfter !== undefined ? { retryAfter } : {}), + }; + } + return undefined; +} + +function buildBlocksForReply( + reply: AnthropicScriptedReply | undefined, + lastUserText: string, +): { readonly content: AnthropicContentBlock[]; readonly stopReason: "end_turn" | "tool_use" | "max_tokens" } { + if (!reply) { + const echo = lastUserText === "" ? "Acknowledged." : `Echo: ${lastUserText}`; + return { content: [{ type: "text", text: echo }], stopReason: "end_turn" }; + } + if (reply.kind === "text") { + return { content: [{ type: "text", text: reply.text }], stopReason: reply.stopReason ?? "end_turn" }; + } + if (reply.kind === "tool_use") { + const blocks: AnthropicContentBlock[] = []; + if (reply.text) blocks.push({ type: "text", text: reply.text }); + blocks.push({ + type: "tool_use", + id: reply.id ?? randomToken("toolu_", 12), + name: reply.name, + input: reply.input, + }); + return { content: blocks, stopReason: "tool_use" }; + } + if (reply.kind === "blocks") { + return { content: [...reply.content], stopReason: reply.stopReason ?? "end_turn" }; + } + return { content: [{ type: "text", text: "" }], stopReason: "end_turn" }; +} + +function chunkString(text: string, size: number): string[] { + if (text === "") return [""]; + const chunks: string[] = []; + for (let i = 0; i < text.length; i += size) { + chunks.push(text.slice(i, i + size)); + } + return chunks; +} + +function writeSseEvent(res: ServerResponse, event: string, data: unknown): void { + res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); +} + +function sendAnthropicStream( + res: ServerResponse, + messageId: string, + model: string, + content: readonly AnthropicContentBlock[], + stopReason: string, + inputTokens: number, + outputTokens: number, +): void { + res.writeHead(200, { + "content-type": "text/event-stream; charset=utf-8", + "cache-control": "no-cache, no-transform", + connection: "keep-alive", + }); + writeSseEvent(res, "message_start", { + type: "message_start", + message: { + id: messageId, + type: "message", + role: "assistant", + model, + content: [], + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: inputTokens, output_tokens: 0 }, + }, + }); + writeSseEvent(res, "ping", { type: "ping" }); + + for (const [index, block] of content.entries()) { + if (block.type === "text") { + writeSseEvent(res, "content_block_start", { + type: "content_block_start", + index, + content_block: { type: "text", text: "" }, + }); + for (const piece of chunkString(block.text, 24)) { + writeSseEvent(res, "content_block_delta", { + type: "content_block_delta", + index, + delta: { type: "text_delta", text: piece }, + }); + } + writeSseEvent(res, "content_block_stop", { type: "content_block_stop", index }); + } else { + writeSseEvent(res, "content_block_start", { + type: "content_block_start", + index, + content_block: { type: "tool_use", id: block.id, name: block.name, input: {} }, + }); + for (const piece of chunkString(JSON.stringify(block.input), 32)) { + writeSseEvent(res, "content_block_delta", { + type: "content_block_delta", + index, + delta: { type: "input_json_delta", partial_json: piece }, + }); + } + writeSseEvent(res, "content_block_stop", { type: "content_block_stop", index }); + } + } + + writeSseEvent(res, "message_delta", { + type: "message_delta", + delta: { stop_reason: stopReason, stop_sequence: null }, + usage: { output_tokens: outputTokens }, + }); + writeSseEvent(res, "message_stop", { type: "message_stop" }); + res.end(); +} + +function handleAnthropicControl( + parsed: ParsedRequest, + res: ServerResponse, + ctx: EmulatorContext, +): boolean { + if (parsed.pathname === "/__control/script" && parsed.method === "POST") { + const state = ctx.getState(); + const rawList = asArray(parsed.params.replies); + const items = rawList ?? (parsed.params.reply !== undefined ? [parsed.params.reply] : [parsed.params]); + const queued: AnthropicScriptedReply[] = []; + for (const item of items) { + const reply = parseScriptedReply(item); + if (!reply) { + sendJson(res, 400, { ok: false, error: "invalid_scripted_reply" }); + return true; + } + queued.push(reply); + } + state.queue.push(...queued); + ctx.save(); + sendJson(res, 200, { ok: true, queued: state.queue.length }); + return true; + } + + if (parsed.pathname === "/__control/messages" && parsed.method === "GET") { + const state = ctx.getState(); + sendJson(res, 200, { ok: true, messages: state.recorded }); + return true; + } + + return false; +} + +function handleCountTokens(parsed: ParsedRequest, res: ServerResponse): void { + if (parsed.method !== "POST") { + sendAnthropicError(res, 405, "invalid_request_error", "Method not allowed."); + return; + } + const body = asRecord(parsed.body); + const model = asString(body?.model); + const messages = asArray(body?.messages); + if (!model || !messages || messages.length === 0) { + sendAnthropicError(res, 400, "invalid_request_error", "model and non-empty messages are required."); + return; + } + const systemText = extractSystemText(body?.system) ?? ""; + const messageText = messages + .map((entry) => extractTextFromContent(asRecord(entry)?.content)) + .join("\n"); + sendJson(res, 200, { input_tokens: estimateTokens(`${systemText}\n${messageText}`) }); +} + +function handleCreateMessage( + parsed: ParsedRequest, + res: ServerResponse, + ctx: EmulatorContext, +): void { + if (parsed.method !== "POST") { + sendAnthropicError(res, 405, "invalid_request_error", "Method not allowed."); + return; + } + const body = asRecord(parsed.body); + if (!body) { + sendAnthropicError(res, 400, "invalid_request_error", "Request body must be a JSON object."); + return; + } + const model = asString(body.model); + const maxTokens = asNumber(body.max_tokens); + const messages = asArray(body.messages); + if (!model || maxTokens === undefined || !Number.isInteger(maxTokens) || maxTokens <= 0 || !messages || messages.length === 0) { + sendAnthropicError(res, 400, "invalid_request_error", "model, positive integer max_tokens, and non-empty messages are required."); + return; + } + + const stream = asBoolean(body.stream) === true; + const system = extractSystemText(body.system); + const tools = asArray(body.tools) ?? []; + const toolNames = tools + .map((item) => asString(asRecord(item)?.name)) + .filter((name): name is string => Boolean(name)); + + let lastUserText = ""; + let inputText = system ?? ""; + for (const item of messages) { + const msg = asRecord(item); + const text = extractTextFromContent(msg?.content); + inputText += `\n${text}`; + if (asString(msg?.role) === "user") lastUserText = text; + } + + const state = ctx.getState(); + const next = state.queue.shift(); + if (next?.kind === "error") { + ctx.save(); + sendAnthropicError(res, next.status, next.errorType, next.message, next.retryAfter); + return; + } + + const { content, stopReason } = buildBlocksForReply(next, lastUserText); + const seq = ++state.seq; + const messageId = `msg_local_${String(seq).padStart(4, "0")}`; + const inputTokens = estimateTokens(inputText); + const outputText = content + .map((block) => (block.type === "text" ? block.text : JSON.stringify(block.input))) + .join(" "); + const outputTokens = estimateTokens(outputText); + + state.recorded.push({ + seq, + id: messageId, + model, + stream, + maxTokens, + ...(system !== undefined ? { system } : {}), + messageCount: messages.length, + toolNames, + lastUserText, + stopReason, + }); + if (state.recorded.length > MAX_RECORDED) { + state.recorded.splice(0, state.recorded.length - MAX_RECORDED); + } + ctx.save(); + + if (stream) { + sendAnthropicStream(res, messageId, model, content, stopReason, inputTokens, outputTokens); + return; + } + + sendJson(res, 200, { + id: messageId, + type: "message", + role: "assistant", + model, + content, + stop_reason: stopReason, + stop_sequence: null, + usage: { input_tokens: inputTokens, output_tokens: outputTokens }, + }); +} + +function handleModels(parsed: ParsedRequest, res: ServerResponse, state: AnthropicState): void { + if (parsed.method !== "GET") { + sendAnthropicError(res, 405, "invalid_request_error", "Method not allowed."); + return; + } + if (parsed.pathname === "/v1/models") { + const first = state.models[0]?.id ?? null; + const last = state.models[state.models.length - 1]?.id ?? null; + sendJson(res, 200, { data: state.models, has_more: false, first_id: first, last_id: last }); + return; + } + const modelId = decodeURIComponent(parsed.pathname.slice("/v1/models/".length)); + const found = state.models.find((item) => item.id === modelId); + if (!found) { + sendAnthropicError(res, 404, "not_found_error", `model: ${modelId}`); + return; + } + sendJson(res, 200, found); +} + +/** Start a stateful loopback Anthropic Messages API (`/v1/messages`, `/v1/models`, SSE, `tool_use`, faults) emulator. */ +export async function startAnthropicProvider( + options: AnthropicProviderOptions = {}, +): Promise { + const apiKey = options.apiKey ?? "sk-ant-local-test-key"; + const initialModels = [...(options.models ?? DEFAULT_ANTHROPIC_MODELS)]; + const initialQueue = [...(options.defaultReplies ?? [])]; + + const running = await createEmulatorServer({ + options: { port: options.port, stateFile: options.stateFile }, + createInitial: () => ({ + seq: 0, + models: initialModels.map((model) => ({ ...model })), + queue: initialQueue.map((item) => ({ ...item })), + recorded: [], + }), + preflightHeaders: () => "x-api-key, anthropic-version, content-type, authorization, x-vibestack-namespace", + defaultFaultBody: defaultAnthropicFaultBody, + onControl: handleAnthropicControl, + onRequest: (parsed, res, ctx) => { + if (!authorizedKey(parsed.headers, apiKey)) { + sendAnthropicError(res, 401, "authentication_error", "invalid x-api-key"); + return; + } + const version = parsed.headers["anthropic-version"]; + if (typeof version !== "string" || version.trim() === "") { + sendAnthropicError(res, 400, "invalid_request_error", "anthropic-version header is required."); + return; + } + + if (parsed.pathname === "/v1/models" || parsed.pathname.startsWith("/v1/models/")) { + handleModels(parsed, res, ctx.getState()); + return; + } + if (parsed.pathname === "/v1/messages/count_tokens") { + handleCountTokens(parsed, res); + return; + } + if (parsed.pathname === "/v1/messages") { + handleCreateMessage(parsed, res, ctx); + return; + } + sendAnthropicError(res, 404, "not_found_error", `Unknown path: ${parsed.pathname}`); + }, + }); + + return { + origin: running.origin, + port: running.port, + apiKey, + stop: () => running.stop(), + }; +} diff --git a/packages/eliza-harness/test/anthropic-provider.test.ts b/packages/eliza-harness/test/anthropic-provider.test.ts new file mode 100644 index 0000000000..1a06d0b107 --- /dev/null +++ b/packages/eliza-harness/test/anthropic-provider.test.ts @@ -0,0 +1,280 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "@effect/vitest"; +import { assertNoSecrets } from "vibestack/emulate"; +import { + DEFAULT_ANTHROPIC_MODELS, + DEFAULT_ANTHROPIC_VERSION, + type RunningAnthropicProvider, + startAnthropicProvider, +} from "../src/index.ts"; + +interface SseFrame { + readonly event: string; + readonly data: Record; +} + +async function readAnthropicSse(response: Response): Promise { + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toContain("text/event-stream"); + const raw = await response.text(); + const frames: SseFrame[] = []; + for (const chunk of raw.split("\n\n")) { + const lines = chunk.split("\n").filter((line) => line.trim() !== ""); + if (lines.length === 0) continue; + let event = ""; + const dataLines: string[] = []; + for (const line of lines) { + if (line.startsWith("event:")) event = line.slice(6).trim(); + else if (line.startsWith("data:")) dataLines.push(line.slice(5).trim()); + } + if (event && dataLines.length > 0) { + frames.push({ event, data: JSON.parse(dataLines.join("\n")) as Record }); + } + } + return frames; +} + +describe("Anthropic Messages API emulator", () => { + let anthropic: RunningAnthropicProvider; + + beforeAll(async () => { + anthropic = await startAnthropicProvider(); + }); + + afterAll(async () => { + await anthropic.stop(); + }); + + beforeEach(async () => { + const res = await fetch(`${anthropic.origin}/__control/reset`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ all: true }), + }); + expect(res.status).toBe(200); + }); + + const authHeaders = (extra: Record = {}) => ({ + "x-api-key": anthropic.apiKey, + "anthropic-version": DEFAULT_ANTHROPIC_VERSION, + "content-type": "application/json", + ...extra, + }); + + it("enforces x-api-key and anthropic-version headers and serves /v1/models and count_tokens", async () => { + const missingKey = await fetch(`${anthropic.origin}/v1/models`, { + headers: { "anthropic-version": DEFAULT_ANTHROPIC_VERSION }, + }); + expect(missingKey.status).toBe(401); + expect(await missingKey.json()).toMatchObject({ type: "error", error: { type: "authentication_error" } }); + + const missingVersion = await fetch(`${anthropic.origin}/v1/models`, { + headers: { "x-api-key": anthropic.apiKey }, + }); + expect(missingVersion.status).toBe(400); + expect(await missingVersion.json()).toMatchObject({ type: "error", error: { type: "invalid_request_error" } }); + + const listed = await fetch(`${anthropic.origin}/v1/models`, { headers: authHeaders() }); + expect(listed.status).toBe(200); + const catalog = (await listed.json()) as { data: { id: string }[]; has_more: boolean; first_id: string }; + expect(catalog.has_more).toBe(false); + expect(catalog.data.map((m) => m.id)).toEqual(DEFAULT_ANTHROPIC_MODELS.map((m) => m.id)); + + const detail = await fetch(`${anthropic.origin}/v1/models/claude-sonnet-4-6`, { headers: authHeaders() }); + expect(detail.status).toBe(200); + expect(await detail.json()).toMatchObject({ id: "claude-sonnet-4-6", type: "model" }); + + const missingModel = await fetch(`${anthropic.origin}/v1/models/claude-unknown`, { headers: authHeaders() }); + expect(missingModel.status).toBe(404); + expect(await missingModel.json()).toMatchObject({ type: "error", error: { type: "not_found_error" } }); + + const counted = await fetch(`${anthropic.origin}/v1/messages/count_tokens`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + model: "claude-sonnet-4-6", + system: "Be concise.", + messages: [{ role: "user", content: "Summarize my calendar for today." }], + }), + }); + expect(counted.status).toBe(200); + const tokenBody = (await counted.json()) as { input_tokens: number }; + expect(tokenBody.input_tokens).toBeGreaterThan(0); + }); + + it("handles non-streaming and SSE streaming /v1/messages plus multi-turn tool_use and tool_result", async () => { + const badMethod = await fetch(`${anthropic.origin}/v1/messages`, { method: "GET", headers: authHeaders() }); + expect(badMethod.status).toBe(405); + + const missingMax = await fetch(`${anthropic.origin}/v1/messages`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ model: "claude-sonnet-4-6", messages: [{ role: "user", content: "hi" }] }), + }); + expect(missingMax.status).toBe(400); + + const scriptRes = await fetch(`${anthropic.origin}/__control/script`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + replies: [ + { + kind: "tool_use", + id: "toolu_cal_01", + name: "list_events", + text: "Checking your calendar.", + input: { day: "2026-12-04" }, + }, + { + kind: "text", + text: "You have Design sync at 2 PM.", + }, + ], + }), + }); + expect(scriptRes.status).toBe(200); + + const turn1 = await fetch(`${anthropic.origin}/v1/messages`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + model: "claude-sonnet-4-6", + max_tokens: 512, + tools: [{ name: "list_events", input_schema: { type: "object" } }], + messages: [{ role: "user", content: "What is on my calendar today?" }], + }), + }); + expect(turn1.status).toBe(200); + const turn1Body = (await turn1.json()) as { + id: string; + stop_reason: string; + content: { type: string; id?: string; name?: string; input?: Record; text?: string }[]; + }; + expect(turn1Body.stop_reason).toBe("tool_use"); + expect(turn1Body.content).toEqual([ + { type: "text", text: "Checking your calendar." }, + { type: "tool_use", id: "toolu_cal_01", name: "list_events", input: { day: "2026-12-04" } }, + ]); + + const turn2 = await fetch(`${anthropic.origin}/v1/messages`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + model: "claude-sonnet-4-6", + max_tokens: 512, + stream: true, + messages: [ + { role: "user", content: "What is on my calendar today?" }, + { role: "assistant", content: turn1Body.content }, + { + role: "user", + content: [{ type: "tool_result", tool_use_id: "toolu_cal_01", content: "Design sync at 2 PM" }], + }, + ], + }), + }); + const frames = await readAnthropicSse(turn2); + expect(frames.map((frame) => frame.event)).toContain("message_start"); + expect(frames.map((frame) => frame.event)).toContain("content_block_start"); + expect(frames.map((frame) => frame.event)).toContain("content_block_delta"); + expect(frames.map((frame) => frame.event)).toContain("content_block_stop"); + expect(frames.map((frame) => frame.event)).toContain("message_delta"); + expect(frames.at(-1)?.event).toBe("message_stop"); + + const streamedText = frames + .filter((frame) => frame.event === "content_block_delta") + .map((frame) => (frame.data.delta as { text?: string }).text ?? "") + .join(""); + expect(streamedText).toBe("You have Design sync at 2 PM."); + + const recorded = (await (await fetch(`${anthropic.origin}/__control/messages`)).json()) as { + ok: boolean; + messages: { model: string; stopReason: string; stream: boolean }[]; + }; + expect(recorded.ok).toBe(true); + expect(recorded.messages).toHaveLength(2); + expect(recorded.messages[0]).toMatchObject({ model: "claude-sonnet-4-6", stopReason: "tool_use", stream: false }); + expect(recorded.messages[1]).toMatchObject({ model: "claude-sonnet-4-6", stopReason: "end_turn", stream: true }); + }); + + it("streams input_json_delta for tool_use, injects 429 and 529 faults, and isolates namespaces", async () => { + const streamToolScript = await fetch(`${anthropic.origin}/__control/script`, { + method: "POST", + headers: { "content-type": "application/json", "x-vibestack-namespace": "ns-a" }, + body: JSON.stringify({ + reply: { kind: "tool_use", id: "toolu_stream_1", name: "send_email", input: { to: "maya@example.com" } }, + }), + }); + expect(streamToolScript.status).toBe(200); + + const streamRes = await fetch(`${anthropic.origin}/v1/messages`, { + method: "POST", + headers: authHeaders({ "x-vibestack-namespace": "ns-a" }), + body: JSON.stringify({ + model: "claude-opus-4-6", + max_tokens: 256, + stream: true, + messages: [{ role: "user", content: "Email Maya" }], + }), + }); + const frames = await readAnthropicSse(streamRes); + const partialJson = frames + .filter((frame) => frame.event === "content_block_delta") + .map((frame) => (frame.data.delta as { partial_json?: string }).partial_json ?? "") + .join(""); + expect(JSON.parse(partialJson)).toEqual({ to: "maya@example.com" }); + + const nsBRes = await fetch(`${anthropic.origin}/v1/messages`, { + method: "POST", + headers: authHeaders({ "x-vibestack-namespace": "ns-b" }), + body: JSON.stringify({ + model: "claude-haiku-4-5-20251001", + max_tokens: 128, + messages: [{ role: "user", content: "Isolated namespace prompt" }], + }), + }); + expect(nsBRes.status).toBe(200); + const nsBBody = (await nsBRes.json()) as { content: { type: string; text: string }[] }; + expect(nsBBody.content[0]?.text).toBe("Echo: Isolated namespace prompt"); + + const arm429 = await fetch(`${anthropic.origin}/__control/fault`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ method: "POST", path: "/v1/messages", status: 429, retryAfter: 3, remaining: 1 }), + }); + expect(arm429.status).toBe(200); + + const hit429 = await fetch(`${anthropic.origin}/v1/messages`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ model: "claude-sonnet-4-6", max_tokens: 64, messages: [{ role: "user", content: "rate test" }] }), + }); + expect(hit429.status).toBe(429); + expect(hit429.headers.get("retry-after")).toBe("3"); + expect(await hit429.json()).toMatchObject({ type: "error", error: { type: "rate_limit_error" } }); + + const arm529 = await fetch(`${anthropic.origin}/__control/fault`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ method: "POST", path: "/v1/messages", status: 529, remaining: 1 }), + }); + expect(arm529.status).toBe(200); + + const hit529 = await fetch(`${anthropic.origin}/v1/messages`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ model: "claude-sonnet-4-6", max_tokens: 64, messages: [{ role: "user", content: "overload test" }] }), + }); + expect(hit529.status).toBe(529); + expect(await hit529.json()).toMatchObject({ type: "error", error: { type: "overloaded_error" } }); + + const recovered = await fetch(`${anthropic.origin}/v1/messages`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ model: "claude-sonnet-4-6", max_tokens: 64, messages: [{ role: "user", content: "recovered" }] }), + }); + expect(recovered.status).toBe(200); + const recoveredBody = (await recovered.json()) as { content: { text: string }[] }; + expect(recoveredBody.content[0]?.text).toBe("Echo: recovered"); + expect(() => assertNoSecrets(recoveredBody)).not.toThrow(); + }); +});