chat-js 1.0.0-alpha.0 → 1.0.0-alpha.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chat-js",
3
- "version": "1.0.0-alpha.0",
3
+ "version": "1.0.0-alpha.2",
4
4
  "private": false,
5
5
  "description": "CLI for creating and extending ChatJS apps",
6
6
  "keywords": [
@@ -61,7 +61,7 @@
61
61
  "zod": "^4.3.6"
62
62
  },
63
63
  "devDependencies": {
64
- "@chat-js/registry-validation": "0.0.0",
64
+ "@chat-js/registry-validation": "workspace:*",
65
65
  "@types/bun": "latest",
66
66
  "@types/node": "22.13.10",
67
67
  "next": "16.3.0",
@@ -0,0 +1,4 @@
1
+ import { otel } from "eve/instrumentation/otel";
2
+ import { guestTracePolicy } from "@/chatjs/plugins/guest-chat/guest-retention";
3
+
4
+ export default otel({ tracePolicy: guestTracePolicy });
@@ -4,6 +4,9 @@ import type { ReadonlyNativeSurface } from "@/lib/readonly-native-surface";
4
4
  import { env } from "@/lib/env";
5
5
  import { runCleanupJob } from "@/lib/cleanup/job";
6
6
 
7
+ export const maxDuration = 300;
8
+ const MAX_BATCHES = 20;
9
+ const DRAIN_BUDGET_MS = 120_000;
7
10
  const HTTP_OK = 200;
8
11
  const HTTP_SERVICE_UNAVAILABLE = 503;
9
12
 
@@ -19,7 +22,25 @@ export const GET = async (
19
22
  if (!hasCronSecret || authHeader !== `Bearer ${env.CRON_SECRET}`) {
20
23
  return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
21
24
  }
22
- const result = await runCleanupJob();
25
+ const deadline = Date.now() + DRAIN_BUDGET_MS;
26
+ let result = await runCleanupJob(deadline);
27
+ for (
28
+ let batch = 1;
29
+ batch < MAX_BATCHES && !result.success && Date.now() < deadline;
30
+ batch += 1
31
+ ) {
32
+ const progress = Object.values(result.results).some(
33
+ (task) =>
34
+ !("error" in task) &&
35
+ !task.skipped &&
36
+ task.deletedCount + (task.retiredCount ?? 0) > 0
37
+ );
38
+ if (!progress) {
39
+ break;
40
+ }
41
+ // oxlint-disable-next-line eslint/no-await-in-loop -- Drain successful batches serially within the scheduler budget.
42
+ result = await runCleanupJob(deadline);
43
+ }
23
44
  return NextResponse.json(result, {
24
45
  status: result.success ? HTTP_OK : HTTP_SERVICE_UNAVAILABLE,
25
46
  });
@@ -11,6 +11,7 @@
11
11
  "chatjs/plugins/guest-chat/guest-ip.ts",
12
12
  "chatjs/plugins/guest-chat/guest-model.ts",
13
13
  "chatjs/plugins/guest-chat/guest-policy.ts",
14
+ "chatjs/plugins/guest-chat/guest-retention.ts",
14
15
  "chatjs/plugins/guest-chat/guest-queries.ts",
15
16
  "chatjs/plugins/guest-chat/guest-scheduler.ts",
16
17
  "chatjs/plugins/guest-chat/guest-schema.ts",
@@ -18,7 +19,8 @@
18
19
  "chatjs/plugins/guest-chat/server-plugin.ts",
19
20
  "chatjs/plugins/guest-chat/session-profile.ts",
20
21
  "chatjs/plugins/guest-chat/signed-out.tsx",
21
- "app/api/eve-guest/route.ts"
22
+ "app/api/eve-guest/route.ts",
23
+ "agent/instrumentation/guest-retention.ts"
22
24
  ],
23
25
  "databaseSchemas": ["chatjs/plugins/guest-chat/guest-schema.ts"],
24
26
  "signedOut": { "export": "GuestChatScreen" },
@@ -151,7 +151,7 @@ export const authenticateDisposableGuest = async (
151
151
  authenticator: "chatjs-disposable-guest",
152
152
  issuer: "chatjs",
153
153
  principalId: claims.ownerId,
154
- principalType: "user",
154
+ principalType: "guest",
155
155
  subject: claims.ownerId,
156
156
  };
157
157
  };
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { Client } from "eve/client";
2
+ import { Client, ClientError } from "eve/client";
3
3
 
4
4
  import {
5
5
  bindGuestRuntimeCleanupSession,
@@ -9,17 +9,19 @@ import {
9
9
  pruneGuestRuntimeRates,
10
10
  } from "@/chatjs/plugins/guest-chat/guest-queries";
11
11
  import { getGuestCleanupConnectionOptions } from "@/chatjs/plugins/guest-chat/guest-cleanup-auth";
12
- import { requireEveDeletionLifecycle } from "@/lib/eve/deletion-lifecycle";
13
12
 
14
13
  const MAX_CLEANUP_BATCH = 5;
15
14
  const RETIRE_TIMEOUT_MS = 30_000;
16
15
 
17
- const resolveCleanupSession = async (guest: {
18
- readonly id: string;
19
- readonly modelId: string;
20
- readonly ownerId: string;
21
- readonly sessionId: string | null;
22
- }): Promise<string> => {
16
+ const resolveCleanupSession = async (
17
+ guest: {
18
+ readonly id: string;
19
+ readonly modelId: string;
20
+ readonly ownerId: string;
21
+ readonly sessionId: string | null;
22
+ },
23
+ signal: AbortSignal
24
+ ): Promise<string> => {
23
25
  if (guest.sessionId !== null) {
24
26
  return guest.sessionId;
25
27
  }
@@ -39,7 +41,7 @@ const resolveCleanupSession = async (guest: {
39
41
  "content-type": "application/json",
40
42
  },
41
43
  body: JSON.stringify({ operationId: guest.id }),
42
- signal: AbortSignal.timeout(RETIRE_TIMEOUT_MS),
44
+ signal,
43
45
  });
44
46
  if (!response.ok) {
45
47
  throw new Error("Guest creation reconciliation remains unresolved.");
@@ -55,34 +57,45 @@ const resolveCleanupSession = async (guest: {
55
57
  return sessionId;
56
58
  };
57
59
 
58
- export const cleanupGuestRuntimeSessions = async (): Promise<{
60
+ export const cleanupGuestRuntimeSessions = async ({
61
+ deadline = Number.POSITIVE_INFINITY,
62
+ }: { readonly deadline?: number } = {}): Promise<{
59
63
  deletedCount: number;
64
+ retiredCount: number;
60
65
  pendingCount: number;
61
66
  skipped: boolean;
62
67
  }> => {
63
- if ((await countPendingGuestRuntimeDeletions()) === 0) {
68
+ const initialPendingCount = await countPendingGuestRuntimeDeletions();
69
+ if (initialPendingCount === 0) {
64
70
  await pruneGuestRuntimeRates();
65
- return { deletedCount: 0, pendingCount: 0, skipped: false };
71
+ return {
72
+ deletedCount: 0,
73
+ retiredCount: 0,
74
+ pendingCount: 0,
75
+ skipped: false,
76
+ };
66
77
  }
67
- const lifecycle = requireEveDeletionLifecycle();
68
- // Compatibility checks precede claims or retirement. Missing fences never
69
- // produce a successful cleanup report or erase the durable retry record.
70
- await lifecycle.check();
71
- let deletedCount = 0;
78
+ let retiredCount = 0;
72
79
  let pendingCount = 0;
73
- for (let attempt = 0; attempt < MAX_CLEANUP_BATCH; attempt += 1) {
74
- // oxlint-disable-next-line eslint/no-await-in-loop -- Claim and purge one session at a time to bound provider connections and work.
80
+ for (
81
+ let attempt = 0;
82
+ attempt < MAX_CLEANUP_BATCH && Date.now() < deadline;
83
+ attempt += 1
84
+ ) {
85
+ // oxlint-disable-next-line eslint/no-await-in-loop -- Claim and retire one session at a time to bound provider connections and work.
75
86
  const guest = await claimExpiredGuestRuntimeSession();
76
87
  if (!guest) {
77
88
  break;
78
89
  }
79
90
  let phase = "reconcile-session";
80
91
  try {
81
- // oxlint-disable-next-line eslint/no-await-in-loop -- Reconcile only the current claimed guest before native purge.
82
- const sessionId = await resolveCleanupSession(guest);
83
- phase = "retire-and-purge";
84
- // oxlint-disable-next-line eslint/no-await-in-loop -- Native purge serializes durable retirement, fencing, queue drain and payload erasure.
85
- await lifecycle.purge(sessionId, async () => {
92
+ const signal = AbortSignal.timeout(
93
+ Math.max(1, Math.min(RETIRE_TIMEOUT_MS, deadline - Date.now()))
94
+ );
95
+ // oxlint-disable-next-line eslint/no-await-in-loop -- Reconcile only the current claimed guest before retirement.
96
+ const sessionId = await resolveCleanupSession(guest, signal);
97
+ phase = "retire";
98
+ const retire = async (): Promise<void> => {
86
99
  const client = new Client(
87
100
  getGuestCleanupConnectionOptions({
88
101
  ownerId: guest.ownerId,
@@ -93,35 +106,49 @@ export const cleanupGuestRuntimeSessions = async (): Promise<{
93
106
  );
94
107
  const session = client.sessions.attach(sessionId);
95
108
  const current = await session.snapshot({
96
- signal: AbortSignal.timeout(RETIRE_TIMEOUT_MS),
109
+ signal,
97
110
  });
98
111
  if (current.events.some((event) => event.type === "session.ended")) {
99
112
  return;
100
113
  }
101
114
  const retirement = await session.end({
102
115
  reason: "Guest retention expired",
103
- signal: AbortSignal.timeout(RETIRE_TIMEOUT_MS),
116
+ signal,
104
117
  });
105
118
  for await (const event of retirement.stream({
106
- signal: AbortSignal.timeout(RETIRE_TIMEOUT_MS),
119
+ signal,
107
120
  })) {
108
121
  if (event.type === "session.ended") {
109
- break;
122
+ return;
110
123
  }
111
124
  }
112
125
  const snapshot = await session.snapshot({
113
- signal: AbortSignal.timeout(RETIRE_TIMEOUT_MS),
126
+ signal,
114
127
  });
115
128
  if (!snapshot.events.some((event) => event.type === "session.ended")) {
116
129
  throw new Error("Guest retirement is not terminal. Retry cleanup.");
117
130
  }
118
- });
131
+ };
132
+ try {
133
+ // oxlint-disable-next-line eslint/no-await-in-loop -- Finish this session before completing its policy; payloads follow native World retention.
134
+ await retire();
135
+ } catch (error) {
136
+ // EVE can expire history as soon as end completes. Only its explicit
137
+ // expiry response is terminal evidence; 404, auth and transport failures retry.
138
+ if (
139
+ !ClientError.is(error) ||
140
+ error.status !== 410 ||
141
+ error.code !== "session_expired"
142
+ ) {
143
+ throw error;
144
+ }
145
+ }
119
146
  phase = "complete-policy";
120
- // oxlint-disable-next-line eslint/no-await-in-loop -- Mark deleted only after the exact bound native session was purged.
147
+ // oxlint-disable-next-line eslint/no-await-in-loop -- Complete local policy after verified ending or expiry.
121
148
  if (!(await completeGuestRuntimeDeletion(guest.id, sessionId))) {
122
149
  throw new Error("Guest deletion binding changed.");
123
150
  }
124
- deletedCount += 1;
151
+ retiredCount += 1;
125
152
  } catch {
126
153
  pendingCount += 1;
127
154
  console.error("Guest runtime cleanup requires retry", {
@@ -130,10 +157,23 @@ export const cleanupGuestRuntimeSessions = async (): Promise<{
130
157
  });
131
158
  }
132
159
  }
160
+ if (Date.now() >= deadline) {
161
+ // No new bookkeeping after the deadline; a later sweep establishes completion.
162
+ return {
163
+ deletedCount: 0,
164
+ retiredCount,
165
+ pendingCount: Math.max(
166
+ pendingCount,
167
+ initialPendingCount - retiredCount,
168
+ 1
169
+ ),
170
+ skipped: false,
171
+ };
172
+ }
133
173
  await pruneGuestRuntimeRates();
134
174
  pendingCount = Math.max(
135
175
  pendingCount,
136
176
  await countPendingGuestRuntimeDeletions()
137
177
  );
138
- return { deletedCount, pendingCount, skipped: false };
178
+ return { deletedCount: 0, retiredCount, pendingCount, skipped: false };
139
179
  };
@@ -200,8 +200,8 @@ export const reserveGuestRuntimeMessage = async (input: {
200
200
  });
201
201
  };
202
202
 
203
- // A five-minute cooldown bounds repeated failures. Native purge has its own
204
- // durable advisory lock and idempotent receipts, so overlapping cron retries are safe.
203
+ // A five-minute cooldown bounds repeated failures. Completion is idempotent
204
+ // for the exact policy/session binding when retries overlap.
205
205
  export const claimExpiredGuestRuntimeSession = async () =>
206
206
  await db.transaction(async (tx) => {
207
207
  const [guest] = await tx
@@ -236,18 +236,22 @@ export const claimExpiredGuestRuntimeSession = async () =>
236
236
  return { ...guest, state: "deleting" };
237
237
  });
238
238
 
239
+ // Completes local credential-policy cleanup; this is not a claim of provider payload erasure.
239
240
  export const completeGuestRuntimeDeletion = async (
240
241
  id: string,
241
242
  sessionId: string
242
243
  ): Promise<boolean> => {
243
244
  const rows = await db
244
245
  .update(guestRuntimeSession)
245
- .set({ state: "deleted", deletedAt: sql`now()` })
246
+ .set({
247
+ state: "deleted",
248
+ deletedAt: sql`coalesce(${guestRuntimeSession.deletedAt}, now())`,
249
+ })
246
250
  .where(
247
251
  and(
248
252
  eq(guestRuntimeSession.id, id),
249
253
  eq(guestRuntimeSession.sessionId, sessionId),
250
- eq(guestRuntimeSession.state, "deleting")
254
+ inArray(guestRuntimeSession.state, ["deleting", "deleted"])
251
255
  )
252
256
  )
253
257
  .returning({ id: guestRuntimeSession.id });
@@ -0,0 +1,8 @@
1
+ import type { TraceCapturePolicy } from "eve/instrumentation/otel";
2
+
3
+ // EVE derives retention 0 from omitted input/output capture. Preserve EVE's
4
+ // default policy for every other principal, including registered users.
5
+ export const guestTracePolicy: TraceCapturePolicy = ({ principalType }) =>
6
+ principalType === "guest"
7
+ ? { emit: true, recordInputs: false, recordOutputs: false }
8
+ : true;
@@ -53,7 +53,7 @@ export const startLocalEveGuestCleanup = (): (() => void) | undefined => {
53
53
  if (
54
54
  result.status === "fulfilled" &&
55
55
  (result.value.skipped ||
56
- result.value.deletedCount ||
56
+ result.value.retiredCount ||
57
57
  Boolean(result.value.pendingCount))
58
58
  ) {
59
59
  console.info("Local EVE guest cleanup", result.value);
@@ -1,4 +1,3 @@
1
- import { requireEveDeletionLifecycle } from "@/lib/eve/deletion-lifecycle";
2
1
  import { readGuestBody } from "@/chatjs/plugins/guest-chat/guest-body";
3
2
  import {
4
3
  createGuestRuntimeSession,
@@ -58,18 +57,6 @@ export const POST = async (
58
57
  { status: 503 }
59
58
  );
60
59
  }
61
- try {
62
- // Never admit temporary data unless this deployment can later erase it.
63
- await requireEveDeletionLifecycle().check();
64
- } catch {
65
- return Response.json(
66
- {
67
- error:
68
- "Guest retention is unavailable. Please sign in or try again later.",
69
- },
70
- { status: 503 }
71
- );
72
- }
73
60
  await loadEveModelDefinition(value.data.modelId);
74
61
  let ipHash: string;
75
62
  try {
@@ -2,9 +2,9 @@
2
2
 
3
3
  Cleanup belongs to the application. Deployment providers schedule the same authenticated `GET /api/cron/cleanup` job; they do not implement retention or deletion themselves.
4
4
 
5
- `lib/cleanup/job.ts` coordinates independent tasks and reports each task's result. It currently cleans up expired legacy guest families, expired shared-runtime guest sessions, and orphaned attachments older than four hours. Registered conversation history is not an expiration target. Add future cleanup tasks here, with their ownership checks, retention policy, retry behavior and tests in their own module.
5
+ `lib/cleanup/job.ts` coordinates independent tasks and reports each task's result. It currently cleans up expired shared-runtime guest sessions and orphaned attachments older than four hours. Registered conversation history is not an expiration target. Add future cleanup tasks here, with their ownership checks, retention policy, retry behavior and tests in their own module.
6
6
 
7
- The tasks retain their existing database claims, ownership fences and idempotent deletion receipts. Guest deletion runs in bounded batches. Attachment deletion uses batches of 100, but inventory traversal can still span the entire bucket; this is not a globally time-bounded job. Failed or uncertain deletions remain retryable. A scheduler must not infer success from dispatching a request: `200` means all tasks completed without pending work, while `503` means incomplete work needs another attempt. Individual failures do not prevent the other tasks from running. Responses contain counts and safe errors, never raw provider exceptions.
7
+ The tasks retain their existing database claims, ownership fences and idempotent deletion receipts. Guest cleanup runs in bounded batches. On every backend, guest cleanup ends or verifies expiry of the session and completes its local credential policy. Guest cleanup reports `retiredCount`, with `deletedCount` zero, and leaves payload retention to the provider. Attachment deletion uses batches of 100, but inventory traversal can still span the entire bucket; this is not a globally time-bounded job. Failed or uncertain deletions remain retryable. A scheduler must not infer success from dispatching a request: `200` means all tasks completed without pending work, while `503` means incomplete work needs another attempt. Individual failures do not prevent the other tasks from running. Responses contain counts and safe errors, never raw provider exceptions.
8
8
 
9
9
  ## Scheduling adapters
10
10
 
@@ -16,6 +16,8 @@ The tasks retain their existing database claims, ownership fences and idempotent
16
16
 
17
17
  The hosted runner requires HTTPS, refuses redirects, drains successful guest batches, and exits nonzero on failed or stalled work. Its two-minute deadline bounds the client wait; it does not cancel work already running on the server. Avoid overlapping schedules; database ownership protections make retries safe, but there is no global scheduler lock. Use the scheduler's single-concurrency setting where available and alert on unsuccessful runs.
18
18
 
19
- The checked-in Vercel schedule is daily for Hobby compatibility; Render's is hourly. Guests become eligible for deletion at 24 hours. Physical deletion follows on a successful scheduled sweep, so a daily schedule can approach 48 hours and an hourly schedule 25 hours, plus failures/backlog. Neither is a strict 24-hour erasure guarantee. Choose a schedule that matches the deployment's advertised retention policy.
19
+ The checked-in Vercel schedule is daily for Hobby compatibility; Render's is hourly. Guests become eligible for retirement at 24 hours. Retirement follows on a successful scheduled sweep, so a daily schedule can approach 48 hours and an hourly schedule 25 hours, plus failures/backlog. Neither is a strict 24-hour erasure guarantee. Choose a schedule that matches the deployment's advertised retention policy.
20
20
 
21
- Verify a deployment by running `bun run cleanup` with its environment and checking both the exit status and protected application logs. To certify retention, also test an expired guest with real workflow data and confirm provider payload deletion while a registered conversation remains available. A successful empty sweep alone does not certify erasure.
21
+ On every backend, these sweep timings describe session retirement and credential-policy completion, not physical payload deletion. The route drains at most 20 batches within a two-minute budget. Guest cleanup stops claiming sessions at the deadline, and each session’s network operations share a 30-second timeout capped by the remaining budget. Attachment inventory continues its existing full scan: interrupting without a durable cursor would starve later files. This budget is a guest network/work-admission bound, not a hard request deadline. Storage and database operations do not support cancellation here; a stalled call can still reach the platform timeout and require a later retry.
22
+
23
+ Verify a deployment by running `bun run cleanup` with its environment and checking both the exit status and protected application logs. Verify native ending or explicit expiry, local policy completion, and credential rejection. Payload deletion follows World support: the pinned PostgreSQL World accepts retention `0` but does not enforce it, so guest payloads remain stored. A successful sweep does not certify erasure. Account-deletion purge remains a separate operation.
@@ -2,13 +2,15 @@
2
2
 
3
3
  Registered and guest chats use one EVE agent and one worker. Both enter through `/eve/chat/v1/*`; authorization is based on server-verified credentials and the persisted session policy, not the public URL. Self-hosted deployments use the same PostgreSQL workflow backend for both session types. Backend selection remains deployment-scoped; a guest-only installation using another workflow backend is not part of this MVP.
4
4
 
5
- Guest admission in this MVP requires the deployment-selected PostgreSQL backend and a verified lifecycle schema with enabled write and queue fences (`bun eve:setup`). Bootstrap checks lifecycle compatibility before creating a guest policy or native session and returns HTTP 503 if verification fails. Managed Workflow and custom Worlds remain available according to the registered application's existing backend selection, but cannot admit new guest sessions until a verified cleanup implementation exists. Selecting a backend is not sufficient evidence of retention support.
5
+ Guest sessions request EVE native retention `0` on every backend. The installed instrumentation policy excludes guest input/output trace capture, which EVE uses to select zero retention; registered-user policy remains unchanged. Scheduled cleanup ends the session and completes the local credential policy. Guest admission and cleanup do not require the PostgreSQL purge lifecycle.
6
+
7
+ The pinned `@workflow/world-postgres@5.0.0-beta.40` accepts the retention preference but does not implement payload deletion. PostgreSQL guest payloads therefore remain stored until the provider implements it or an operator removes them separately. This is an accepted limitation, not a deletion guarantee. Vercel enforces its own retention policy. Native retention does not remove provider logs, traces already exported, or all run metadata.
6
8
 
7
9
  Guests keep the existing chat presentation at `/`. They get one inexpensive text model (`openai/gpt-5-nano`), with the picker locked. No tools, uploads, connectors, account APIs or account data are accessible. Server-owned policy enforces usage and rate limits plus bounded input and output. Registered authentication, billing, durable history and recovery keep their existing behavior.
8
10
 
9
11
  Guest credentials are signed, expire, and authorize only their assigned session. The browser keeps the credential and conversation binding in memory; reload and New chat start fresh. Guest history does not migrate on sign-in. The guest and registered sessions use the same agent-level runtime timeout; credential expiry is a separate authorization boundary.
10
12
 
11
- Guest transcripts are temporary PostgreSQL workflows with scheduled cleanup targeting 24 hours, replacing the separate guest agent's immediate workflow retention setting. Hourly cleanup means deletion can occur after the target by the scheduling interval, plus retries during failures; this is not a hard 24-hour deletion guarantee. Model-provider logs and observability retention are separate. Unload and New chat still request retirement on a best-effort basis. Operators must monitor the protected cleanup endpoint and retry unsuccessful sweeps.
13
+ Scheduled cleanup targets session retirement after 24 hours, plus the scheduling interval and retries. Payload retention is owned by the selected Workflow World. Model-provider logs and observability retention are separate. Unload and New chat request retirement on a best-effort basis. Operators must monitor the protected cleanup endpoint and retry unsuccessful sweeps.
12
14
 
13
15
  This deployment removes the old `/eve/guest/v1/*` mount and guest worker. Existing open guest tabs should reload after upgrading; their old runtime sessions are not migrated. Registered session recovery must remain compatible with the existing workflow backend.
14
16
 
@@ -16,7 +18,7 @@ Run the guest browser suite with `bunx playwright test --config playwright.guest
16
18
 
17
19
  The policy is 5 messages per IP per minute, 5 sessions per IP per hour, a one-hour credential, 4,000 characters per message, 24,000 cumulative user-input characters and a 24,000-character serialized model prompt, and 512 output tokens. GPT-5 nano uses minimal reasoning to leave room for visible output. Admission is charged before dispatch, including failed attempts. Configure a trusted proxy IP header; missing trusted client identity fails closed.
18
20
 
19
- The 24-hour target applies to conversation/workflow payloads. Minimal deletion fences and policy audit metadata (including identifiers, counters and hashed IP) remain for safe retries and late-write prevention; rate buckets are pruned after two days. This is not a promise that all metadata disappears after 24 hours.
21
+ The 24-hour target applies to session retirement (plus scheduler delay and retries), not physical payload deletion. Cleanup reports `retiredCount`, with `deletedCount` zero. Local policy audit metadata (including identifiers, counters and hashed IP) remains for safe retries; rate buckets are pruned after two days. The PostgreSQL guest path no longer installs native payload/queue purge receipts or late-write fences. Account deletion still uses its separate lifecycle safeguards.
20
22
 
21
23
  The plugin-owned `chatjs/plugins/guest-chat/guest-policy.ts` is authoritative. The obsolete `ai.anonymousModels` and `anonymous` settings are removed. The provider prompt includes assistant replies and framing, so a long conversation can reach that bound before its user-input allowance. Failed or ambiguous dispatches remain charged to admission capacity.
22
24
 
@@ -24,6 +26,12 @@ The plugin contributes a signed-out screen, native session profile, and cleanup
24
26
 
25
27
  Migration 0022 drops the old `EveGuest`, `EveGuestMessage`, and `EveGuestRate` tables and their conversation cleanup column. It stops if a legacy guest still owns an undeleted conversation: drain that inventory using the previous release before upgrading. Current `GuestRuntimeSession` and `GuestRuntimeRate` tables retain their names and data under plugin ownership.
26
28
 
27
- Cleanup refuses ambiguous workflow queue ownership rather than risking another session's data. A partial batch reports its remaining expired backlog; the hosted scheduler continues batches that make progress and fails on stalled work so operators can retry. The default Vercel schedule remains daily for Hobby compatibility; PostgreSQL guest deployments need the hourly external scheduler described in the Render profile.
29
+ Cleanup requires the exact guest policy/session binding and verified session ending or explicit expiry. A partial batch reports its remaining expired backlog; the hosted scheduler continues batches that make progress and fails on stalled work so operators can retry. The default Vercel schedule remains daily for Hobby compatibility; PostgreSQL guest deployments need the hourly external scheduler described in the Render profile.
28
30
 
29
31
  The migration sequence preserves the existing `0016_large_zeigeist` sandbox migration and introduces guest tables in `0017_flimsy_whiplash` and `0018_shallow_tyrannus`. The earlier disposable Render verification database used pre-review guest migration numbers. Do not automatically deploy this revised sequence to that database: provision a fresh verification database or reconcile its migration history and schema explicitly before rollout.
32
+
33
+ Cleanup accepts `session.ended` or EVE's explicit `410 session_expired` response before completing the local credential policy. Empty history, missing sessions, authentication failures and transport errors do not prove retirement and remain retryable.
34
+
35
+ New guests authenticate with principal type `guest`. Before deploying this identity change onto an existing installation, stop guest admission and retire outstanding sessions using the previous code. Existing account sessions are unaffected; this change does not add guest identity compatibility aliases.
36
+
37
+ `agent/instrumentation/guest-retention.ts` is installed only with Guest Chat. It preserves EVE's default trace policy for non-guest principals; it does not set an agent-wide retention override. Guest payload tracing is disabled in development as well as production. See [Workflow retention](https://workflow-sdk.dev/docs/observability/retention).
@@ -24,11 +24,13 @@ The first run exposed a test-configuration error: `PLAYWRIGHT=True` intentionall
24
24
 
25
25
  The published EVE fork needed its canonical `workflow//eve//workflowEntry` identity preserved by the workflow transform; the checked-in patch and regression test cover that. Guest model validation now accepts server-generated assistant reasoning history while still denying nontext user input and tools. Registry-owned research/MCP guards live in their canonical sources and synchronize into the app.
26
26
 
27
- ## Limits and deployment requirements
27
+ ## Historical limits and deployment requirements
28
28
 
29
29
  This is local integration verification, not Render/Supabase certification or a full regression of every registered tool/provider. The cron endpoint correctly returned 503 because this isolated test environment had no configured attachment-storage credentials; its runtime-guest result independently reported one deletion and zero pending, and database payload deletion was verified. Attachment cleanup was not bypassed or weakened.
30
30
 
31
- Apply migrations 0016 and 0017, run EVE setup to install/verify PostgreSQL lifecycle fences, configure the trusted client-IP header and protected hourly cleanup job, and deploy the single worker. Guest admission fails closed if the selected backend cannot prove cleanup support. Managed/local guest-only backends are not implemented. Existing guest tabs must reload; registered workflow history remains on the same backend.
31
+ The following describes the original PostgreSQL verification, not current deployment instructions. Managed Vercel guest sessions are now supported using provider retention; see [guest sessions](guest-sessions.md) and [cleanup](cleanup.md). Use the full current migration sequence for new deployments.
32
+
33
+ For that original verification: apply migrations 0016 and 0017, run EVE setup to install/verify PostgreSQL lifecycle fences, configure the trusted client-IP header and protected hourly cleanup job, and deploy the single worker. Guest admission fails closed if the selected backend cannot prove cleanup support. Managed/local guest-only backends were not implemented at that revision. Existing guest tabs must reload; registered workflow history remains on the same backend.
32
34
 
33
35
  The 24-hour target covers conversation payloads with hourly scheduling and retries, not all operational metadata or provider logs. Policy audit records and deletion fences remain. UI Verify captures passed locally, but remote baseline comparison was unavailable without `UIVERIFY_API_KEY`.
34
36
 
@@ -1,10 +1,15 @@
1
1
  /** Each task reports a bounded sweep. Pending work and skipped sweeps are never success. */
2
2
  export interface CleanupResult {
3
3
  readonly deletedCount: number;
4
+ /** Sessions ended with payloads still governed by provider retention. */
5
+ readonly retiredCount?: number;
4
6
  readonly pendingCount?: number;
5
7
  readonly skipped: boolean;
6
8
  }
7
9
  export interface CleanupTask {
8
10
  readonly id: string;
9
- readonly run: () => Promise<CleanupResult>;
11
+ /** Best-effort deadline for new work; does not promise cancellation of database/storage calls. */
12
+ readonly run: (options?: {
13
+ readonly deadline?: number;
14
+ }) => Promise<CleanupResult>;
10
15
  }
@@ -4,7 +4,7 @@ import type { CleanupResult, CleanupTask } from "./contracts";
4
4
 
5
5
  const ORPHANED_ATTACHMENTS_RETENTION_TIME = 14_400_000;
6
6
 
7
- export const runCleanupJob = async () => {
7
+ export const runCleanupJob = async (deadline = Number.POSITIVE_INFINITY) => {
8
8
  const tasks: readonly CleanupTask[] = [
9
9
  {
10
10
  id: "orphanedAttachments",
@@ -21,10 +21,12 @@ export const runCleanupJob = async () => {
21
21
  const results: Record<string, CleanupResult | { error: string }> = {};
22
22
  const settled = await Promise.allSettled(
23
23
  tasks.map(async (task) => {
24
- const result = await task.run();
24
+ const result = await task.run({ deadline });
25
25
  if (
26
26
  !Number.isSafeInteger(result.deletedCount) ||
27
27
  result.deletedCount < 0 ||
28
+ !Number.isSafeInteger(result.retiredCount ?? 0) ||
29
+ (result.retiredCount ?? 0) < 0 ||
28
30
  !Number.isSafeInteger(result.pendingCount ?? 0) ||
29
31
  (result.pendingCount ?? 0) < 0 ||
30
32
  typeof result.skipped !== "boolean"
@@ -45,3 +45,52 @@ test.each([
45
45
  expect(mocks.run).toHaveBeenCalledOnce();
46
46
  }
47
47
  );
48
+
49
+ test("Vercel cron drains successful retirement batches in the same invocation", async () => {
50
+ mocks.run
51
+ .mockResolvedValueOnce({
52
+ success: false,
53
+ results: {
54
+ guests: {
55
+ deletedCount: 0,
56
+ retiredCount: 5,
57
+ pendingCount: 2,
58
+ skipped: false,
59
+ },
60
+ },
61
+ })
62
+ .mockResolvedValueOnce({
63
+ success: true,
64
+ results: {
65
+ guests: {
66
+ deletedCount: 0,
67
+ retiredCount: 2,
68
+ pendingCount: 0,
69
+ skipped: false,
70
+ },
71
+ },
72
+ });
73
+ const response = await GET({
74
+ headers: new Headers({ authorization: "Bearer scheduler-secret" }),
75
+ });
76
+ expect(response.status).toBe(200);
77
+ expect(mocks.run).toHaveBeenCalledTimes(2);
78
+ });
79
+ test("Vercel cron bounds a continuously growing backlog", async () => {
80
+ mocks.run.mockResolvedValue({
81
+ success: false,
82
+ results: {
83
+ guests: {
84
+ deletedCount: 0,
85
+ retiredCount: 5,
86
+ pendingCount: 100,
87
+ skipped: false,
88
+ },
89
+ },
90
+ });
91
+ const response = await GET({
92
+ headers: new Headers({ authorization: "Bearer scheduler-secret" }),
93
+ });
94
+ expect(response.status).toBe(503);
95
+ expect(mocks.run).toHaveBeenCalledTimes(20);
96
+ });
@@ -5,25 +5,28 @@ const batchStep = 1;
5
5
  const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
6
6
  typeof value === "object" && value !== null;
7
7
 
8
- const verifiedDeletedCount = (inventory: unknown): number => {
8
+ const verifiedCompletedCount = (inventory: unknown): number => {
9
9
  if (
10
10
  !isRecord(inventory) ||
11
11
  typeof inventory.deletedCount !== "number" ||
12
12
  !Number.isSafeInteger(inventory.deletedCount) ||
13
13
  inventory.deletedCount < emptyCount ||
14
+ typeof inventory.retiredCount !== "number" ||
15
+ !Number.isSafeInteger(inventory.retiredCount) ||
16
+ inventory.retiredCount < emptyCount ||
14
17
  typeof inventory.pendingCount !== "number" ||
15
18
  !Number.isSafeInteger(inventory.pendingCount) ||
16
19
  inventory.pendingCount < emptyCount ||
17
20
  (inventory.pendingCount > emptyCount &&
18
- inventory.deletedCount === emptyCount) ||
21
+ inventory.deletedCount + inventory.retiredCount === emptyCount) ||
19
22
  inventory.skipped !== false
20
23
  ) {
21
24
  throw new Error("Cleanup inventory unavailable; retry required.");
22
25
  }
23
- return inventory.deletedCount;
26
+ return inventory.deletedCount + inventory.retiredCount;
24
27
  };
25
28
 
26
- const deletedCount = (result: unknown): number => {
29
+ const completedCount = (result: unknown): number => {
27
30
  if (
28
31
  !isRecord(result) ||
29
32
  !isRecord(result.results) ||
@@ -36,9 +39,10 @@ const deletedCount = (result: unknown): number => {
36
39
  if (!isRecord(task) || "error" in task) {
37
40
  throw new Error("Cleanup failed; retry required.");
38
41
  }
39
- total += verifiedDeletedCount({
42
+ total += verifiedCompletedCount({
40
43
  ...task,
41
44
  pendingCount: task.pendingCount ?? 0,
45
+ retiredCount: task.retiredCount ?? 0,
42
46
  });
43
47
  }
44
48
  return total;
@@ -57,7 +61,7 @@ const drainCleanup = async (
57
61
  if (!response.ok && response.status !== 503) {
58
62
  throw new Error("Cleanup incomplete or unavailable; retry required.");
59
63
  }
60
- if (deletedCount(await response.json()) > emptyCount) {
64
+ if (completedCount(await response.json()) > emptyCount) {
61
65
  await drainCleanup(request, remaining - batchStep);
62
66
  return;
63
67
  }
@@ -1,7 +0,0 @@
1
- /// <reference types="next" />
2
- /// <reference types="next/image-types/global" />
3
- import "./.next/types/routes.d.ts";
4
- import "./.next/types/root-params.d.ts";
5
-
6
- // NOTE: This file should not be edited
7
- // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.