From 8db797eed83bbb9ca1065b71f167cce461327558 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 04:37:32 +0000 Subject: [PATCH 01/13] task: inbox slice G (questions into asks) Co-Authored-By: Claude Opus 5.5 --- ...11-16-inbox-slice-g-questions-into-asks.md | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md diff --git a/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md b/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md new file mode 100644 index 0000000000..def797b256 --- /dev/null +++ b/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md @@ -0,0 +1,120 @@ +# Inbox slice G: questions into `asks` + +SAM task `01M7H9J27FET6DZ0SVNTD8AN6X`. Spec: idea `01M7G03ZCQ6TM6CMEYDRKQ8ST9` (decision 8: one record +per ask, in D1; slice G in section 6). Coordination channel `feature.inbox`. Authorized through +production on 2026-11-16. Builds on slice A (PR #2776, `b3c04e1d3`). + +## Problem + +A question an agent asks with `request_human_input` is a ProjectData attention marker today +(`session_attention_markers`, kind `needs_input`, source `request_human_input`), copied into D1 +`session_summaries.attention_json` for the chat list and inbox. Decision 8 says every ask has one +record, in D1, with no copies. After this slice a new question is one `asks` row (kind `question`) +and nothing else: the row holds the ask, its status and its answer. Marker-era questions that +exist at deploy time stay answerable and archivable until they resolve or expire. + +## Research findings + +(Inventory of every reader and writer: see "Rule 44 inventory" below.) + +- `request_human_input` (`apps/api/src/routes/mcp/human-input-tool.ts`) validates context + (<= `MAX_HUMAN_INPUT_CONTEXT_LENGTH`), category, options; resolves the chat; creates a marker with + `computeHumanInputSchedule(env)`; sends `notifyNeedsInput` (metadata `attentionMarkerId`) and links + the notification to the marker; returns `{message, humanInputRequest:{id, sessionId}, + notificationScheduled}`. The chat card (`HumanInputCard`) loads the question by that id through + `GET /api/projects/:p/sessions/:s/attention/:markerId`. +- Answer today: `answerAttention` (`routes/chat-attention.ts`): `authorizeAgentWake` (writer: + owner or active grantee + wake policy) → DO claim (`prepareAttentionAnswer`, outcomes ready / + in_flight / already_resolved / conflicting_answer / invalid_option / not_found) → live-agent + prompt (`preparePromptForLiveAgent` + `sendPreparedPromptToLiveAgent`, dedup on marker id) → + `completeAttentionAnswer`. Response `{resolved, alreadyResolved, answer}` or 202 `{inFlight}`. + Archive (slice A) uses the same claim with an archive value. +- Expiry today (DO alarm, `attention-expiry.ts`): escalations at fractions of the window resend the + linked push; at `expires_at` without a confirmed push delivery the marker is extended by the + undelivered grace up to `max_expires_at`; at expiry the task is failed + (`transitionToTerminal`), work preserved (`preserveFailedWorkOrSurfaceLoss`) or the session + failed and the run released. Schedule from env `HUMAN_INPUT_*` (no GitHub Environment overrides + in staging or production, checked 2026-11-16). +- A typed human chat message resolves every open marker of the chat + (`message-persistence.ts:resolveAttentionForRoles`, `durability-foundation.ts` human prompt). +- Slice A gave `asks` a CAS writer (`closeAsk`), durable agent notices (`deliverInboxAskNotice`, + prompt source kind `inbox_ask`, `notified_at` + 5-minute sweep retry) and an expiry sweep + (`services/inbox/sweep.ts`). Durable prompt delivery wakes a sleeping chat (VM and Instant). +- The chat list reads attention from `session_summaries.attention_json` (D1 index, + `services/session-summary-index.ts`) or the DO (`listSessions` → `getAttentionSummary`). +- Connector operations (`attention-core.ts:pendingAttention`) read open markers per chat for + `sam_chat_read`, `sam_chat_interactions`, `sam_work_changes`; `sam_agent_answer` answers through + `ports.chat.answerAttention`. +- The stalled-task classifier keeps a task alive while a question is pending + (`hasPendingSessionHumanInput`). + +## Design + +- **Create.** `request_human_input` keeps its inputs and limits, files the question through the + shared `createAsk` (kind `question`, blocking, assignee = the task owner, title = first sentence + of the context capped at `inbox.titleMaxChars`, body = the full context, answer spec = options or + text, category, source session/task/workspace, schedule) and sends the same notification, linked + to the ask (`notification_id`). The tool result keeps its shape; `humanInputRequest.id` is the + ask id. +- **Answer (one shared operation).** Compare-and-set `open` → `answered` with the answer, bound to + project and chat; deliver through the durable prompt path (the wake path for sleeping chats) and + record `notified_at`; the inbox sweep retries an answer whose delivery was not queued. Outcomes for + the caller: accepted; already answered (same answer); conflicting answer; invalid option; still + being delivered (claimed, `notified_at` NULL, same answer → 202 inFlight). Callers: the attention + resolve route (chat card, notification deep link, `sam_agent_answer`) and the inbox answer route. +- **Typed chat message.** A human message in the chat closes the chat's open questions + (`answered`, no answer text, `notified_at` set: the message itself reached the agent), as it + resolves markers today. +- **Expiry and reminders** run from `asks` in the 5-minute inbox sweep with today's schedule + (window, reminder fractions, undelivered grace, hard maximum), read from admin settings + `inbox.question*`. At expiry the ask becomes `expired` and the same task outcome as today runs + (ProjectData RPC reusing the marker-expiry consequence). +- **Adapters, no web change.** The attention GET and resolve routes accept an ask id in place of a + marker id (asks first, marker fallback for marker-era questions) and return today's shapes. The + chat list overlays the chat's newest open question ask onto `attention`; the live read ranks + chats with an open question in the attention group. The Connector's pending attention merges + open question asks. The stalled-task guard reads `asks` then the DO. +- **Marker-era overlap.** Markers that exist at deploy keep their DO paths (answer, archive, + expiry, list via `attention_json`) until they resolve; no new question marker is written. + Removing the marker-era question code after the overlap is tracked (idea filed in this PR). +- **Migration** `0247_asks_questions.sql` (additive): `source_workspace_id`, `category`, + `notification_id`, `next_escalation_at`, `escalation_count`, `max_expires_at`; partial index + for due reminders. + +## Implementation checklist + +- [ ] Rule 44 inventory written below and in the PR +- [ ] Migration 0247 + drizzle columns +- [ ] Admin settings `inbox.questionTimeoutMinutes`, `inbox.questionFirstReminderPercent`, + `inbox.questionSecondReminderPercent`, `inbox.questionUndeliveredGraceMinutes`, + `inbox.questionMaxWaitMinutes` +- [ ] `createAsk` accepts question fields; `request_human_input` writes an ask, links notification +- [ ] Shared question answer operation (CAS + outcomes + durable delivery + notified_at) +- [ ] Inbox answer of a question goes through it; inbox archive of a question unchanged (asks) +- [ ] Attention GET/resolve adapters (ask first, marker fallback) +- [ ] Typed human message closes open question asks (both DO paths) +- [ ] Sweep: question reminders, undelivered-grace extension, expiry with task outcome +- [ ] Chat list overlay (index + DO fallback) and live-read ranking +- [ ] Connector pending attention merges question asks +- [ ] Stalled-task classifier reads asks +- [ ] Remove code that only served new needs_input question markers +- [ ] Tests: capability (ask → sleep → answer via inbox → woken once; archive), concurrent answers, + marker-era vs asks-era overlap, tenancy attack/owner pairs on real SQL (discriminating), + expiry/reminder schedule, chat list overlay, Connector projection +- [ ] Docs: API reference / admin settings / any doc describing request_human_input storage +- [ ] Idea for removing marker-era question code after overlap + +## Rule 44 inventory + +(filled in from the code inventory) + +## Acceptance criteria + +- [ ] A new request_human_input question is one `asks` row; no marker, no `attention_json` change +- [ ] Chat card, chat list needs-input state and the inbox show it as before +- [ ] Answer via chat card and via inbox: one wins under concurrency; same outcomes as today +- [ ] Answer to a sleeping chat wakes it and the agent receives the answer once; archive likewise +- [ ] Expiry and reminders keep today's schedule; expired ask ends `expired` +- [ ] Marker-era questions stay answerable/archivable until resolved or expired +- [ ] Tenancy guards on `asks` proven on real SQL with discriminating attack/owner pairs +- [ ] Limits are admin settings From 6133dcaaceed69e5440cfeb0b386c5f3fc3a235e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 04:49:58 +0000 Subject: [PATCH 02/13] feat(inbox): questions from request_human_input are D1 asks rows (slice G) request_human_input files one asks row (kind question) through createAsk; the answer is a compare-and-set on the row plus a durable prompt with notified_at and sweep retry; reminders, the undelivered grace and expiry run from asks in the inbox sweep with admin settings inbox.question*. The attention routes, chat list, ProjectData session reads, idea status, Connector reads, check-in hold and stalled-task guard read open questions from asks. Marker-era questions keep their ProjectData paths until they resolve. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/env-reference/SKILL.md | 2 +- .github/workflows/deploy-reusable.yml | 2 - apps/api/.env.example | 1 - .../src/db/migrations/0247_asks_questions.sql | 25 ++ .../durable-objects/project-data/attention.ts | 1 - apps/api/src/env.ts | 1 - apps/api/src/routes/chat-attention.ts | 85 ++++- apps/api/src/routes/mcp/human-input-tool.ts | 54 ++-- .../src/scheduled/stalled-task-classifier.ts | 13 +- apps/api/src/services/inbox/ask-notice.ts | 57 +++- apps/api/src/services/inbox/question-asks.ts | 302 ++++++++++++++++++ apps/api/src/services/inbox/sweep.ts | 176 +++++++++- .../api/src/services/session-summary-index.ts | 43 ++- .../omitted-worker-var-defaults.test.ts | 2 - packages/operations/src/attention-core.ts | 91 +++++- .../operations/src/connector-read-core.ts | 24 +- .../operations/src/inbox-question-schedule.ts | 67 ++++ .../src/inbox-settings-definition.ts | 38 +++ packages/operations/src/inbox-write-core.ts | 75 +++-- packages/operations/src/index.ts | 8 + packages/operations/src/ports.ts | 4 + .../project-data/src/client/project-data.ts | 41 +-- .../project-data/src/do/attention-expiry.ts | 41 +++ packages/project-data/src/do/attention.ts | 48 --- .../src/do/durability-foundation.ts | 20 ++ packages/project-data/src/do/idea-work.ts | 39 +++ packages/project-data/src/do/index.ts | 170 ++++++++-- .../src/do/message-persistence.ts | 6 + packages/project-data/src/do/question-asks.ts | 87 +++++ .../src/do/reconciliation-candidates.ts | 20 +- packages/project-data/src/do/types.ts | 1 - packages/project-data/src/index.ts | 1 - packages/shared/src/constants/index.ts | 1 - .../shared/src/constants/notifications.ts | 3 - packages/worker-core/src/index.ts | 11 + packages/worker-core/src/question-asks.ts | 211 ++++++++++++ packages/worker-core/src/schema.ts | 15 + scripts/deploy/installer-engine-ci-env.json | 1 - scripts/deploy/sync-wrangler-config.ts | 1 - scripts/deploy/worker-var-defaults.ts | 1 - .../quality/runtime-tunables-baseline.json | 1 - 41 files changed, 1595 insertions(+), 195 deletions(-) create mode 100644 apps/api/src/db/migrations/0247_asks_questions.sql create mode 100644 apps/api/src/services/inbox/question-asks.ts create mode 100644 packages/operations/src/inbox-question-schedule.ts create mode 100644 packages/project-data/src/do/question-asks.ts create mode 100644 packages/worker-core/src/question-asks.ts diff --git a/.claude/skills/env-reference/SKILL.md b/.claude/skills/env-reference/SKILL.md index 2a1b2dae18..8e1cf93c89 100644 --- a/.claude/skills/env-reference/SKILL.md +++ b/.claude/skills/env-reference/SKILL.md @@ -500,7 +500,7 @@ by the read-only cron-liveness check. ### Human Input and Web Push -- `HUMAN_INPUT_TIMEOUT_MS` — Initial needs-input response window (default: `7200000`) +- The question window is the admin setting `inbox.questionTimeoutMinutes` (slice G); the three `HUMAN_INPUT_*` variables below apply only to questions asked before it, held as attention markers - `HUMAN_INPUT_ESCALATION_FRACTIONS` — Comma-separated reminder points within the initial window (default: `0.25,0.75`) - `HUMAN_INPUT_UNDELIVERED_GRACE_MS` — Extension when no push delivery was confirmed (default: `7200000`) - `HUMAN_INPUT_MAX_WAIT_MS` — Hard maximum needs-input marker lifetime (default: `86400000`) diff --git a/.github/workflows/deploy-reusable.yml b/.github/workflows/deploy-reusable.yml index 45719423d9..fc73378c2e 100644 --- a/.github/workflows/deploy-reusable.yml +++ b/.github/workflows/deploy-reusable.yml @@ -1030,7 +1030,6 @@ jobs: CLOUD_INIT_CERT_REQUEST_TIMEOUT_SECONDS: ${{ vars.CLOUD_INIT_CERT_REQUEST_TIMEOUT_SECONDS }} TASK_RUNNER_FIRST_HEARTBEAT_TIMEOUT_MS: ${{ vars.TASK_RUNNER_FIRST_HEARTBEAT_TIMEOUT_MS }} TASK_RUNNER_BOOT_MAX_REPLACEMENTS: ${{ vars.TASK_RUNNER_BOOT_MAX_REPLACEMENTS }} - HUMAN_INPUT_TIMEOUT_MS: ${{ vars.HUMAN_INPUT_TIMEOUT_MS }} HUMAN_INPUT_ESCALATION_FRACTIONS: ${{ vars.HUMAN_INPUT_ESCALATION_FRACTIONS }} HUMAN_INPUT_UNDELIVERED_GRACE_MS: ${{ vars.HUMAN_INPUT_UNDELIVERED_GRACE_MS }} HUMAN_INPUT_MAX_WAIT_MS: ${{ vars.HUMAN_INPUT_MAX_WAIT_MS }} @@ -1901,7 +1900,6 @@ jobs: CLOUD_INIT_CERT_REQUEST_TIMEOUT_SECONDS: ${{ vars.CLOUD_INIT_CERT_REQUEST_TIMEOUT_SECONDS }} TASK_RUNNER_FIRST_HEARTBEAT_TIMEOUT_MS: ${{ vars.TASK_RUNNER_FIRST_HEARTBEAT_TIMEOUT_MS }} TASK_RUNNER_BOOT_MAX_REPLACEMENTS: ${{ vars.TASK_RUNNER_BOOT_MAX_REPLACEMENTS }} - HUMAN_INPUT_TIMEOUT_MS: ${{ vars.HUMAN_INPUT_TIMEOUT_MS }} HUMAN_INPUT_ESCALATION_FRACTIONS: ${{ vars.HUMAN_INPUT_ESCALATION_FRACTIONS }} HUMAN_INPUT_UNDELIVERED_GRACE_MS: ${{ vars.HUMAN_INPUT_UNDELIVERED_GRACE_MS }} HUMAN_INPUT_MAX_WAIT_MS: ${{ vars.HUMAN_INPUT_MAX_WAIT_MS }} diff --git a/apps/api/.env.example b/apps/api/.env.example index dd16853833..5ccc619005 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -1280,7 +1280,6 @@ INFOMANIAK_IP_POLL_INTERVAL_MS=3000 # NOTIFICATION_PROGRESS_BATCH_WINDOW_MS=300000 # Batch window for progress notifications (5 min) # NOTIFICATION_DEDUP_WINDOW_MS=60000 # Dedup window for task_complete notifications (60s) # NOTIFICATION_FULL_BODY_LENGTH=5000 # Max chars stored as fullMessage in notification metadata -# HUMAN_INPUT_TIMEOUT_MS=7200000 # Initial needs-input response window (2h) # HUMAN_INPUT_ESCALATION_FRACTIONS=0.25,0.75 # Reminder points within the initial window # HUMAN_INPUT_UNDELIVERED_GRACE_MS=7200000 # Extension without confirmed push delivery (2h) # HUMAN_INPUT_MAX_WAIT_MS=86400000 # Hard needs-input marker lifetime (24h) diff --git a/apps/api/src/db/migrations/0247_asks_questions.sql b/apps/api/src/db/migrations/0247_asks_questions.sql new file mode 100644 index 0000000000..fe2509b046 --- /dev/null +++ b/apps/api/src/db/migrations/0247_asks_questions.sql @@ -0,0 +1,25 @@ +-- Inbox slice G (idea 01M7G03ZCQ6TM6CMEYDRKQ8ST9): a question an agent asks with +-- request_human_input is one `asks` row (kind 'question') instead of a ProjectData attention +-- marker. These columns carry what the marker carried for the question's reminders and expiry +-- (`apps/api/src/services/inbox/sweep.ts`): +-- source_workspace_id the asking agent's workspace (the expiry outcome stops its task run) +-- category the request_human_input category +-- notification_id the notification sent for it (reminders resend its push; expiry +-- checks its delivery receipt) +-- next_escalation_at next reminder, NULL when none is left +-- escalation_count reminders sent +-- max_expires_at hard limit for extending an ask whose push was never delivered +-- +-- Additive only: nullable columns, one integer column with a default, one partial index. +-- Existing rows (reviews, tasks, errors filed since slice A) keep NULL / 0 and are unaffected: +-- the reminder sweep selects only rows with next_escalation_at set. +ALTER TABLE asks ADD COLUMN source_workspace_id TEXT; +ALTER TABLE asks ADD COLUMN category TEXT; +ALTER TABLE asks ADD COLUMN notification_id TEXT; +ALTER TABLE asks ADD COLUMN next_escalation_at INTEGER; +ALTER TABLE asks ADD COLUMN escalation_count INTEGER NOT NULL DEFAULT 0; +ALTER TABLE asks ADD COLUMN max_expires_at INTEGER; + +-- Due reminders. +CREATE INDEX idx_asks_open_escalation ON asks (next_escalation_at) + WHERE status = 'open' AND next_escalation_at IS NOT NULL; diff --git a/apps/api/src/durable-objects/project-data/attention.ts b/apps/api/src/durable-objects/project-data/attention.ts index 8647c27234..1badaca6e9 100644 --- a/apps/api/src/durable-objects/project-data/attention.ts +++ b/apps/api/src/durable-objects/project-data/attention.ts @@ -2,6 +2,5 @@ // worker's existing importers are unchanged. export { ATTENTION_ARCHIVE_CLAIM, - computeHumanInputSchedule, parseAttentionOptions, } from '@simple-agent-manager/project-data'; diff --git a/apps/api/src/env.ts b/apps/api/src/env.ts index c04d9b785c..ebef05fa41 100644 --- a/apps/api/src/env.ts +++ b/apps/api/src/env.ts @@ -992,7 +992,6 @@ export interface Env ORCHESTRATOR_STOP_CAS_MAX_ATTEMPTS?: string; // Max task-status CAS attempts after a hard stop (default: 2) ORCHESTRATOR_MESSAGE_MAX_LENGTH?: string; // Max length for injected messages to child agents (default: 32768) // Attention markers - HUMAN_INPUT_TIMEOUT_MS?: string; // Attention marker expiry for needs_input (default: 7200000 = 2 hours) HUMAN_INPUT_ESCALATION_FRACTIONS?: string; // Comma-separated fractions of initial window (default: 0.25,0.75) HUMAN_INPUT_UNDELIVERED_GRACE_MS?: string; // Extension without confirmed delivery (default: 7200000) HUMAN_INPUT_MAX_WAIT_MS?: string; // Hard marker residence limit (default: 86400000) diff --git a/apps/api/src/routes/chat-attention.ts b/apps/api/src/routes/chat-attention.ts index d9c87584ef..d5a094a294 100644 --- a/apps/api/src/routes/chat-attention.ts +++ b/apps/api/src/routes/chat-attention.ts @@ -5,7 +5,7 @@ */ import { HUMAN_INPUT_CATEGORIES, type HumanInputCategory } from '@simple-agent-manager/shared'; import { drizzle } from 'drizzle-orm/d1'; -import type { Hono } from 'hono'; +import type { Context, Hono } from 'hono'; import * as schema from '../db/schema'; import { @@ -28,6 +28,12 @@ import { import { parseOptionalBody, ResolveAttentionAnswerSchema } from '../schemas'; import { authorizeAgentWake } from '../services/agent-wake-authorization'; import { readAskContext } from '../services/inbox/ask-context'; +import { + answerQuestionAsk, + loadQuestionAsk, + type QuestionAsk, + questionAskRequestState, +} from '../services/inbox/question-asks'; import * as projectDataService from '../services/project-data'; import { recordSharedSessionAnswer } from '../services/session-access'; import { preparePromptForLiveAgent, sendPreparedPromptToLiveAgent } from './chat-prompt-forward'; @@ -82,6 +88,73 @@ export async function loadAttentionForViewer( }; } +/** + * The chat card's read of a question held in D1 `asks`, in the shape a marker read had. Who may + * read and answer is decided as for a marker: any reader of the chat reads it, a writer of the + * chat (owner, or a grantee whose owner can still write) answers it. + */ +async function questionAskAttentionResponse( + c: Context<{ Bindings: Env }>, + ask: QuestionAsk, + role: string, + userId: string +) { + const db = drizzle(c.env.DATABASE, { schema }); + const { session, access } = await projectDataService.getSessionAccess( + c.env, + ask.projectId, + ask.sessionId, + userId + ); + if (!session || !access.found || !projectRoleHasCapability(role, 'task:read')) + throw errors.notFound('Chat session'); + const writer = + Boolean(access.ownerUserId) && + projectRoleHasCapability(role, 'task:write') && + (access.role === 'owner' || + (access.role === 'grantee' && + Boolean(access.grant) && + (await hasProjectCapability(db, ask.projectId, access.ownerUserId ?? '', 'task:write')))); + const now = Date.now(); + const state = questionAskRequestState(ask, now); + const context = + c.req.query('context') === 'true' + ? await readAskContext(c.env, { + projectId: ask.projectId, + sessionId: ask.sessionId, + askedAt: ask.createdAt, + requestedLimit: Number(c.req.query('limit')), + }) + : null; + return { + request: { + id: ask.id, + reason: ask.reason, + options: ask.options, + category: ask.category, + createdAt: ask.createdAt, + resolvedAt: state.resolvedAt, + resolvedAnswer: state.resolvedAnswer, + expired: state.expired, + canAnswer: ask.status === 'open' && !state.expired && writer, + }, + session: { + id: ask.sessionId, + topic: typeof session.topic === 'string' ? session.topic : null, + }, + messages: (context?.before ?? []).map((message) => ({ + id: message.id, + sessionId: ask.sessionId, + role: message.role, + content: message.content, + createdAt: message.createdAt, + toolMetadata: null, + truncated: message.truncated, + })), + since: context?.since ?? null, + }; +} + export function registerChatAttentionRoute(chatRoutes: Hono<{ Bindings: Env }>): void { // Read-only: no runtime contact or whole-conversation fetch. Context is opt-in. chatRoutes.get('/:sessionId/attention/:markerId', async (c) => { @@ -93,6 +166,9 @@ export function registerChatAttentionRoute(chatRoutes: Hono<{ Bindings: Env }>): const { membership } = await requireActiveProjectMembership(db, projectId, userId); if (!projectRoleHasCapability(membership.role, 'task:read')) throw errors.forbidden('Project capability is required'); + // A question asked since inbox slice G is an `asks` row; one asked before is a marker. + const ask = await loadQuestionAsk(c.env, projectId, sessionId, markerId); + if (ask) return c.json(await questionAskAttentionResponse(c, ask, membership.role, userId)); const { session, marker, writer, canRead } = await loadAttentionForViewer( c.env, projectId, @@ -187,6 +263,13 @@ export async function answerAttention( if (!answer) throw markRejectedBeforeEffects(errors.badRequest('answer is required')); + // A question asked since inbox slice G is an `asks` row: one compare-and-set, then a durable + // prompt (`services/inbox/question-asks.ts`). One asked before is still a marker, below. + const ask = await loadQuestionAsk(env, projectId, sessionId, markerId); + if (ask) { + return answerQuestionAsk(env, { ask, answer, userId, authorization: { writer, wake } }); + } + const prepared = await projectDataService.prepareAttentionAnswer( env, projectId, diff --git a/apps/api/src/routes/mcp/human-input-tool.ts b/apps/api/src/routes/mcp/human-input-tool.ts index 25e7e17512..071fc3d492 100644 --- a/apps/api/src/routes/mcp/human-input-tool.ts +++ b/apps/api/src/routes/mcp/human-input-tool.ts @@ -1,7 +1,8 @@ /** - * MCP request_human_input — records a user decision request as a durable - * attention marker and notifies the user. The tool call itself is non-blocking. + * MCP request_human_input — files the question as one D1 `asks` row (kind `question`, inbox slice + * G, idea 01M7G03ZCQ6TM6CMEYDRKQ8ST9) and notifies the user. The tool call itself is non-blocking. */ +import { OperationError } from '@simple-agent-manager/operations'; import type { HumanInputCategory } from '@simple-agent-manager/shared'; import { HUMAN_INPUT_CATEGORIES, @@ -10,11 +11,10 @@ import { MAX_HUMAN_INPUT_OPTIONS_COUNT, } from '@simple-agent-manager/shared'; -import { computeHumanInputSchedule } from '../../durable-objects/project-data/attention'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; +import { fileQuestionAsk, linkQuestionNotification } from '../../services/inbox/question-asks'; import * as notificationService from '../../services/notification'; -import * as projectDataService from '../../services/project-data'; import { INTERNAL_ERROR, INVALID_PARAMS, @@ -124,29 +124,32 @@ export async function handleRequestHumanInput( ); } - const schedule = computeHumanInputSchedule(env); - let marker: Awaited>; + let question: Awaited>; try { - marker = await projectDataService.createAttentionMarker(env, tokenData.projectId, { + question = await fileQuestionAsk(env, { + projectId: tokenData.projectId, sessionId, taskId: tokenData.taskId, workspaceId: tokenData.workspaceId, - kind: 'needs_input', - source: 'request_human_input', - notificationUserId: tokenData.userId, - reason: sanitizedContext, - metadata: category || options ? JSON.stringify({ category, options }) : null, - ...schedule, + userId: tokenData.userId, + context: sanitizedContext, + category, + options, }); } catch (err) { - log.error('mcp.request_human_input.attention_marker_failed', { + log.error('mcp.request_human_input.ask_failed', { taskId: tokenData.taskId, error: err instanceof Error ? err.message : String(err), }); + // The per-chat cap and length limits are the inbox's; say which one the agent hit. + const limitHit = + err instanceof OperationError && ['rate_limited', 'invalid_input'].includes(err.code); return jsonRpcError( requestId, - INTERNAL_ERROR, - 'Human input request could not be recorded safely' + limitHit ? INVALID_PARAMS : INTERNAL_ERROR, + limitHit && err instanceof Error + ? err.message + : 'Human input request could not be recorded safely' ); } @@ -163,22 +166,16 @@ export async function handleRequestHumanInput( category, options, sessionId, - attentionMarkerId: marker.id, + attentionMarkerId: question.id, }); notificationScheduled = notification.id !== 'suppressed'; if (notificationScheduled) { - await projectDataService.linkAttentionNotification( - env, - tokenData.projectId, - marker.id, - tokenData.userId, - notification.id - ); + await linkQuestionNotification(env, tokenData.projectId, question.id, notification.id); } } catch (err) { log.warn('mcp.request_human_input.notification_failed', { taskId: tokenData.taskId, - markerId: marker.id, + askId: question.id, error: err instanceof Error ? err.message : String(err), }); } @@ -191,13 +188,14 @@ export async function handleRequestHumanInput( hasOptions: options !== null, }); - // JSON so the chat can render this call as an answerable card: the card reads the question - // from the attention marker by ID (see HumanInputCard in apps/web), never from chat text. + // JSON so the chat can render this call as an answerable card: the card reads the question by + // ID through the attention route (see HumanInputCard in apps/web), never from chat text. The ID + // is the `asks` row's; the route reads it there (`routes/chat-attention.ts`). const payload = { message: notificationScheduled ? 'Human input request recorded. Notification delivery has been scheduled. You may continue working or end your turn.' : 'Human input request recorded, but notification delivery was not scheduled. SAM will keep the task alive while waiting for delivery. You may continue working.', - humanInputRequest: { id: marker.id, sessionId }, + humanInputRequest: { id: question.id, sessionId }, notificationScheduled, }; return jsonRpcSuccess(requestId, { diff --git a/apps/api/src/scheduled/stalled-task-classifier.ts b/apps/api/src/scheduled/stalled-task-classifier.ts index dad050514d..8cb1e76c01 100644 --- a/apps/api/src/scheduled/stalled-task-classifier.ts +++ b/apps/api/src/scheduled/stalled-task-classifier.ts @@ -8,6 +8,7 @@ import { DEFAULT_STALLED_TASK_CLASSIFIER_TRANSCRIPT_MAX_CHARS, DEFAULT_TASK_LIVENESS_PROBE_TIMEOUT_MS, } from '@simple-agent-manager/shared'; +import { hasOpenQuestionAsk } from '@simple-agent-manager/worker-core'; import type { Env } from '../env'; import { redactCredentialTokens } from '../lib/credential-token-redaction'; @@ -189,8 +190,16 @@ async function isWaitingForHumanInput( ); }); try { - const [attentionPending, interactionPending] = await Promise.race([ + const [questionPending, attentionPending, interactionPending] = await Promise.race([ Promise.all([ + // A question in D1 `asks` (inbox slice G); a failed read throws into the fail-safe catch. + hasOpenQuestionAsk(env.DATABASE, { + projectId: task.project_id, + sessionId: task.chat_session_id, + taskId: task.id, + now: nowMs, + }), + // A question asked before slice G is still a ProjectData marker until it resolves. projectDataService.hasPendingSessionHumanInput( env, task.project_id, @@ -205,7 +214,7 @@ async function isWaitingForHumanInput( if (typeof attentionPending !== 'boolean' || typeof interactionPending !== 'boolean') { throw new Error('invalid human input probe response'); } - return attentionPending || interactionPending; + return questionPending || attentionPending || interactionPending; } finally { if (timer) clearTimeout(timer); } diff --git a/apps/api/src/services/inbox/ask-notice.ts b/apps/api/src/services/inbox/ask-notice.ts index 8a5c55188d..9643ff5ec4 100644 --- a/apps/api/src/services/inbox/ask-notice.ts +++ b/apps/api/src/services/inbox/ask-notice.ts @@ -35,8 +35,17 @@ export function buildInboxAskPrompt( outcome: InboxAskNoticeOutcome ): string { // Title and answer were bounded when written (`inbox.titleMaxChars`, `inbox.answerMaxChars`). - const item = `inbox item ${row.id} ("${row.title}")`; const answer = answerText(row.answerJson); + if (row.kind === 'question') { + // A request_human_input question (slice G). Its expiry stops the task instead of a notice + // (`deliverInboxAskNotice`). + const question = `your question ("${row.title}")`; + if (outcome === 'archived') { + return `The person archived ${question} from their inbox and will not act on it. Do not wait for an answer: continue without it, or end your turn and say what is left undone.`; + } + return answer ? `The person answered ${question}:\n\n${answer}` : `The person answered ${question}.`; + } + const item = `inbox item ${row.id} ("${row.title}")`; switch (outcome) { case 'answered': return answer @@ -81,6 +90,9 @@ export async function deliverInboxAskNotice( ): Promise { // Nothing filed it from a chat, so there is no agent to tell. if (!row.sourceSessionId) return true; + if (row.kind === 'question' && outcome === 'expired') { + return expireQuestion(env, { ...row, sourceSessionId: row.sourceSessionId }); + } const creatorUserId = row.resolvedByUserId ?? row.assigneeUserId; if (!creatorUserId || !row.sourceTaskId) { // The delivery guard needs both; without them the notice could wake an unrelated chat. @@ -110,7 +122,13 @@ export async function deliverInboxAskNotice( messageClass: 'deliver', sourceKind: 'inbox_ask', ttlMs: config.ttlMs, - metadata: { askId: row.id, outcome, creatorUserId }, + // `questionAskId` clears the chat's question live (`durability-foundation.ts`). + metadata: { + askId: row.id, + outcome, + creatorUserId, + ...(row.kind === 'question' ? { questionAskId: row.id } : {}), + }, notice: safeNotice(() => askNotice(row, outcome), { askId: row.id }), }); return true; @@ -125,3 +143,38 @@ export async function deliverInboxAskNotice( return false; } } + +/** + * An expired question has the outcome a question marker's expiry had: the asking task stops and + * its work is preserved (`ProjectData.expireQuestionAsk`). `notified_at` records that this ran; + * a failed call leaves it NULL and the sweep retries it. True when it ran. + */ +async function expireQuestion( + env: Env, + row: InboxAskNoticeRow & { sourceSessionId: string } +): Promise { + try { + const result = await projectDataService.expireQuestionAsk(env, row.projectId, { + askId: row.id, + sessionId: row.sourceSessionId, + taskId: row.sourceTaskId, + workspaceId: row.sourceWorkspaceId, + createdAt: row.createdAt ?? 0, + }); + log.info('inbox_ask.question_expired', { + askId: row.id, + projectId: row.projectId, + sessionId: row.sourceSessionId, + outcome: result.outcome, + }); + return true; + } catch (error) { + log.error('inbox_ask.question_expiry_failed', { + askId: row.id, + projectId: row.projectId, + sessionId: row.sourceSessionId, + ...serializeError(error), + }); + return false; + } +} diff --git a/apps/api/src/services/inbox/question-asks.ts b/apps/api/src/services/inbox/question-asks.ts new file mode 100644 index 0000000000..6043838f06 --- /dev/null +++ b/apps/api/src/services/inbox/question-asks.ts @@ -0,0 +1,302 @@ +/** + * Agent questions held in D1 `asks` (inbox slice G, idea 01M7G03ZCQ6TM6CMEYDRKQ8ST9): filing one + * for `request_human_input`, answering one, and reading one for the chat card. The row is the + * record of truth for the question, its status and its answer; nothing else holds a copy. + * + * Answering is one compare-and-set on the row's status (`open` → `answered`), bound to the + * project and the chat (rule 11), then the answer goes to the agent as a durable prompt + * (`deliverInboxAskNotice`, the wake path for a sleeping chat) and `notified_at` is recorded. A + * delivery that was not queued keeps `notified_at` NULL and the inbox sweep retries it. + */ +import { + createAsk, + getInboxLimits, + inboxTitle, + loadAskNoticeRow, + notifyClosedAsk, + questionSchedule, +} from '@simple-agent-manager/operations'; +import type { HumanInputCategory } from '@simple-agent-manager/shared'; +import { HUMAN_INPUT_CATEGORIES } from '@simple-agent-manager/shared'; +import { maybeJsonRecord, questionOptions } from '@simple-agent-manager/worker-core'; + +import type { Env } from '../../env'; +import { agentWakeRecord } from '../../lib/agent-wake-policy'; +import { log } from '../../lib/logger'; +import { markRejectedBeforeEffects } from '../../lib/operation-effect-boundary'; +import { errors } from '../../middleware/error'; +import { createOperationPorts } from '../../operation-ports'; +import type { authorizeAgentWake } from '../agent-wake-authorization'; +import * as projectDataService from '../project-data'; +import { recordSharedSessionAnswer } from '../session-access'; + +export interface QuestionAsk { + id: string; + projectId: string; + sessionId: string; + taskId: string | null; + title: string; + reason: string | null; + options: string[]; + category: HumanInputCategory | null; + status: string; + answer: string | null; + createdAt: number; + expiresAt: number | null; + resolvedAt: number | null; + notifiedAt: number | null; +} + +function int(value: unknown): number | null { + return typeof value === 'number' && Number.isSafeInteger(value) ? value : null; +} + +function text(value: unknown): string | null { + return typeof value === 'string' && value ? value : null; +} + +/** The typed answer recorded on the row (`{text}`), or null (archived, expired, chat message). */ +export function askAnswerText(answerJson: unknown): string | null { + if (typeof answerJson !== 'string' || !answerJson) return null; + try { + return text(maybeJsonRecord(JSON.parse(answerJson) as unknown)?.text); + } catch { + return null; + } +} + +function parseQuestionAsk(row: Record): QuestionAsk | null { + const id = text(row.id); + const projectId = text(row.project_id); + const sessionId = text(row.source_session_id); + const status = text(row.status); + const createdAt = int(row.created_at); + if (!id || !projectId || !sessionId || !status || createdAt === null) return null; + const category = text(row.category); + return { + id, + projectId, + sessionId, + taskId: text(row.source_task_id), + title: text(row.title) ?? '', + reason: text(row.body_md) ?? text(row.title), + options: questionOptions(row.answer_spec_json), + category: (HUMAN_INPUT_CATEGORIES as readonly unknown[]).includes(category) + ? (category as HumanInputCategory) + : null, + status, + answer: askAnswerText(row.answer_json), + createdAt, + expiresAt: int(row.expires_at), + resolvedAt: int(row.resolved_at), + notifiedAt: int(row.notified_at), + }; +} + +/** + * One question of one chat, or null. Project, chat and kind are all in the predicate, so an id + * from another project or chat reads as missing (rule 11). + */ +export async function loadQuestionAsk( + env: Env, + projectId: string, + sessionId: string, + askId: string +): Promise { + const row = await env.DATABASE.prepare( + `SELECT id, project_id, source_session_id, source_task_id, title, body_md, answer_spec_json, + category, status, answer_json, created_at, expires_at, resolved_at, notified_at + FROM asks + WHERE id = ? AND project_id = ? AND source_session_id = ? AND kind = 'question'` + ) + .bind(askId, projectId, sessionId) + .first>(); + if (!row) return null; + const ask = parseQuestionAsk(row); + if (!ask) { + // A malformed row is a clean not-found, never an opaque 500 (rule 50). + log.warn('question_ask.row_unreadable', { askId, projectId }); + } + return ask; +} + +export type QuestionAnswerResult = + | { resolved: true; alreadyResolved: boolean; answer: string } + | { resolved: false; alreadyResolved: false; inFlight: true; answer: string }; + +/** A question that is no longer open, answered the way an attention marker answered. */ +function settledOutcome(ask: QuestionAsk, answer: string): QuestionAnswerResult { + if (ask.status === 'answered' && ask.answer === answer) { + return ask.notifiedAt === null + ? { resolved: false, alreadyResolved: false, inFlight: true, answer } + : { resolved: true, alreadyResolved: true, answer }; + } + if (ask.status === 'answered' && ask.answer !== null && ask.notifiedAt === null) { + throw markRejectedBeforeEffects( + errors.conflict('A different answer is already being delivered') + ); + } + throw markRejectedBeforeEffects(errors.conflict('Attention request is already resolved')); +} + +/** + * Answer an open question. The caller has authorized the answer (`authorizeAgentWake`: a writer + * of the chat whose wake policy allows it). Outcomes, as for a question marker: + * accepted; already answered (same answer); a different answer already being delivered or the + * question already resolved (409); an answer outside the options (400); still being delivered + * (202 `inFlight`). + */ +export async function answerQuestionAsk( + env: Env, + input: { + ask: QuestionAsk; + answer: string; + userId: string; + authorization: Awaited>; + } +): Promise { + const { ask, answer, userId } = input; + if (ask.status !== 'open') return settledOutcome(ask, answer); + const now = Date.now(); + if (ask.expiresAt !== null && ask.expiresAt <= now) { + throw markRejectedBeforeEffects(errors.conflict('This question expired')); + } + if (ask.options.length > 0 && !ask.options.includes(answer)) { + throw markRejectedBeforeEffects( + errors.badRequest('answer must match one of the requested options') + ); + } + const claimed = await env.DATABASE.prepare( + `UPDATE asks + SET status = 'answered', answer_json = ?, resolved_by_user_id = ?, resolved_at = ?, + updated_at = ? + WHERE id = ? AND project_id = ? AND source_session_id = ? AND kind = 'question' + AND status = 'open' AND (expires_at IS NULL OR expires_at > ?)` + ) + .bind(JSON.stringify({ text: answer }), userId, now, now, ask.id, ask.projectId, ask.sessionId, now) + .run(); + if ((claimed.meta?.changes ?? 0) !== 1) { + // Someone else settled it first: report what they did. + const current = await loadQuestionAsk(env, ask.projectId, ask.sessionId, ask.id); + if (!current) throw markRejectedBeforeEffects(errors.notFound('Attention request')); + if (current.status === 'open') throw markRejectedBeforeEffects(errors.conflict('This question expired')); + return settledOutcome(current, answer); + } + + const deps = { env, ports: createOperationPorts(env) }; + const row = await loadAskNoticeRow(deps, ask.projectId, ask.id); + const queued = row ? await notifyClosedAsk(deps, row, 'answered') : false; + // A teammate's answer is recorded on the shared-answer audit event, as for a marker. + await recordSharedSessionAnswer(env, input.authorization.writer, { + markerId: ask.id, + wake: agentWakeRecord(input.authorization.wake), + }); + return queued + ? { resolved: true, alreadyResolved: false, answer } + : { resolved: false, alreadyResolved: false, inFlight: true, answer }; +} + +/** `request.resolvedAt` / `resolvedAnswer` as the chat card read them from a marker. */ +export function questionAskRequestState(ask: QuestionAsk, now: number) { + // An answer that has not reached the agent yet is in flight: a marker showed it as a staged + // answer with no resolution time. + const delivering = ask.status === 'answered' && ask.answer !== null && ask.notifiedAt === null; + return { + resolvedAt: ask.status === 'open' || delivering ? null : ask.resolvedAt, + resolvedAnswer: ask.status === 'answered' ? ask.answer : null, + expired: ask.status === 'expired' || (ask.expiresAt !== null && ask.expiresAt <= now), + }; +} + +export interface FileQuestionInput { + projectId: string; + sessionId: string; + taskId: string; + workspaceId: string | null; + userId: string; + context: string; + category: HumanInputCategory | null; + options: string[] | null; +} + +/** + * File a `request_human_input` question as an `asks` row through the shared create operation + * (`createAsk`): assignee, per-chat cap and lengths are its checks; the schedule is the + * `inbox.question*` settings. The chat list shows it live (`recordQuestionAsked`). + */ +export async function fileQuestionAsk( + env: Env, + input: FileQuestionInput +): Promise<{ id: string; createdAt: number; expiresAt: number }> { + const ports = createOperationPorts(env); + const ctx = { + env, + ports, + requestId: '', + actor: { + userId: input.userId, + via: 'workspace-agent' as const, + scopes: new Set(['sam.write'] as const), + workspace: { + workspaceId: input.workspaceId ?? '', + taskId: input.taskId, + projectId: input.projectId, + }, + }, + }; + const limits = await getInboxLimits(ctx); + const now = Date.now(); + const schedule = questionSchedule(limits, now); + const created = await createAsk(ctx, { + projectId: input.projectId, + assigneeKind: 'user', + assigneeUserId: input.userId, + kind: 'question', + blocking: true, + title: inboxTitle(input.context, limits.titleMaxChars), + body: input.context, + answerSpec: input.options?.length + ? { type: 'options', options: input.options, allowText: false } + : { type: 'text' }, + sourceSessionId: input.sessionId, + sourceTaskId: input.taskId, + sourceWorkspaceId: input.workspaceId ?? undefined, + category: input.category ?? undefined, + expiresAt: schedule.expiresAt, + nextEscalationAt: schedule.nextEscalationAt ?? undefined, + maxExpiresAt: schedule.maxExpiresAt, + }); + try { + await projectDataService.recordQuestionAsked(env, input.projectId, { + sessionId: input.sessionId, + askId: created.id, + createdAt: now, + expiresAt: schedule.expiresAt, + reason: input.context, + options: input.options ?? [], + }); + } catch (error) { + // The question is filed; the chat list shows it on its next read. + log.warn('question_ask.live_update_failed', { + askId: created.id, + projectId: input.projectId, + error: error instanceof Error ? error.message : String(error), + }); + } + return { id: created.id, createdAt: now, expiresAt: schedule.expiresAt }; +} + +/** Link the notification sent for a question, so reminders resend its push (`sweep.ts`). */ +export async function linkQuestionNotification( + env: Env, + projectId: string, + askId: string, + notificationId: string +): Promise { + await env.DATABASE.prepare( + `UPDATE asks SET notification_id = ?, updated_at = ? + WHERE id = ? AND project_id = ? AND kind = 'question' AND status = 'open'` + ) + .bind(notificationId, Date.now(), askId, projectId) + .run(); +} diff --git a/apps/api/src/services/inbox/sweep.ts b/apps/api/src/services/inbox/sweep.ts index 6401069e42..cbfc2f8de2 100644 --- a/apps/api/src/services/inbox/sweep.ts +++ b/apps/api/src/services/inbox/sweep.ts @@ -1,22 +1,32 @@ /** * Five-minute inbox sweep, isolated in the cron (`scheduled/handler.ts`): - * 1. expire open asks past `expires_at` (compare-and-set on `open`) and tell the agent; + * 0. send due question reminders (push resend at the `inbox.question*Percent` points; slice G); + * 1. expire open asks past `expires_at` (compare-and-set on `open`) and tell the agent. A question + * whose push no device confirmed is first extended by `inbox.questionUndeliveredGraceMinutes`, + * up to its `max_expires_at` (the delivery contract of rule 47 requirement 8); an expired + * question stops its task, as a question marker's expiry did (`ask-notice.ts`); * 2. retry notices that were not queued (`notified_at IS NULL` on a closed ask) for * `inbox.noticeRetryMinutes` after the item closed, the way the secret request sweep retries * `runtime_secret_requests.notified_at`. - * Both steps share one budget of `inbox.sweepBatchSize` rows, so a tick is bounded (rule 47); - * a notice past its retry window leaves the candidate set. + * The steps share one budget of `inbox.sweepBatchSize` rows, so a tick is bounded (rule 47); + * every selected row leaves the candidate set: a reminder advances `next_escalation_at`, an + * extension moves `expires_at`, an expiry closes the row, a notice past its window ages out. + * The schedule has the ProjectData marker alarm's precision of one sweep tick (five minutes). */ import { getInboxLimits, type InboxAskNoticeOutcome, type InboxAskNoticeRow, + type InboxLimits, + nextQuestionReminderAt, notifyClosedAsk, + questionUndeliveredExtension, } from '@simple-agent-manager/operations'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { createOperationPorts } from '../../operation-ports'; +import { notificationsPort } from '../../project-data-ports/notifications'; /** * A notice is retried only once its inline attempt is at least this old, so the sweep does not race @@ -25,7 +35,10 @@ import { createOperationPorts } from '../../operation-ports'; const NOTICE_RETRY_GRACE_MS = 60_000; const NOTICE_COLUMNS = `id, project_id, kind, title, status, answer_json, source_session_id, - source_task_id, resolved_by_user_id, assignee_user_id`; + source_task_id, source_workspace_id, created_at, resolved_by_user_id, assignee_user_id`; +/** A question's schedule columns (migration 0247), read with the notice columns. */ +const SCHEDULE_COLUMNS = `${NOTICE_COLUMNS}, expires_at, max_expires_at, notification_id, + next_escalation_at, escalation_count`; function noticeRow(row: Record): InboxAskNoticeRow | null { const text = (value: unknown) => (typeof value === 'string' ? value : null); @@ -44,6 +57,8 @@ function noticeRow(row: Record): InboxAskNoticeRow | null { answerJson: text(row.answer_json), sourceSessionId: text(row.source_session_id), sourceTaskId: text(row.source_task_id), + sourceWorkspaceId: text(row.source_workspace_id), + createdAt: typeof row.created_at === 'number' ? row.created_at : null, resolvedByUserId: text(row.resolved_by_user_id), assigneeUserId: text(row.assignee_user_id), }; @@ -59,6 +74,126 @@ const OUTCOMES: Record = { export interface InboxSweepStats { expired: number; noticesRetried: number; + remindersSent: number; + extended: number; +} + +function num(value: unknown): number | null { + return typeof value === 'number' && Number.isSafeInteger(value) ? value : null; +} + +/** Resend a question's push. Best-effort: a reminder that fails is not retried. */ +async function resendQuestionPush(env: Env, raw: Record): Promise { + const userId = typeof raw.assignee_user_id === 'string' ? raw.assignee_user_id : null; + const notificationId = typeof raw.notification_id === 'string' ? raw.notification_id : null; + if (!userId || !notificationId) return; + try { + await notificationsPort.resendPush(env, userId, notificationId); + } catch (error) { + log.warn('inbox_ask.question_push_resend_failed', { + askId: raw.id, + error: error instanceof Error ? error.message : String(error), + }); + } +} + +/** Whether a device confirmed the question's push; an unreadable receipt is "no" (fail safe). */ +async function questionPushConfirmed(env: Env, raw: Record): Promise { + const userId = typeof raw.assignee_user_id === 'string' ? raw.assignee_user_id : null; + const notificationId = typeof raw.notification_id === 'string' ? raw.notification_id : null; + if (!userId || !notificationId) return false; + try { + return await notificationsPort.hasConfirmedPushDelivery(env, userId, notificationId); + } catch (error) { + log.warn('inbox_ask.question_receipt_check_failed', { + askId: raw.id, + error: error instanceof Error ? error.message : String(error), + }); + return false; + } +} + +/** Step 0: due question reminders. Returns how many rows it selected. */ +async function sendDueQuestionReminders( + env: Env, + limits: InboxLimits, + now: number, + budget: number +): Promise<{ selected: number; sent: number }> { + const due = await env.DATABASE.prepare( + `SELECT ${SCHEDULE_COLUMNS} FROM asks + WHERE status = 'open' AND next_escalation_at IS NOT NULL AND next_escalation_at <= ? + AND (expires_at IS NULL OR expires_at > ?) + ORDER BY next_escalation_at LIMIT ?` + ) + .bind(now, now, budget) + .all>(); + let sent = 0; + for (const raw of due.results ?? []) { + try { + const count = num(raw.escalation_count) ?? 0; + const createdAt = num(raw.created_at); + const next = + createdAt === null + ? null + : nextQuestionReminderAt( + { createdAt, expiresAt: num(raw.expires_at), escalationCount: count }, + limits + ); + // Compare-and-set on the count read, so two ticks never send the same reminder twice. + const advanced = await env.DATABASE.prepare( + `UPDATE asks SET escalation_count = ?, next_escalation_at = ?, updated_at = ? + WHERE id = ? AND project_id = ? AND status = 'open' AND escalation_count = ?` + ) + .bind(count + 1, next, now, raw.id, raw.project_id, count) + .run(); + if ((advanced.meta?.changes ?? 0) !== 1) continue; + await resendQuestionPush(env, raw); + sent += 1; + } catch (error) { + log.warn('inbox_ask.question_reminder_failed', { + askId: raw.id, + error: error instanceof Error ? error.message : String(error), + }); + } + } + return { selected: (due.results ?? []).length, sent }; +} + +/** + * A question at its deadline whose push no device confirmed is kept open for the undelivered + * grace, up to its hard limit, and its push resent. True when it was extended. + */ +async function extendUndeliveredQuestion( + env: Env, + limits: InboxLimits, + raw: Record, + now: number +): Promise { + const createdAt = num(raw.created_at); + if (raw.kind !== 'question' || createdAt === null) return false; + if (await questionPushConfirmed(env, raw)) return false; + const { maxExpiresAt, extendedExpiry } = questionUndeliveredExtension( + limits, + { createdAt, maxExpiresAt: num(raw.max_expires_at) }, + now + ); + if (now >= maxExpiresAt || extendedExpiry <= now) return false; + const extended = await env.DATABASE.prepare( + `UPDATE asks SET expires_at = ?, next_escalation_at = NULL, updated_at = ? + WHERE id = ? AND project_id = ? AND status = 'open' AND expires_at = ?` + ) + .bind(extendedExpiry, now, raw.id, raw.project_id, raw.expires_at) + .run(); + if ((extended.meta?.changes ?? 0) !== 1) return true; + log.warn('inbox_ask.question_expiry_deferred_without_delivery', { + askId: raw.id, + projectId: raw.project_id, + extendedExpiry, + maxExpiresAt, + }); + await resendQuestionPush(env, raw); + return true; } export async function runInboxAskSweep(env: Env, now = Date.now()): Promise { @@ -67,9 +202,17 @@ export async function runInboxAskSweep(env: Env, now = Date.now()): Promise 0 || noticesRetried > 0) { - log.info('inbox_ask.sweep', { expired, noticesRetried }); + if (expired > 0 || noticesRetried > 0 || reminders.sent > 0 || extended > 0) { + log.info('inbox_ask.sweep', { expired, noticesRetried, remindersSent: reminders.sent, extended }); } - return { expired, noticesRetried }; + return { expired, noticesRetried, remindersSent: reminders.sent, extended }; } diff --git a/apps/api/src/services/session-summary-index.ts b/apps/api/src/services/session-summary-index.ts index 38cc754e72..4492113159 100644 --- a/apps/api/src/services/session-summary-index.ts +++ b/apps/api/src/services/session-summary-index.ts @@ -21,6 +21,11 @@ * availability (see `listSessionsFromIndex`). */ import { DEFAULT_SESSION_INDEX_MAX_STALENESS_MS } from '@simple-agent-manager/shared'; +import { + preferAttention, + type QuestionAttentionSummary, + readOpenQuestionAttention, +} from '@simple-agent-manager/worker-core'; import * as v from 'valibot'; import type { Env } from '../env'; @@ -270,7 +275,7 @@ async function readIndex( .prepare( `SELECT ${columns} FROM ( SELECT ${columns}, ROW_NUMBER() OVER ( - PARTITION BY status, attention_json IS NOT NULL + PARTITION BY status, (attention_json IS NOT NULL OR ${OPEN_QUESTION_EXISTS}) ORDER BY COALESCE(last_message_at, created_at, started_at) DESC, id DESC ) AS status_rank FROM session_summaries @@ -296,7 +301,9 @@ async function readIndex( // awake ones. Sessions carrying an attention marker are ranked in their own group, // so newer quiet chats cannot crowd out an older one that is waiting on a person. It is an extra on top of the page: if it fails, serve the page without // it rather than turning a good index read into a Durable Object fallback. - const [countRow, page, live] = await Promise.all([ + // Open questions live in D1 `asks` (inbox slice G), not in `attention_json`; one indexed read + // for the project, merged into each chat's attention below. + const [countRow, page, live, questions] = await Promise.all([ db .prepare(`SELECT COUNT(*) as cnt FROM session_summaries WHERE ${whereClause}`) .bind(...params) @@ -308,12 +315,19 @@ async function readIndex( .bind(...params, query.limit, query.offset) .all>(), readLive ? readLiveRows() : null, + readOpenQuestionAttention(db, { + projectId: query.projectId, + assigneeUserId: query.createdByUserId ?? null, + now: Date.now(), + }), ]); const total = countRow?.cnt ?? 0; const rows = page.results ?? []; - const sessions = mapIndexRows(env, query.projectId, rows); - const liveSessions = live ? mapIndexRows(env, query.projectId, live.results ?? []) : []; + const sessions = withQuestionAttention(mapIndexRows(env, query.projectId, rows), questions); + const liveSessions = live + ? withQuestionAttention(mapIndexRows(env, query.projectId, live.results ?? []), questions) + : []; // Mirrors the DO: `rows.length` is the raw SQL-fetched count, so post-fetch // skips cannot make `hasMore` claim the window reached the end when it did not. @@ -322,6 +336,27 @@ async function readIndex( return { result: { sessions: appendMissingSessions(sessions, liveSessions), total, hasMore } }; } +/** + * A chat holds an open question in D1 `asks` (inbox slice G). Correlated on the row being ranked; + * `idx_asks_session_status` answers it. + */ +const OPEN_QUESTION_EXISTS = `EXISTS ( + SELECT 1 FROM asks a + WHERE a.source_session_id = session_summaries.id AND a.project_id = session_summaries.project_id + AND a.kind = 'question' AND a.status = 'open')`; + +/** Each chat's attention with its open question merged in, as the ProjectData read does. */ +function withQuestionAttention( + sessions: Record[], + questions: ReadonlyMap +): Record[] { + if (questions.size === 0) return sessions; + return sessions.map((session) => { + const question = typeof session.id === 'string' ? questions.get(session.id) : undefined; + return question ? { ...session, attention: preferAttention(session.attention, question) } : session; + }); +} + /** * Map index rows with per-row isolation (.claude/rules/50): one row that fails the schema * — a legacy shape, a NULL where the schema wants a number — must degrade to "that row is diff --git a/apps/api/tests/unit/config/omitted-worker-var-defaults.test.ts b/apps/api/tests/unit/config/omitted-worker-var-defaults.test.ts index 09cde8292b..835514ef5c 100644 --- a/apps/api/tests/unit/config/omitted-worker-var-defaults.test.ts +++ b/apps/api/tests/unit/config/omitted-worker-var-defaults.test.ts @@ -32,7 +32,6 @@ import { } from '@simple-agent-manager/project-data/internal/client/project-data-archive-routing'; import { resolveArchiveHashPageRows } from '@simple-agent-manager/project-data/internal/do/archive-sharding'; import { - computeHumanInputSchedule, humanInputMaxWaitMs, humanInputUndeliveredGraceMs, parseHumanInputEscalationFractions, @@ -240,7 +239,6 @@ const READ_PATHS: readonly ReadPath[] = [ `packages/project-data/src/do/attention-expiry.ts`, ], read: (env) => [ - computeHumanInputSchedule(env, 0), parseHumanInputEscalationFractions(env.HUMAN_INPUT_ESCALATION_FRACTIONS), humanInputMaxWaitMs(env.HUMAN_INPUT_MAX_WAIT_MS), humanInputUndeliveredGraceMs(env.HUMAN_INPUT_UNDELIVERED_GRACE_MS), diff --git a/packages/operations/src/attention-core.ts b/packages/operations/src/attention-core.ts index 109de32492..558d2a16b6 100644 --- a/packages/operations/src/attention-core.ts +++ b/packages/operations/src/attention-core.ts @@ -16,7 +16,12 @@ import { MAX_HUMAN_INPUT_OPTION_LENGTH, MAX_HUMAN_INPUT_OPTIONS_COUNT, } from '@simple-agent-manager/shared'; -import { log, maybeJsonRecord } from '@simple-agent-manager/worker-core'; +import { + log, + maybeJsonRecord, + QUESTION_ASK_SOURCE, + questionOptions, +} from '@simple-agent-manager/worker-core'; import type { OperationProjectDataPort } from './ports'; import type { OperationDeps } from './types'; @@ -106,9 +111,77 @@ export function projectAttentionMarker(marker: Marker) { export type PendingAttentionItem = ReturnType; +function num(value: unknown): number | null { + return typeof value === 'number' && Number.isSafeInteger(value) ? value : null; +} + +function str(value: unknown): string | null { + return typeof value === 'string' && value ? value : null; +} + +/** + * The chat's open questions held in D1 `asks` (inbox slice G), as the marker records they replace, + * so one projection serves both. Bound to the project and the chat (rule 11). Newest first. + */ +async function openQuestionMarkers( + deps: OperationDeps, + projectId: string, + sessionId: string +): Promise { + const result = await deps.env.DATABASE.prepare( + `SELECT id, source_task_id, source_workspace_id, title, body_md, answer_spec_json, category, + created_at, expires_at, max_expires_at, escalation_count, next_escalation_at, + notification_id, assignee_user_id + FROM asks + WHERE project_id = ? AND source_session_id = ? AND kind = 'question' AND status = 'open' + ORDER BY created_at DESC, id DESC + LIMIT ?` + ) + .bind(projectId, sessionId, MAX_OPEN_QUESTIONS_PER_READ) + .all>(); + const markers: Marker[] = []; + for (const row of result.results ?? []) { + const id = str(row.id); + const createdAt = num(row.created_at); + if (!id || createdAt === null) continue; + markers.push({ + id, + sessionId, + taskId: str(row.source_task_id), + workspaceId: str(row.source_workspace_id), + kind: 'needs_input', + source: QUESTION_ASK_SOURCE, + sourceEventId: null, + sourceMessageId: null, + sourceNotificationId: str(row.notification_id), + reason: str(row.body_md) ?? str(row.title), + metadata: JSON.stringify({ + category: str(row.category), + options: questionOptions(row.answer_spec_json), + }), + createdAt, + expiresAt: num(row.expires_at), + resolvedAt: null, + resolvedByMessageId: null, + resolvedByActorType: null, + resolvedReason: null, + notificationUserId: str(row.assignee_user_id), + nextEscalationAt: num(row.next_escalation_at), + escalationCount: num(row.escalation_count) ?? 0, + maxExpiresAt: num(row.max_expires_at), + resolvedAnswer: null, + }); + } + return markers; +} + +/** A chat holds at most `inbox.openItemsPerChat` open asks; this read is bounded on its own. */ +const MAX_OPEN_QUESTIONS_PER_READ = 50; + /** - * Open markers for one chat. A failed read degrades to `unavailable` rather than failing the - * caller's whole read, and says so: an empty list must mean "nothing open". + * Open markers and open questions for one chat, newest first. A failed read degrades to + * `unavailable` rather than failing the caller's whole read, and says so: an empty list must + * mean "nothing open". */ export async function pendingAttention( deps: OperationDeps, @@ -116,8 +189,16 @@ export async function pendingAttention( sessionId: string ): Promise<{ items: PendingAttentionItem[]; available: boolean }> { try { - const markers = await deps.ports.projectData.listActiveAttentionMarkers(projectId, sessionId); - return { items: markers.map(projectAttentionMarker), available: true }; + const [markers, questions] = await Promise.all([ + deps.ports.projectData.listActiveAttentionMarkers(projectId, sessionId), + openQuestionMarkers(deps, projectId, sessionId), + ]); + return { + items: [...questions, ...markers] + .sort((left, right) => right.createdAt - left.createdAt) + .map(projectAttentionMarker), + available: true, + }; } catch (error) { log.warn('connector.pending_attention_unavailable', { projectId, diff --git a/packages/operations/src/connector-read-core.ts b/packages/operations/src/connector-read-core.ts index 834759b71c..4c86da4e5a 100644 --- a/packages/operations/src/connector-read-core.ts +++ b/packages/operations/src/connector-read-core.ts @@ -1,4 +1,4 @@ -import { maybeJsonRecord, parsePositiveInt } from '@simple-agent-manager/worker-core'; +import { maybeJsonRecord, parsePositiveInt, preferAttention, readOpenQuestionAttention } from '@simple-agent-manager/worker-core'; import * as schema from '@simple-agent-manager/worker-core/schema'; import { and, desc, eq, sql } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; @@ -54,7 +54,8 @@ export async function projectsList( status: schema.projects.status, role: schema.projectMembers.role, runningWork: sql`(select count(*) from tasks t where t.project_id = ${schema.projects.id} and t.status in ('queued','delegated','in_progress'))`, - needsAttention: sql`(select count(*) from session_summaries ss where ss.project_id = ${schema.projects.id} and ss.created_by_user_id = ${ctx.actor.userId} and ss.attention_json is not null)`, + // Chats waiting on the viewer: an attention marker, or an open question in `asks` (slice G). + needsAttention: sql`(select count(*) from session_summaries ss where ss.project_id = ${schema.projects.id} and ss.created_by_user_id = ${ctx.actor.userId} and (ss.attention_json is not null or exists (select 1 from asks a where a.source_session_id = ss.id and a.project_id = ss.project_id and a.kind = 'question' and a.status = 'open' and (a.expires_at is null or a.expires_at > ${Date.now()}))))`, }) .from(schema.projects) .innerJoin( @@ -134,14 +135,27 @@ export async function chatsList( .limit(limit + 1); const page = rows.slice(0, limit); const last = page[page.length - 1]; - const taskStates = await chatTaskStates(db, page); + const [taskStates, questions] = await Promise.all([ + chatTaskStates(db, page), + // Open questions live in D1 `asks` (inbox slice G); only the chat's creator sees attention. + readOpenQuestionAttention(ctx.env.DATABASE, { + chats: page + .filter((row) => row.createdByUserId === ctx.actor.userId) + .map((row) => ({ projectId: row.projectId, sessionId: row.id })), + assigneeUserId: ctx.actor.userId, + now: Date.now(), + }), + ]); return { chats: page.map(({ attention, ...row }) => ({ ...row, operational: taskStates.get(row.id) ?? null, attention: - row.createdByUserId === ctx.actor.userId && attention - ? (JSON.parse(attention) as unknown) + row.createdByUserId === ctx.actor.userId + ? preferAttention( + attention ? (JSON.parse(attention) as unknown) : null, + questions.get(row.id) + ) : null, link: operationLink(ctx, row.projectId, row.id), })), diff --git a/packages/operations/src/inbox-question-schedule.ts b/packages/operations/src/inbox-question-schedule.ts new file mode 100644 index 0000000000..1f3909326a --- /dev/null +++ b/packages/operations/src/inbox-question-schedule.ts @@ -0,0 +1,67 @@ +/** + * The schedule of an agent question (`request_human_input`): its window, its reminders, the grace + * an undelivered question gets and its hard limit. The rules are the ones the ProjectData marker + * alarm used (`computeHumanInputSchedule`, `advanceAttentionEscalation`, + * `packages/project-data/src/do/attention.ts`); the values are admin settings `inbox.question*`. + */ +import type { InboxLimits } from './inbox-settings'; + +const MINUTE_MS = 60_000; + +type QuestionLimits = Pick< + InboxLimits, + | 'questionTimeoutMinutes' + | 'questionFirstReminderPercent' + | 'questionSecondReminderPercent' + | 'questionUndeliveredGraceMinutes' + | 'questionMaxWaitMinutes' +>; + +/** Reminder points as fractions of the window, ascending, without duplicates or zeros. */ +export function questionReminderFractions(limits: QuestionLimits): number[] { + const fractions = [limits.questionFirstReminderPercent, limits.questionSecondReminderPercent] + .filter((percent) => percent > 0 && percent < 100) + .map((percent) => percent / 100); + return [...new Set(fractions)].sort((left, right) => left - right); +} + +export function questionSchedule( + limits: QuestionLimits, + now: number +): { expiresAt: number; nextEscalationAt: number | null; maxExpiresAt: number } { + const timeout = limits.questionTimeoutMinutes * MINUTE_MS; + const maxWait = Math.max(timeout, limits.questionMaxWaitMinutes * MINUTE_MS); + const first = questionReminderFractions(limits)[0]; + return { + expiresAt: now + timeout, + nextEscalationAt: first === undefined ? null : now + Math.round(timeout * first), + maxExpiresAt: now + maxWait, + }; +} + +/** When the reminder after `escalationCount` is due, or null when none is left. */ +export function nextQuestionReminderAt( + ask: { createdAt: number; expiresAt: number | null; escalationCount: number }, + limits: QuestionLimits +): number | null { + const fraction = questionReminderFractions(limits)[ask.escalationCount + 1]; + if (fraction === undefined) return null; + const window = Math.max(0, (ask.expiresAt ?? ask.createdAt) - ask.createdAt); + return ask.createdAt + Math.round(window * fraction); +} + +/** How far an undelivered question is extended, capped at its hard limit. */ +export function questionUndeliveredExtension( + limits: QuestionLimits, + ask: { createdAt: number; maxExpiresAt: number | null }, + now: number +): { maxExpiresAt: number; extendedExpiry: number } { + const maxExpiresAt = + ask.maxExpiresAt ?? + ask.createdAt + + Math.max(limits.questionTimeoutMinutes, limits.questionMaxWaitMinutes) * MINUTE_MS; + return { + maxExpiresAt, + extendedExpiry: Math.min(maxExpiresAt, now + limits.questionUndeliveredGraceMinutes * MINUTE_MS), + }; +} diff --git a/packages/operations/src/inbox-settings-definition.ts b/packages/operations/src/inbox-settings-definition.ts index 114bfa1b70..f906619c1c 100644 --- a/packages/operations/src/inbox-settings-definition.ts +++ b/packages/operations/src/inbox-settings-definition.ts @@ -56,6 +56,44 @@ export const INBOX_SETTINGS = [ 'Minutes the sweep keeps retrying an agent’s notice that an inbox item was archived or expired.', range: { min: 5, max: 1_440 }, }, + // Questions (`request_human_input`). Defaults are the old HUMAN_INPUT_* Worker defaults + // (`DEFAULT_HUMAN_INPUT_*`, `packages/shared/src/constants/notifications.ts`); the sweep in + // `apps/api/src/services/inbox/sweep.ts` runs this schedule (spec section 7). + { + name: 'inbox.questionTimeoutMinutes', + defaultValue: 120, + description: + 'Minutes an agent question stays open once its notification reached the person. Then it expires and the task stops.', + range: { min: 1, max: 1_440 }, + }, + { + name: 'inbox.questionFirstReminderPercent', + defaultValue: 25, + description: + 'Point in a question’s window, as a percent, where its push notification is sent again. 0 turns this reminder off.', + range: { min: 0, max: 99 }, + }, + { + name: 'inbox.questionSecondReminderPercent', + defaultValue: 75, + description: + 'Point in a question’s window, as a percent, where its push notification is sent a last time. 0 turns this reminder off.', + range: { min: 0, max: 99 }, + }, + { + name: 'inbox.questionUndeliveredGraceMinutes', + defaultValue: 120, + description: + 'Minutes a question is kept open again, and its push resent, when it would expire but no device confirmed its notification.', + range: { min: 1, max: 1_440 }, + }, + { + name: 'inbox.questionMaxWaitMinutes', + defaultValue: 1_440, + description: + 'Most minutes a question may stay open, even when its notification never reached a device. Never shorter than the question window.', + range: { min: 1, max: 4_320 }, + }, { name: 'inbox.sweepBatchSize', defaultValue: 10, diff --git a/packages/operations/src/inbox-write-core.ts b/packages/operations/src/inbox-write-core.ts index 1937bc8adf..7255f3077b 100644 --- a/packages/operations/src/inbox-write-core.ts +++ b/packages/operations/src/inbox-write-core.ts @@ -10,6 +10,7 @@ import { type AcpInteractionBrowserAnswer, ASK_ASSIGNEE_KINDS, ASK_KINDS, + HUMAN_INPUT_CATEGORIES, type InboxActionResponse, type InboxItem, type ParsedInboxRef, @@ -50,6 +51,11 @@ export const CreateAskInputSchema = v.object({ agentProfileId: v.optional(id), groupKey: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(200))), dedupeKey: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(200))), + // Questions (`request_human_input`, slice G): reminders and the expiry outcome. + sourceWorkspaceId: v.optional(id), + category: v.optional(v.picklist(HUMAN_INPUT_CATEGORIES)), + nextEscalationAt: v.optional(v.pipe(v.number(), v.safeInteger())), + maxExpiresAt: v.optional(v.pipe(v.number(), v.safeInteger())), }); export type CreateAskInput = v.InferInput; @@ -114,8 +120,9 @@ export async function createAsk( `INSERT INTO asks (id, project_id, assignee_kind, assignee_user_id, kind, blocking, title, body_md, answer_spec_json, steps_json, links_json, due_hint, due_at, source_session_id, source_task_id, source_message_id, agent_profile_id, group_key, dedupe_key, status, - expires_at, created_at, updated_at) - SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ? + expires_at, source_workspace_id, category, next_escalation_at, max_expires_at, + created_at, updated_at) + SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?, ?, ?, ?, ? WHERE ? IS NULL OR (SELECT COUNT(*) FROM asks WHERE source_session_id = ? AND project_id = ? AND status = 'open') < ? ON CONFLICT (project_id, dedupe_key) WHERE dedupe_key IS NOT NULL DO NOTHING` @@ -141,6 +148,10 @@ export async function createAsk( input.groupKey ?? null, input.dedupeKey ?? null, input.expiresAt ?? null, + input.sourceWorkspaceId ?? null, + input.category ?? null, + input.nextEscalationAt ?? null, + input.maxExpiresAt ?? null, now, now, input.sourceSessionId ?? null, @@ -188,30 +199,38 @@ async function requireActable( return resolved; } -async function loadNoticeRow( - ctx: OperationContext, +export async function loadAskNoticeRow( + ctx: Pick, projectId: string, askId: string ): Promise { const row = await ctx.env.DATABASE.prepare( `SELECT id, project_id, kind, title, status, answer_json, source_session_id, source_task_id, - resolved_by_user_id, assignee_user_id + source_workspace_id, resolved_by_user_id, assignee_user_id, created_at FROM asks WHERE id = ? AND project_id = ?` ) .bind(askId, projectId) - .first>(); - if (!row?.id || !row.project_id || !row.kind || !row.title || !row.status) return null; + .first>(); + const text = (value: unknown) => (typeof value === 'string' && value ? value : null); + const id = text(row?.id); + const rowProjectId = text(row?.project_id); + const kind = text(row?.kind); + const title = text(row?.title); + const status = text(row?.status); + if (!row || !id || !rowProjectId || !kind || !title || !status) return null; return { - id: row.id, - projectId: row.project_id, - kind: row.kind, - title: row.title, - status: row.status, - answerJson: row.answer_json ?? null, - sourceSessionId: row.source_session_id ?? null, - sourceTaskId: row.source_task_id ?? null, - resolvedByUserId: row.resolved_by_user_id ?? null, - assigneeUserId: row.assignee_user_id ?? null, + id, + projectId: rowProjectId, + kind, + title, + status, + answerJson: text(row.answer_json), + sourceSessionId: text(row.source_session_id), + sourceTaskId: text(row.source_task_id), + sourceWorkspaceId: text(row.source_workspace_id), + createdAt: typeof row.created_at === 'number' ? row.created_at : null, + resolvedByUserId: text(row.resolved_by_user_id), + assigneeUserId: text(row.assignee_user_id), }; } @@ -273,6 +292,24 @@ async function answerAsk( ): Promise { // Length was checked against `inbox.answerMaxChars` by `answerInboxItem`. const answer = input.answer?.trim(); + if (item.kind === 'question' && item.sessionId) { + // A question is answered through the one path a chat card, a notification and the Connector + // also use (`answerAttention`, `apps/api/src/routes/chat-attention.ts`), so concurrent answers + // from any of them meet at the same compare-and-set and get the same outcomes. + if (!answer) throw new OperationError('invalid_input', 'answer is required'); + const result = await ctx.ports.chat.answerAttention( + ctx.actor.userId, + item.projectId, + item.sessionId, + askId, + answer + ); + return { + ref: item.ref, + outcome: result.inFlight ? 'in_flight' : 'answered', + agentNotified: !result.inFlight, + }; + } const spec = item.answerSpec; if (spec.type === 'options' && !(answer && (spec.options.includes(answer) || spec.allowText))) throw new OperationError('invalid_input', 'answer must match one of the requested options'); @@ -285,7 +322,7 @@ async function answerAsk( const answerJson = answer ? JSON.stringify({ text: answer }) : null; if (!(await closeAsk(ctx, item.projectId, askId, status, answerJson))) throw new OperationError('conflict', 'This inbox item was already answered or closed'); - const row = await loadNoticeRow(ctx, item.projectId, askId); + const row = await loadAskNoticeRow(ctx, item.projectId, askId); const agentNotified = row ? await notifyClosedAsk(ctx, row, status) : false; return { ref: item.ref, outcome: status, agentNotified }; } @@ -447,7 +484,7 @@ export async function archiveInboxItem( await ctx.ports.inbox.authorizeAnswerWake(item.projectId, item.sessionId, me); if (!(await closeAsk(ctx, item.projectId, ref.id, 'archived', null))) throw new OperationError('conflict', 'This inbox item was already answered or closed'); - const row = await loadNoticeRow(ctx, item.projectId, ref.id); + const row = await loadAskNoticeRow(ctx, item.projectId, ref.id); const agentNotified = row ? await notifyClosedAsk(ctx, row, 'archived') : false; return { ref: item.ref, outcome: 'archived', agentNotified }; } diff --git a/packages/operations/src/index.ts b/packages/operations/src/index.ts index c4c4382c7d..5e75edd5c0 100644 --- a/packages/operations/src/index.ts +++ b/packages/operations/src/index.ts @@ -74,6 +74,13 @@ export { samInboxItemGet, samInboxList, } from './inbox-operations'; +export { + nextQuestionReminderAt, + questionReminderFractions, + questionSchedule, + questionUndeliveredExtension, +} from './inbox-question-schedule'; +export { inboxTitle } from './inbox-rows'; export { defaultInboxLimits, getInboxLimits, type InboxLimits } from './inbox-settings'; export { INBOX_SETTINGS, type InboxSettingName } from './inbox-settings-definition'; export { @@ -82,6 +89,7 @@ export { createAsk, type CreateAskInput, type InboxAnswerInput, + loadAskNoticeRow, notifyClosedAsk, } from './inbox-write-core'; export { getPlatformOperationLimits } from './limits'; diff --git a/packages/operations/src/ports.ts b/packages/operations/src/ports.ts index b85fac43e3..f3f6489131 100644 --- a/packages/operations/src/ports.ts +++ b/packages/operations/src/ports.ts @@ -418,6 +418,10 @@ export interface InboxAskNoticeRow { answerJson: string | null; sourceSessionId: string | null; sourceTaskId: string | null; + /** The asking agent's workspace (questions); the expiry outcome stops its task run. */ + sourceWorkspaceId: string | null; + /** Epoch ms the ask was filed. */ + createdAt: number | null; resolvedByUserId: string | null; assigneeUserId: string | null; } diff --git a/packages/project-data/src/client/project-data.ts b/packages/project-data/src/client/project-data.ts index a67b0f6e92..ec12a7df25 100644 --- a/packages/project-data/src/client/project-data.ts +++ b/packages/project-data/src/client/project-data.ts @@ -3386,39 +3386,32 @@ export async function syncProviderLimitAttention( ); } -export async function createAttentionMarker( +/** A question filed as a D1 `asks` row: answers SAM's check-in, shows live (inbox slice G). */ +export async function recordQuestionAsked( env: Env, projectId: string, - opts: { - sessionId: string; - taskId: string | null; - workspaceId: string | null; - kind: string; - source: string; - sourceNotificationId?: string | null; - notificationUserId?: string | null; - reason?: string | null; - metadata?: string | null; - expiresAt?: number | null; - nextEscalationAt?: number | null; - maxExpiresAt?: number | null; - } -): Promise<{ id: string; createdAt: number; expiresAt: number | null }> { - const stub = await getStub(env, projectId); - return stub.createAttentionMarker(opts); + input: Parameters[0] +): Promise { + return callProjectDataWithRetry( + env, + projectId, + 'recordQuestionAsked', + (stub) => stub.recordQuestionAsked(input), + 'mutation' + ); } -export async function linkAttentionNotification( +/** The task outcome of an expired question held in D1 `asks` (inbox slice G). */ +export async function expireQuestionAsk( env: Env, projectId: string, - markerId: string, - notificationUserId: string, - notificationId: string -): Promise { + input: Parameters[0] +): Promise<{ outcome: 'expired' | 'answered_in_chat' }> { const stub = await getStub(env, projectId); - return stub.linkAttentionNotification(markerId, notificationUserId, notificationId); + return stub.expireQuestionAsk(input); } + export async function prepareAttentionAnswer( env: Env, projectId: string, diff --git a/packages/project-data/src/do/attention-expiry.ts b/packages/project-data/src/do/attention-expiry.ts index 10c78730e3..319669925c 100644 --- a/packages/project-data/src/do/attention-expiry.ts +++ b/packages/project-data/src/do/attention-expiry.ts @@ -317,6 +317,47 @@ async function failExpiredTaskMarker( }); } +/** + * The outcome of an expired agent question held in D1 `asks` (inbox slice G): the same task + * outcome a question marker's expiry has (`failExpiredTaskMarker`). The inbox sweep expires the + * row and calls this through `ProjectData.expireQuestionAsk`. + */ +export async function failExpiredQuestionAsk( + sql: SqlStorage, + env: Env, + question: { + id: string; + sessionId: string; + taskId: string | null; + workspaceId: string | null; + createdAt: number; + }, + failSession: (sessionId: string, errorMessage: string) => Promise, + hooks: AttentionExpiryProcessingHooks +): Promise { + await failExpiredTaskMarker( + sql, + env, + { + id: question.id, + sessionId: question.sessionId, + taskId: question.taskId, + workspaceId: question.workspaceId, + kind: 'needs_input', + source: 'request_human_input', + sourceNotificationId: null, + notificationUserId: null, + createdAt: question.createdAt, + expiresAt: null, + nextEscalationAt: null, + escalationCount: 0, + maxExpiresAt: null, + }, + failSession, + hooks + ); +} + async function cleanupExpiredTaskRun(env: Env, workspaceId: string, taskId: string): Promise { try { await projectDataPorts().tasks.releaseTaskRun(env, taskId); diff --git a/packages/project-data/src/do/attention.ts b/packages/project-data/src/do/attention.ts index 1945659178..c4588a4f1d 100644 --- a/packages/project-data/src/do/attention.ts +++ b/packages/project-data/src/do/attention.ts @@ -8,7 +8,6 @@ import { DEFAULT_HUMAN_INPUT_ESCALATION_FRACTIONS, DEFAULT_HUMAN_INPUT_MAX_WAIT_MS, - DEFAULT_HUMAN_INPUT_TIMEOUT_MS, DEFAULT_HUMAN_INPUT_UNDELIVERED_GRACE_MS, } from '@simple-agent-manager/shared'; import { createModuleLogger } from '@simple-agent-manager/worker-core'; @@ -187,23 +186,6 @@ export function resolveAttentionMarkerById( return count; } -export function linkAttentionNotification( - sql: SqlStorage, - markerId: string, - notificationUserId: string, - notificationId: string -): boolean { - return ( - sql.exec( - `UPDATE session_attention_markers - SET notification_user_id = ?, source_notification_id = ? - WHERE id = ? AND resolved_at IS NULL`, - notificationUserId, - notificationId, - markerId - ).rowsWritten > 0 - ); -} export type PrepareAttentionAnswerResult = | { status: 'ready' } @@ -579,36 +561,6 @@ export function computeAttentionAlarmTime(sql: SqlStorage): number | null { return row.earliest as number; } -/** - * Compute the expiry time for a needs_input marker based on env config. - */ -export function computeHumanInputExpiry(humanInputTimeoutMs: string | undefined): number { - const parsed = Number.parseInt(humanInputTimeoutMs ?? '', 10); - const timeoutMs = Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_HUMAN_INPUT_TIMEOUT_MS; - return Date.now() + timeoutMs; -} - -export function computeHumanInputSchedule( - env: { - HUMAN_INPUT_TIMEOUT_MS?: string; - HUMAN_INPUT_ESCALATION_FRACTIONS?: string; - HUMAN_INPUT_MAX_WAIT_MS?: string; - }, - now: number = Date.now() -): { expiresAt: number; nextEscalationAt: number | null; maxExpiresAt: number } { - const timeout = positiveEnvNumber(env.HUMAN_INPUT_TIMEOUT_MS, DEFAULT_HUMAN_INPUT_TIMEOUT_MS); - const maxWait = Math.max( - timeout, - positiveEnvNumber(env.HUMAN_INPUT_MAX_WAIT_MS, DEFAULT_HUMAN_INPUT_MAX_WAIT_MS) - ); - const firstFraction = - parseHumanInputEscalationFractions(env.HUMAN_INPUT_ESCALATION_FRACTIONS)[0] ?? null; - return { - expiresAt: now + timeout, - nextEscalationAt: firstFraction === null ? null : now + Math.round(timeout * firstFraction), - maxExpiresAt: now + maxWait, - }; -} export function humanInputUndeliveredGraceMs(value?: string): number { return positiveEnvNumber(value, DEFAULT_HUMAN_INPUT_UNDELIVERED_GRACE_MS); diff --git a/packages/project-data/src/do/durability-foundation.ts b/packages/project-data/src/do/durability-foundation.ts index a718487fb0..183c294530 100644 --- a/packages/project-data/src/do/durability-foundation.ts +++ b/packages/project-data/src/do/durability-foundation.ts @@ -33,6 +33,8 @@ export interface DurabilityFoundationHooks { armIdleCleanup(chatSessionId: string): void; /** Release durable messages queued behind the (now ended) turn. */ nudgeDeliveries(chatSessionId: string): number; + /** A person's message answers the chat's open questions in D1 `asks` (`question-asks.ts`). */ + closeQuestionAsks?(sessionId: string, messageId: string): Promise; } export async function acceptPromptDelivery( @@ -59,6 +61,9 @@ export async function finalizeAcceptedPromptDelivery( let alarmError: unknown = null; try { runAcceptedPromptDeliveryHooks(sql, _env, hooks, input, accepted); + if (accepted.transcriptInserted && input.senderType === 'human') { + await hooks.closeQuestionAsks?.(input.targetSessionId, accepted.transcriptMessageId); + } } catch (error) { hookError = error; } finally { @@ -84,6 +89,21 @@ function runAcceptedPromptDeliveryHooks( input: delivery.AcceptPromptDeliveryInput, accepted: delivery.AcceptedPromptDelivery ): void { + // The answer or archive of a question held in D1 `asks` reaches the agent here (`inbox_ask`, + // `apps/api/src/services/inbox/ask-notice.ts`); the chat list clears its question live, as it + // did when a question marker resolved. + const questionAskId = input.sourceKind === 'inbox_ask' ? input.metadata?.questionAskId : null; + if (typeof questionAskId === 'string' && questionAskId) { + hooks.broadcastEvent( + 'attention.resolved', + { + sessionId: input.targetSessionId, + markerId: questionAskId, + reason: typeof input.metadata?.outcome === 'string' ? input.metadata.outcome : null, + }, + input.targetSessionId + ); + } if (accepted.transcriptInserted) { idleCleanup.resetIdleCleanup(sql, env, input.targetSessionId); if (input.senderType === 'human') { diff --git a/packages/project-data/src/do/idea-work.ts b/packages/project-data/src/do/idea-work.ts index 93169fb669..95209981b2 100644 --- a/packages/project-data/src/do/idea-work.ts +++ b/packages/project-data/src/do/idea-work.ts @@ -193,6 +193,45 @@ function applyAssets( } } +/** The chats whose questions an idea shows: the ones strongly linked to it. */ +export function ideaQuestionSessionIds(snapshots: Record): string[] { + return [ + ...new Set( + Object.values(snapshots).flatMap((snapshot) => + snapshot.sessions.filter((session) => session.strong).map((session) => session.sessionId) + ) + ), + ]; +} + +/** + * Add the open questions held in D1 `asks` (inbox slice G) to the snapshots, as question markers + * are: one per strongly linked chat, the newest, newest first. + */ +export function mergeQuestionAsks( + snapshots: Record, + questions: ReadonlyMap +): void { + if (questions.size === 0) return; + for (const snapshot of Object.values(snapshots)) { + for (const session of snapshot.sessions) { + const question = session.strong ? questions.get(session.sessionId) : undefined; + if (!question) continue; + const existing = snapshot.needsInput.find((row) => row.sessionId === session.sessionId); + if (existing && existing.askedAt >= question.createdAt) continue; + snapshot.needsInput = snapshot.needsInput.filter( + (row) => row.sessionId !== session.sessionId + ); + snapshot.needsInput.push({ + sessionId: session.sessionId, + question: question.reason, + askedAt: question.createdAt, + }); + } + snapshot.needsInput.sort((a, b) => b.askedAt - a.askedAt); + } +} + /** * The work linked to each of `ideaIds`, keyed by idea id. Ideas with no linked work get an * entry with empty lists, so a caller never has to distinguish "absent" from "nothing yet". diff --git a/packages/project-data/src/do/index.ts b/packages/project-data/src/do/index.ts index dac8c17e90..cf9b8d92e7 100644 --- a/packages/project-data/src/do/index.ts +++ b/packages/project-data/src/do/index.ts @@ -26,6 +26,7 @@ import { import { createModuleLogger, serializeError } from '@simple-agent-manager/worker-core'; import { expectJsonRecord } from '@simple-agent-manager/worker-core'; import { normalizeSearchQuery } from '@simple-agent-manager/worker-core'; +import { preferAttention, readOpenQuestionAttention } from '@simple-agent-manager/worker-core'; import { DurableObject } from 'cloudflare:workers'; import { measureArchiveSql } from '../archive/sql-metrics'; @@ -112,6 +113,7 @@ import { type ProviderLimitAttentionResult, syncProviderLimitAttention, } from './provider-limit-attention'; +import * as questionAsks from './question-asks'; import * as reconciliation from './reconciliation'; import { parseCountCnt, parseMaxLatest, parseMetaValue } from './row-schemas'; import { instrumentRowUsage, RowUsage } from './row-usage'; @@ -998,9 +1000,40 @@ export class ProjectData extends DurableObject { }, nudgeDeliveries: (chatSessionId) => promptDelivery.nudgePromptDeliveriesForTarget(this.sql, chatSessionId), + closeQuestionAsks: (sessionId, messageId) => this.closeQuestionAsks(sessionId, messageId), }; } + /** A person's chat message answers the chat's open questions in D1 `asks` (inbox slice G). */ + private closeQuestionAsks(sessionId: string, messageId: string | null): Promise { + return questionAsks.closeQuestionAsksForHumanMessage( + this.env, + { projectId: this.getProjectId(), sessionId, messageId }, + (type, payload, targetSessionId) => this.broadcastEvent(type, payload, targetSessionId) + ); + } + + /** The chats' open questions from D1 `asks`, merged into their attention (inbox slice G). */ + private async withQuestionAttention( + sessions: Record[] + ): Promise[]> { + const projectId = this.getProjectId(); + const sessionIds = sessions + .map((session) => session.id) + .filter((id): id is string => typeof id === 'string'); + if (!projectId || sessionIds.length === 0) return sessions; + const questions = await readOpenQuestionAttention(this.env.DATABASE, { + projectId, + sessionIds, + now: Date.now(), + }); + if (questions.size === 0) return sessions; + return sessions.map((session) => { + const question = typeof session.id === 'string' ? questions.get(session.id) : undefined; + return question ? { ...session, attention: preferAttention(session.attention, question) } : session; + }); + } + /** * Fan-out for a reconciled terminal activity transition. Every consumer of * "is this session mid-prompt" is served from this one place so a future @@ -1025,6 +1058,7 @@ export class ProjectData extends DurableObject { recalculateAlarm: () => this.recalculateAlarm(), scheduleSummarySync: () => this.scheduleSummarySync(), broadcastEvent: (type, payload, sessionId) => this.broadcastEvent(type, payload, sessionId), + closeQuestionAsks: (sessionId, messageId) => this.closeQuestionAsks(sessionId, messageId), }; } @@ -1070,20 +1104,26 @@ export class ProjectData extends DurableObject { taskId, createdByUserId ); + const sessions = await this.withQuestionAttention(result.sessions); return { - sessions: result.sessions.map((s) => this.addBaseDomain(s)), + sessions: sessions.map((s) => this.addBaseDomain(s)), total: result.total, hasMore: result.hasMore, }; } async getSessionsByTaskIds(taskIds: string[]): Promise>> { - return sessionReads.getSessionsByTaskIds(this.sql, taskIds).map((s) => this.addBaseDomain(s)); + const sessions = await this.withQuestionAttention( + sessionReads.getSessionsByTaskIds(this.sql, taskIds) + ); + return sessions.map((s) => this.addBaseDomain(s)); } async getSession(sessionId: string): Promise | null> { const result = sessionReads.getSession(this.sql, sessionId); - return result ? this.addBaseDomain(result) : null; + if (!result) return null; + const [session] = await this.withQuestionAttention([result]); + return this.addBaseDomain(session ?? result); } async getMessages( @@ -2609,8 +2649,21 @@ export class ProjectData extends DurableObject { } /** Batched: the work linked to many ideas at once, for the Ideas list. */ - getIdeaWorkSnapshots(ideaIds: string[], caps: ideaWork.IdeaWorkLinkCaps) { - return ideaWork.getIdeaWorkSnapshots(this.sql, ideaIds, caps); + async getIdeaWorkSnapshots(ideaIds: string[], caps: ideaWork.IdeaWorkLinkCaps) { + const snapshots = ideaWork.getIdeaWorkSnapshots(this.sql, ideaIds, caps); + const projectId = this.getProjectId(); + const sessionIds = ideaWork.ideaQuestionSessionIds(snapshots); + if (projectId && sessionIds.length > 0) { + ideaWork.mergeQuestionAsks( + snapshots, + await readOpenQuestionAttention(this.env.DATABASE, { + projectId, + sessionIds, + now: Date.now(), + }) + ); + } + return snapshots; } async cacheCommands( @@ -2770,19 +2823,94 @@ export class ProjectData extends DurableObject { }); } - async createAttentionMarker( - opts: attention.CreateAttentionMarkerOpts - ): Promise<{ id: string; createdAt: number; expiresAt: number | null }> { - if (opts.kind === 'needs_input' && opts.source === 'request_human_input') { - attention.resolveAttentionMarkersByKind( + /** + * An agent asked a question that is now a D1 `asks` row (inbox slice G): it answers SAM's open + * check-in, as a question marker did, and the chat list shows it live. Nothing is stored here. + */ + async recordQuestionAsked(input: { + sessionId: string; + askId: string; + createdAt: number; + expiresAt: number | null; + reason: string | null; + options: string[]; + }): Promise { + const resolved = attention.resolveAttentionMarkersByKind( + this.sql, + input.sessionId, + 'reconciliation_checkin', + null, + 'agent', + 'human_input_requested' + ); + if (resolved > 0) { + await this.recalculateAlarm(); + this.scheduleSummarySync(); + } + this.broadcastEvent( + 'attention.created', + { + sessionId: input.sessionId, + markerId: input.askId, + kind: 'needs_input', + createdAt: input.createdAt, + expiresAt: input.expiresAt, + reason: input.reason, + options: input.options, + }, + input.sessionId + ); + } + + /** + * The outcome of an expired question held in D1 `asks` (the inbox sweep expired the row): the + * same task outcome a question marker's expiry has. A chat message from the person after the + * question answered it, so then the task is left alone. + */ + async expireQuestionAsk(input: { + askId: string; + sessionId: string; + taskId: string | null; + workspaceId: string | null; + createdAt: number; + }): Promise<{ outcome: 'expired' | 'answered_in_chat' }> { + const answeredInChat = questionAsks.humanMessageSince( + this.sql, + input.sessionId, + input.createdAt + ); + if (!answeredInChat) { + await attentionExpiry.failExpiredQuestionAsk( this.sql, - opts.sessionId, - 'reconciliation_checkin', - null, - 'agent', - 'human_input_requested' + this.env, + { + id: input.askId, + sessionId: input.sessionId, + taskId: input.taskId, + workspaceId: input.workspaceId, + createdAt: input.createdAt, + }, + async (sessionId, errorMessage) => { + await this.failSession(sessionId, errorMessage); + }, + { projectId: this.getProjectId(), scheduleSummarySync: () => this.scheduleSummarySync() } ); } + this.broadcastEvent( + 'attention.resolved', + { + sessionId: input.sessionId, + markerId: input.askId, + reason: answeredInChat ? 'human_message' : 'expired', + }, + input.sessionId + ); + return { outcome: answeredInChat ? 'answered_in_chat' : 'expired' }; + } + + async createAttentionMarker( + opts: attention.CreateAttentionMarkerOpts + ): Promise<{ id: string; createdAt: number; expiresAt: number | null }> { const result = attention.createAttentionMarker(this.sql, opts); await this.recalculateAlarm(); // The D1 session index (Connector inbox, chat list badges) copies the attention summary; a @@ -2804,18 +2932,6 @@ export class ProjectData extends DurableObject { return result; } - linkAttentionNotification( - markerId: string, - notificationUserId: string, - notificationId: string - ): boolean { - return attention.linkAttentionNotification( - this.sql, - markerId, - notificationUserId, - notificationId - ); - } prepareAttentionAnswer(sessionId: string, markerId: string, answer: string) { return attention.prepareAttentionAnswer(this.sql, sessionId, markerId, answer); diff --git a/packages/project-data/src/do/message-persistence.ts b/packages/project-data/src/do/message-persistence.ts index b216843983..6ec301f107 100644 --- a/packages/project-data/src/do/message-persistence.ts +++ b/packages/project-data/src/do/message-persistence.ts @@ -29,6 +29,11 @@ export type MessagePersistenceHooks = { recalculateAlarm: () => Promise; scheduleSummarySync: () => void; broadcastEvent: (type: string, payload: Record, sessionId?: string) => void; + /** + * A person's chat message answers the chat's open questions in D1 `asks` (inbox slice G), as it + * resolves its attention markers. Never throws (`question-asks.ts`). + */ + closeQuestionAsks?: (sessionId: string, messageId: string) => Promise; }; export type MessageBatchPersistenceResult = { @@ -224,6 +229,7 @@ async function resolveAttentionForRoles( 'human_message' ); reason = 'human_message'; + await hooks.closeQuestionAsks?.(sessionId, firstUserMsg.id); } else if (firstAssistantMsg) { resolved = attention.resolveAttentionMarkersByKind( sql, diff --git a/packages/project-data/src/do/question-asks.ts b/packages/project-data/src/do/question-asks.ts new file mode 100644 index 0000000000..e6a3844ec3 --- /dev/null +++ b/packages/project-data/src/do/question-asks.ts @@ -0,0 +1,87 @@ +/** + * ProjectData's side of agent questions held in D1 `asks` (inbox slice G, idea + * 01M7G03ZCQ6TM6CMEYDRKQ8ST9). The ask is one D1 row; this object keeps no copy of it. It does + * what a question marker used to do inside the object: + * - a person's chat message answers the chat's open questions, as it resolved every marker + * (`message-persistence.ts:resolveAttentionForRoles`, `durability-foundation.ts`); + * - the live `attention.*` socket events the chat list follows. + */ +import { createModuleLogger, serializeError } from '@simple-agent-manager/worker-core'; + +import type { Env } from './types'; + +const log = createModuleLogger('project_data.question_asks'); + +type Broadcast = (type: string, payload: Record, sessionId?: string) => void; + +/** + * Close the chat's open questions because the person wrote to the agent in the chat. The message + * itself reached the agent, so no notice is queued (`notified_at` is set). Bound to the project + * and the chat (rule 11). A failure is logged, never thrown: the message is already persisted, + * and the question still expires on its schedule, where `ProjectData.expireQuestionAsk` sees + * the message and does not stop the task. + */ +export async function closeQuestionAsksForHumanMessage( + env: Env, + input: { projectId: string | null; sessionId: string; messageId: string | null }, + broadcast: Broadcast +): Promise { + if (!input.projectId) return 0; + const now = Date.now(); + try { + const result = await env.DATABASE.prepare( + `UPDATE asks + SET status = 'answered', answer_json = ?, resolved_at = ?, updated_at = ?, notified_at = ? + WHERE project_id = ? AND source_session_id = ? AND kind = 'question' AND status = 'open' + RETURNING id` + ) + .bind( + JSON.stringify({ via: 'chat_message', messageId: input.messageId }), + now, + now, + now, + input.projectId, + input.sessionId + ) + .all<{ id: string }>(); + const ids = (result.results ?? []).map((row) => row.id).filter(Boolean); + for (const askId of ids) { + broadcast( + 'attention.resolved', + { sessionId: input.sessionId, markerId: askId, reason: 'human_message' }, + input.sessionId + ); + } + if (ids.length > 0) { + log.info('question_asks.answered_by_chat_message', { + projectId: input.projectId, + sessionId: input.sessionId, + count: ids.length, + }); + } + return ids.length; + } catch (error) { + log.error('question_asks.chat_message_close_failed', { + projectId: input.projectId, + sessionId: input.sessionId, + ...serializeError(error), + }); + return 0; + } +} + +/** Whether the person wrote in the chat after the question was asked (expiry backstop). */ +export function humanMessageSince(sql: SqlStorage, sessionId: string, since: number): boolean { + return ( + sql + .exec( + `SELECT 1 FROM chat_messages + WHERE session_id = ? AND role = 'user' AND created_at > ? + AND (origin IS NULL OR origin != 'system') + LIMIT 1`, + sessionId, + since + ) + .toArray().length > 0 + ); +} diff --git a/packages/project-data/src/do/reconciliation-candidates.ts b/packages/project-data/src/do/reconciliation-candidates.ts index 16bf797115..8307b42113 100644 --- a/packages/project-data/src/do/reconciliation-candidates.ts +++ b/packages/project-data/src/do/reconciliation-candidates.ts @@ -154,11 +154,20 @@ async function resolveCandidateProjectId( taskId: string, sql: SqlStorage ): Promise { + const now = Date.now(); + // An open question in D1 `asks` (inbox slice G) holds the check-in off, as an open question + // marker does in the local candidate query: the agent is waiting on a person, not stalled. const taskRow = await env.DATABASE.prepare( - `SELECT task_mode, status, project_id, workspace_id, chat_session_id, admission_state + `SELECT task_mode, status, project_id, workspace_id, chat_session_id, admission_state, + EXISTS ( + SELECT 1 FROM asks a + WHERE a.project_id = tasks.project_id AND a.source_session_id = ? + AND a.kind = 'question' AND a.status = 'open' + AND (a.expires_at IS NULL OR a.expires_at > ?) + ) AS open_question FROM tasks WHERE id = ? LIMIT 1` ) - .bind(taskId) + .bind(sessionId, now, taskId) .first<{ task_mode: string | null; admission_state?: string | null; @@ -166,6 +175,7 @@ async function resolveCandidateProjectId( project_id: string | null; workspace_id: string | null; chat_session_id: string | null; + open_question?: number | null; }>(); if (!taskRow) { recordReconciliationCandidateInconclusive(sql, env, { @@ -207,6 +217,12 @@ async function resolveCandidateProjectId( }); return null; } + if (taskRow.open_question) { + // Looked at again one lease later; answering or expiring the question ends the hold, and + // the deferral spends no probe attempt. + deferReconciliationCandidateUntil(sql, sessionId, now + reconciliationCandidateLeaseMs(env)); + return null; + } return taskRow.project_id; } diff --git a/packages/project-data/src/do/types.ts b/packages/project-data/src/do/types.ts index 1283e6da7c..fbd56cac16 100644 --- a/packages/project-data/src/do/types.ts +++ b/packages/project-data/src/do/types.ts @@ -302,7 +302,6 @@ export interface ProjectDataEnv { MAILBOX_DELIVERY_POLL_INTERVAL_MS?: string; MAILBOX_MAX_MESSAGES_PER_PROJECT?: string; POLICY_MAX_PER_PROJECT?: string; - HUMAN_INPUT_TIMEOUT_MS?: string; HUMAN_INPUT_ESCALATION_FRACTIONS?: string; HUMAN_INPUT_UNDELIVERED_GRACE_MS?: string; HUMAN_INPUT_MAX_WAIT_MS?: string; diff --git a/packages/project-data/src/index.ts b/packages/project-data/src/index.ts index d1f9bd5540..35eb906d46 100644 --- a/packages/project-data/src/index.ts +++ b/packages/project-data/src/index.ts @@ -53,7 +53,6 @@ export { } from './do/agent-wake-policy'; export { ATTENTION_ARCHIVE_CLAIM, - computeHumanInputSchedule, parseAttentionOptions, } from './do/attention'; export { CommentNotFoundError } from './do/comment-contracts'; diff --git a/packages/shared/src/constants/index.ts b/packages/shared/src/constants/index.ts index 6624170e06..b960553a45 100644 --- a/packages/shared/src/constants/index.ts +++ b/packages/shared/src/constants/index.ts @@ -669,7 +669,6 @@ export { DEFAULT_COMMENT_NOTIFICATION_WINDOW_MS, DEFAULT_HUMAN_INPUT_ESCALATION_FRACTIONS, DEFAULT_HUMAN_INPUT_MAX_WAIT_MS, - DEFAULT_HUMAN_INPUT_TIMEOUT_MS, DEFAULT_HUMAN_INPUT_UNDELIVERED_GRACE_MS, DEFAULT_MAX_NOTIFICATIONS_PER_USER, DEFAULT_NOTIFICATION_AUTO_DELETE_AGE_MS, diff --git a/packages/shared/src/constants/notifications.ts b/packages/shared/src/constants/notifications.ts index dcead20459..49daf7d069 100644 --- a/packages/shared/src/constants/notifications.ts +++ b/packages/shared/src/constants/notifications.ts @@ -88,9 +88,6 @@ export const MAX_WEB_PUSH_ENDPOINT_LENGTH = 2_048; /** Maximum accepted encoded browser subscription key length. */ export const MAX_WEB_PUSH_SUBSCRIPTION_KEY_LENGTH = 256; -/** Initial human-input response window. Default: 2 hours. */ -export const DEFAULT_HUMAN_INPUT_TIMEOUT_MS = 2 * 60 * 60 * 1000; - /** Fractions of the initial response window at which push is re-notified. */ export const DEFAULT_HUMAN_INPUT_ESCALATION_FRACTIONS = '0.25,0.75'; diff --git a/packages/worker-core/src/index.ts b/packages/worker-core/src/index.ts index de918c5d2d..11e96eb166 100644 --- a/packages/worker-core/src/index.ts +++ b/packages/worker-core/src/index.ts @@ -42,6 +42,17 @@ export { type LogLevel, serializeError, } from './logger'; +export { + DEFAULT_OPEN_QUESTION_READ_LIMIT, + hasOpenQuestionAsk, + type OpenQuestionQuery, + preferAttention, + QUESTION_ASK_SOURCE, + questionAttentionFromRow, + type QuestionAttentionSummary, + questionOptions, + readOpenQuestionAttention, +} from './question-asks'; export { parsePositiveInt, requireRouteParam } from './route-helpers'; export { mapRows, parseRow, parseRowOrNull } from './row-parsing'; export { diff --git a/packages/worker-core/src/question-asks.ts b/packages/worker-core/src/question-asks.ts new file mode 100644 index 0000000000..3c1df4f286 --- /dev/null +++ b/packages/worker-core/src/question-asks.ts @@ -0,0 +1,211 @@ +/** + * Open questions held in D1 `asks` (inbox slice G, idea 01M7G03ZCQ6TM6CMEYDRKQ8ST9). + * + * A question an agent asks with `request_human_input` is one `asks` row (kind `question`). The + * readers that used to find it as a ProjectData attention marker (the chat list, a chat's + * attention, the ProjectData session reads, the stalled-task guard) read it here, in the shape + * the marker summary had (`getAttentionSummary`, `packages/project-data/src/do/attention.ts`), so + * their consumers see no difference. One home for the record; this module only reads it. + */ +import { createModuleLogger } from './logger'; + +const log = createModuleLogger('question_asks'); + +/** The `source` a question ask reports in an attention summary, as its marker did. */ +export const QUESTION_ASK_SOURCE = 'request_human_input'; + +/** The attention summary shape (`getAttentionSummary`), for an open question ask. */ +export interface QuestionAttentionSummary { + markerId: string; + kind: 'needs_input'; + source: typeof QUESTION_ASK_SOURCE; + createdAt: number; + expiresAt: number | null; + reason: string | null; + options: string[]; + category: string | null; + interactionId: null; + interactionKind: null; +} + +export interface OpenQuestionQuery { + /** One project; or `chats` across projects. */ + projectId?: string; + /** Only these chats; omit for every chat of the project. */ + sessionIds?: readonly string[]; + /** Chats of several projects, each bound to its own project (cross-project lists). */ + chats?: ReadonlyArray<{ projectId: string; sessionId: string }>; + /** Only questions addressed to this person (the chat's creator). */ + assigneeUserId?: string | null; + now: number; + /** Rows read at most; open questions are bounded by expiry and the per-chat cap. */ + limit?: number; +} + +/** Open questions live at most a day and a chat holds at most `inbox.openItemsPerChat`. */ +export const DEFAULT_OPEN_QUESTION_READ_LIMIT = 500; + +/** The options of a question's answer spec (`{type:'options', options}`), or none. */ +export function questionOptions(answerSpecJson: unknown): string[] { + if (typeof answerSpecJson !== 'string' || !answerSpecJson) return []; + try { + const spec = JSON.parse(answerSpecJson) as unknown; + if (!spec || typeof spec !== 'object') return []; + const record = spec as Record; + if (record.type !== 'options' || !Array.isArray(record.options)) return []; + return record.options.filter((option): option is string => typeof option === 'string'); + } catch { + return []; + } +} + +function text(value: unknown): string | null { + return typeof value === 'string' && value ? value : null; +} + +function int(value: unknown): number | null { + return typeof value === 'number' && Number.isSafeInteger(value) ? value : null; +} + +/** One `asks` row as an attention summary, or null when it cannot be read (rule 50). */ +export function questionAttentionFromRow(row: Record): { + sessionId: string; + summary: QuestionAttentionSummary; +} | null { + const id = text(row.id); + const sessionId = text(row.source_session_id); + const createdAt = int(row.created_at); + if (!id || !sessionId || createdAt === null) return null; + return { + sessionId, + summary: { + markerId: id, + kind: 'needs_input', + source: QUESTION_ASK_SOURCE, + createdAt, + expiresAt: int(row.expires_at), + reason: text(row.body_md) ?? text(row.title), + options: questionOptions(row.answer_spec_json), + category: text(row.category), + interactionId: null, + interactionKind: null, + }, + }; +} + +/** + * The newest open question per chat, as attention summaries. Bound to the project in the + * predicate (rule 11). Never throws: a failed read returns an empty map and logs, because every + * caller is enriching a read that is still worth serving without the question badge. + */ +export async function readOpenQuestionAttention( + db: D1Database, + query: OpenQuestionQuery +): Promise> { + const bySession = new Map(); + if (query.sessionIds && query.sessionIds.length === 0) return bySession; + if (query.chats && query.chats.length === 0) return bySession; + // Every read is bound to a project (rule 11): one, or each chat's own. + if (!query.projectId && !query.chats) return bySession; + const limit = query.limit ?? DEFAULT_OPEN_QUESTION_READ_LIMIT; + const conditions = [ + "kind = 'question'", + "status = 'open'", + 'source_session_id IS NOT NULL', + '(expires_at IS NULL OR expires_at > ?)', + ]; + const params: unknown[] = [query.now]; + if (query.projectId) { + conditions.push('project_id = ?'); + params.push(query.projectId); + } + if (query.chats) { + conditions.push(`EXISTS (SELECT 1 FROM json_each(?) chat + WHERE json_extract(chat.value, '$[0]') = asks.project_id + AND json_extract(chat.value, '$[1]') = asks.source_session_id)`); + params.push(JSON.stringify(query.chats.map((chat) => [chat.projectId, chat.sessionId]))); + } + if (query.sessionIds) { + // json_each keeps any number of chats inside the bound-parameter ceiling (rule 69). + conditions.push('source_session_id IN (SELECT value FROM json_each(?))'); + params.push(JSON.stringify(query.sessionIds)); + } + if (query.assigneeUserId) { + conditions.push('assignee_user_id = ?'); + params.push(query.assigneeUserId); + } + let rows: Record[]; + try { + const result = await db + .prepare( + `SELECT id, source_session_id, title, body_md, answer_spec_json, category, created_at, + expires_at + FROM asks WHERE ${conditions.join(' AND ')} + ORDER BY created_at DESC, id DESC + LIMIT ?` + ) + .bind(...params, limit) + .all>(); + rows = result.results ?? []; + } catch (error) { + log.warn('question_asks.read_failed', { + projectId: query.projectId ?? null, + error: error instanceof Error ? error.message : String(error), + }); + return bySession; + } + if (rows.length >= limit) { + log.warn('question_asks.read_limit_reached', { projectId: query.projectId ?? null, limit }); + } + for (const row of rows) { + const parsed = questionAttentionFromRow(row); + if (!parsed) { + log.warn('question_asks.row_skipped', { + projectId: query.projectId ?? null, + askId: text(row.id), + }); + continue; + } + // Newest first, so the first row of a chat is the one it shows. + if (!bySession.has(parsed.sessionId)) bySession.set(parsed.sessionId, parsed.summary); + } + return bySession; +} + +/** + * The attention a chat shows when it holds both a ProjectData marker summary and an open question + * ask: the newest question for a person, then any other marker. This is `getAttentionSummary`'s + * rule with both stores taken together (a later `wake_failed` must not hide a question). + */ +export function preferAttention(marker: unknown, question: QuestionAttentionSummary | undefined) { + if (!question) return marker ?? null; + if (marker && typeof marker === 'object') { + const record = marker as Record; + if ( + record.kind === 'needs_input' && + typeof record.createdAt === 'number' && + record.createdAt > question.createdAt + ) { + return marker; + } + } + return question; +} + +/** Whether the chat has an open, unexpired question from this task (the stalled-task guard). */ +export async function hasOpenQuestionAsk( + db: D1Database, + input: { projectId: string; sessionId: string; taskId: string; now: number } +): Promise { + const row = await db + .prepare( + `SELECT 1 AS open FROM asks + WHERE project_id = ? AND source_session_id = ? AND kind = 'question' AND status = 'open' + AND (source_task_id IS NULL OR source_task_id = ?) + AND (expires_at IS NULL OR expires_at > ?) + LIMIT 1` + ) + .bind(input.projectId, input.sessionId, input.taskId, input.now) + .first<{ open: number }>(); + return Boolean(row); +} diff --git a/packages/worker-core/src/schema.ts b/packages/worker-core/src/schema.ts index 3fbe1cff72..7dc8d6c7e8 100644 --- a/packages/worker-core/src/schema.ts +++ b/packages/worker-core/src/schema.ts @@ -816,8 +816,23 @@ export const asks = sqliteTable( notifiedAt: integer('notified_at'), createdAt: integer('created_at').notNull(), updatedAt: integer('updated_at').notNull(), + // Questions (`request_human_input`, slice G; migration 0247). + /** The workspace the asking agent ran in, for the expiry outcome (task and runtime). */ + sourceWorkspaceId: text('source_workspace_id'), + /** The `request_human_input` category (`HUMAN_INPUT_CATEGORIES`), when given. */ + category: text('category'), + /** The notification sent for the ask; reminders resend its push, expiry checks its receipt. */ + notificationId: text('notification_id'), + /** Next reminder (push resend); NULL when none is left. */ + nextEscalationAt: integer('next_escalation_at'), + escalationCount: integer('escalation_count').notNull().default(0), + /** Hard limit on how long an undelivered ask may be extended. */ + maxExpiresAt: integer('max_expires_at'), }, (table) => ({ + openEscalationIdx: index('idx_asks_open_escalation') + .on(table.nextEscalationAt) + .where(sql`status = 'open' AND next_escalation_at IS NOT NULL`), assigneeStatusIdx: index('idx_asks_assignee_status').on( table.assigneeUserId, table.status, diff --git a/scripts/deploy/installer-engine-ci-env.json b/scripts/deploy/installer-engine-ci-env.json index 40ac71acaf..ee0c4130f9 100644 --- a/scripts/deploy/installer-engine-ci-env.json +++ b/scripts/deploy/installer-engine-ci-env.json @@ -523,7 +523,6 @@ "CLOUD_INIT_CERT_REQUEST_TIMEOUT_SECONDS": "${{ vars.CLOUD_INIT_CERT_REQUEST_TIMEOUT_SECONDS }}", "TASK_RUNNER_FIRST_HEARTBEAT_TIMEOUT_MS": "${{ vars.TASK_RUNNER_FIRST_HEARTBEAT_TIMEOUT_MS }}", "TASK_RUNNER_BOOT_MAX_REPLACEMENTS": "${{ vars.TASK_RUNNER_BOOT_MAX_REPLACEMENTS }}", - "HUMAN_INPUT_TIMEOUT_MS": "${{ vars.HUMAN_INPUT_TIMEOUT_MS }}", "HUMAN_INPUT_ESCALATION_FRACTIONS": "${{ vars.HUMAN_INPUT_ESCALATION_FRACTIONS }}", "HUMAN_INPUT_UNDELIVERED_GRACE_MS": "${{ vars.HUMAN_INPUT_UNDELIVERED_GRACE_MS }}", "HUMAN_INPUT_MAX_WAIT_MS": "${{ vars.HUMAN_INPUT_MAX_WAIT_MS }}", diff --git a/scripts/deploy/sync-wrangler-config.ts b/scripts/deploy/sync-wrangler-config.ts index c3c3afce89..43d567f48f 100644 --- a/scripts/deploy/sync-wrangler-config.ts +++ b/scripts/deploy/sync-wrangler-config.ts @@ -726,7 +726,6 @@ export function getApiWorkerVars( 'WEB_PUSH_MAX_SUBSCRIPTIONS_PER_USER', 'WEB_PUSH_USER_AGENT_MAX_LENGTH', 'RATE_LIMIT_PUSH_SUBSCRIPTION', - 'HUMAN_INPUT_TIMEOUT_MS', 'HUMAN_INPUT_ESCALATION_FRACTIONS', 'HUMAN_INPUT_UNDELIVERED_GRACE_MS', 'HUMAN_INPUT_MAX_WAIT_MS', diff --git a/scripts/deploy/worker-var-defaults.ts b/scripts/deploy/worker-var-defaults.ts index f68678cf40..8d0f0ce571 100644 --- a/scripts/deploy/worker-var-defaults.ts +++ b/scripts/deploy/worker-var-defaults.ts @@ -54,7 +54,6 @@ export const OMITTED_WORKER_VAR_DEFAULTS: Readonly> = { RATE_LIMIT_PUSH_SUBSCRIPTION: '30', // Human input - HUMAN_INPUT_TIMEOUT_MS: '7200000', HUMAN_INPUT_ESCALATION_FRACTIONS: '0.25,0.75', HUMAN_INPUT_UNDELIVERED_GRACE_MS: '7200000', HUMAN_INPUT_MAX_WAIT_MS: '86400000', diff --git a/scripts/quality/runtime-tunables-baseline.json b/scripts/quality/runtime-tunables-baseline.json index 49ee48a84f..192d0d6513 100644 --- a/scripts/quality/runtime-tunables-baseline.json +++ b/scripts/quality/runtime-tunables-baseline.json @@ -445,7 +445,6 @@ "HETZNER_MAX_LIST_PAGES", "HUMAN_INPUT_ESCALATION_FRACTIONS", "HUMAN_INPUT_MAX_WAIT_MS", - "HUMAN_INPUT_TIMEOUT_MS", "HUMAN_INPUT_UNDELIVERED_GRACE_MS", "IDENTITY_TOKEN_CACHE_BUFFER_SECONDS", "IDENTITY_TOKEN_CACHE_MIN_TTL_SECONDS", From 0d5ca670095e9ea88fc954761392cb7067a9e86b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 05:15:42 +0000 Subject: [PATCH 03/13] test+docs(inbox): slice G questions on real SQL, workers capability, overlay and hold tests - question-asks.test.ts: filing, answer outcomes, concurrent answers, tenancy attack/owner pairs, typed-message close, sweep reminders/grace/expiry - workers: request_human_input -> asks row -> inbox archive/answer of a sleeping chat queues one wake-capable delivery; marker-era overlap case - chat list index overlay + live ranking, stall guard, check-in hold, Connector projection; marker-era route tests keep the overlap path - createAsk split into inbox-ask-create-core.ts (file size rule) - docs: admin settings inbox.question*, API reference, notifications/config Co-Authored-By: Claude Opus 5.5 --- apps/api/src/services/inbox/question-asks.ts | 56 +- .../tests/unit/chat-attention-reader.test.ts | 35 +- .../api/tests/unit/connector/protocol.test.ts | 1 + .../durable-objects/reconciliation.test.ts | 35 ++ .../unit/operations/inbox-operations.test.ts | 4 + .../operations/operational-operations.test.ts | 38 ++ .../unit/routes/chat-prompt-cancel.test.ts | 6 + apps/api/tests/unit/routes/mcp.test.ts | 62 +- .../unit/services/inbox/question-asks.test.ts | 560 ++++++++++++++++++ .../services/session-summary-index.test.ts | 112 +++- .../unit/stuck-task-live-runtime.test.ts | 39 ++ .../tests/workers/inbox-capability.test.ts | 146 ++++- .../workers/notification-push-do.test.ts | 52 +- .../docs/docs/guides/admin-settings.md | 14 + .../content/docs/docs/guides/notifications.md | 14 +- .../src/content/docs/docs/reference/api.md | 21 +- .../docs/docs/reference/configuration.md | 7 +- .../operations/src/inbox-ask-create-core.ts | 166 ++++++ packages/operations/src/inbox-operations.ts | 3 +- packages/operations/src/inbox-write-core.ts | 156 +---- packages/operations/src/index.ts | 3 +- .../src/do/reconciliation-candidates.ts | 8 +- .../project-data/tests/unit/attention.test.ts | 31 - ...11-16-inbox-slice-g-questions-into-asks.md | 67 ++- 24 files changed, 1342 insertions(+), 294 deletions(-) create mode 100644 apps/api/tests/unit/services/inbox/question-asks.test.ts create mode 100644 packages/operations/src/inbox-ask-create-core.ts diff --git a/apps/api/src/services/inbox/question-asks.ts b/apps/api/src/services/inbox/question-asks.ts index 6043838f06..511c6c805a 100644 --- a/apps/api/src/services/inbox/question-asks.ts +++ b/apps/api/src/services/inbox/question-asks.ts @@ -173,13 +173,23 @@ export async function answerQuestionAsk( WHERE id = ? AND project_id = ? AND source_session_id = ? AND kind = 'question' AND status = 'open' AND (expires_at IS NULL OR expires_at > ?)` ) - .bind(JSON.stringify({ text: answer }), userId, now, now, ask.id, ask.projectId, ask.sessionId, now) + .bind( + JSON.stringify({ text: answer }), + userId, + now, + now, + ask.id, + ask.projectId, + ask.sessionId, + now + ) .run(); if ((claimed.meta?.changes ?? 0) !== 1) { // Someone else settled it first: report what they did. const current = await loadQuestionAsk(env, ask.projectId, ask.sessionId, ask.id); if (!current) throw markRejectedBeforeEffects(errors.notFound('Attention request')); - if (current.status === 'open') throw markRejectedBeforeEffects(errors.conflict('This question expired')); + if (current.status === 'open') + throw markRejectedBeforeEffects(errors.conflict('This question expired')); return settledOutcome(current, answer); } @@ -247,25 +257,29 @@ export async function fileQuestionAsk( const limits = await getInboxLimits(ctx); const now = Date.now(); const schedule = questionSchedule(limits, now); - const created = await createAsk(ctx, { - projectId: input.projectId, - assigneeKind: 'user', - assigneeUserId: input.userId, - kind: 'question', - blocking: true, - title: inboxTitle(input.context, limits.titleMaxChars), - body: input.context, - answerSpec: input.options?.length - ? { type: 'options', options: input.options, allowText: false } - : { type: 'text' }, - sourceSessionId: input.sessionId, - sourceTaskId: input.taskId, - sourceWorkspaceId: input.workspaceId ?? undefined, - category: input.category ?? undefined, - expiresAt: schedule.expiresAt, - nextEscalationAt: schedule.nextEscalationAt ?? undefined, - maxExpiresAt: schedule.maxExpiresAt, - }); + const created = await createAsk( + ctx, + { + projectId: input.projectId, + assigneeKind: 'user', + assigneeUserId: input.userId, + kind: 'question', + blocking: true, + title: inboxTitle(input.context, limits.titleMaxChars), + body: input.context, + answerSpec: input.options?.length + ? { type: 'options', options: input.options, allowText: false } + : { type: 'text' }, + sourceSessionId: input.sessionId, + sourceTaskId: input.taskId, + sourceWorkspaceId: input.workspaceId ?? undefined, + category: input.category ?? undefined, + expiresAt: schedule.expiresAt, + nextEscalationAt: schedule.nextEscalationAt ?? undefined, + maxExpiresAt: schedule.maxExpiresAt, + }, + now + ); try { await projectDataService.recordQuestionAsked(env, input.projectId, { sessionId: input.sessionId, diff --git a/apps/api/tests/unit/chat-attention-reader.test.ts b/apps/api/tests/unit/chat-attention-reader.test.ts index ff8837defc..17eb817911 100644 --- a/apps/api/tests/unit/chat-attention-reader.test.ts +++ b/apps/api/tests/unit/chat-attention-reader.test.ts @@ -49,6 +49,13 @@ function app() { return app; } const path = '/api/projects/p-1/sessions/s-1/attention/a-1'; +/** + * A D1 with no `asks` row for the id, so the route reads the question as a marker: the + * marker-era path questions asked before inbox slice G keep until they resolve. + */ +const MARKER_ERA_ENV = { + DATABASE: { prepare: () => ({ bind: () => ({ first: async () => null }) }) }, +}; const fullReason = 'A complete, very old question. '.repeat(100); describe('notification question reader route', () => { beforeEach(() => { @@ -86,7 +93,7 @@ describe('notification question reader route', () => { }); }); it('returns full canonical text and options without reading transcript until requested', async () => { - const response = await app().request(path, {}, { DATABASE: {} }); + const response = await app().request(path, {}, MARKER_ERA_ENV); expect(response.status).toBe(200); const result = await response.json(); expect(result.request).toMatchObject({ @@ -102,7 +109,7 @@ describe('notification question reader route', () => { const base = await mocks.marker(); const read = async (metadata: string | null) => { mocks.marker.mockResolvedValue({ ...base, metadata }); - return (await (await app().request(path, {}, { DATABASE: {} })).json()).request.category; + return (await (await app().request(path, {}, MARKER_ERA_ENV)).json()).request.category; }; expect(await read(JSON.stringify({ category: 'approval', options: ['Go'] }))).toBe('approval'); expect(await read(JSON.stringify({ options: ['Go'] }))).toBeNull(); @@ -111,7 +118,7 @@ describe('notification question reader route', () => { expect(await read(null)).toBeNull(); }); it('reads a small window before the request, not the latest conversation page', async () => { - const response = await app().request(path + '?context=true', {}, { DATABASE: {} }); + const response = await app().request(path + '?context=true', {}, MARKER_ERA_ENV); expect((await response.json()).messages[0].content).toBe('Previous context'); expect(mocks.messages).toHaveBeenCalledWith( expect.anything(), @@ -134,7 +141,7 @@ describe('notification question reader route', () => { 'makes settled, expired, in-flight and unsupported requests read-only: %j', async (override) => { mocks.marker.mockResolvedValue({ ...(await mocks.marker()), ...override }); - const response = await app().request(path, {}, { DATABASE: {} }); + const response = await app().request(path, {}, MARKER_ERA_ENV); expect((await response.json()).request.canAnswer).toBe(false); } ); @@ -143,12 +150,12 @@ describe('notification question reader route', () => { session: { topic: null }, access: { found: true, role: 'reader' }, }); - const response = await app().request(path, {}, { DATABASE: {} }); + const response = await app().request(path, {}, MARKER_ERA_ENV); expect((await response.json()).request.canAnswer).toBe(false); }); it('keeps downgraded project members and grantees without an active owner read-only', async () => { mocks.capability.mockResolvedValue({ membership: { role: 'viewer' } }); - expect((await (await app().request(path, {}, { DATABASE: {} })).json()).request.canAnswer).toBe( + expect((await (await app().request(path, {}, MARKER_ERA_ENV)).json()).request.canAnswer).toBe( false ); mocks.capability.mockResolvedValue({ membership: { role: 'maintainer' } }); @@ -157,11 +164,11 @@ describe('notification question reader route', () => { access: { found: true, role: 'grantee', ownerUserId: 'owner-1', grant: { id: 'grant-1' } }, }); mocks.ownerCapability.mockResolvedValue(false); - expect((await (await app().request(path, {}, { DATABASE: {} })).json()).request.canAnswer).toBe( + expect((await (await app().request(path, {}, MARKER_ERA_ENV)).json()).request.canAnswer).toBe( false ); mocks.ownerCapability.mockResolvedValue(true); - expect((await (await app().request(path, {}, { DATABASE: {} })).json()).request.canAnswer).toBe( + expect((await (await app().request(path, {}, MARKER_ERA_ENV)).json()).request.canAnswer).toBe( true ); }); @@ -169,7 +176,7 @@ describe('notification question reader route', () => { await app().request( path + '?context=true&limit=7', {}, - { DATABASE: {}, CHAT_SESSION_MESSAGE_MAX: '5', CHAT_SESSION_MESSAGE_LIMIT: '3' } + { ...MARKER_ERA_ENV, CHAT_SESSION_MESSAGE_MAX: '5', CHAT_SESSION_MESSAGE_LIMIT: '3' } ); expect(mocks.messages).toHaveBeenCalledWith( expect.anything(), @@ -181,7 +188,7 @@ describe('notification question reader route', () => { it.each(['', 'bad', '0', '-1'])( 'uses the context default for invalid limit %j', async (limit) => { - await app().request(path + '?context=true&limit=' + limit, {}, { DATABASE: {} }); + await app().request(path + '?context=true&limit=' + limit, {}, MARKER_ERA_ENV); expect(mocks.messages).toHaveBeenCalledWith( expect.anything(), 'p-1', @@ -216,7 +223,7 @@ describe('notification question reader route', () => { }, ], }); - const result = await (await app().request(path + '?context=true', {}, { DATABASE: {} })).json(); + const result = await (await app().request(path + '?context=true', {}, MARKER_ERA_ENV)).json(); expect(result.messages.map((m: { id: string }) => m.id)).toEqual(['m-older', 'm-newer']); expect(result.messages[1].content).toBe('First streamed chunk. Second streamed chunk.'); expect(result.messages[0].truncated).toBe(true); @@ -224,16 +231,16 @@ describe('notification question reader route', () => { it('rejects missing and cross-session markers', async () => { for (const marker of [null, { sessionId: 'other', kind: 'needs_input' }]) { mocks.marker.mockResolvedValue(marker); - expect((await app().request(path, {}, { DATABASE: {} })).status).toBe(404); + expect((await app().request(path, {}, MARKER_ERA_ENV)).status).toBe(404); } }); it('checks project and session access before reading a question', async () => { mocks.capability.mockRejectedValue(Object.assign(new Error('Forbidden'), { statusCode: 403 })); - expect((await app().request(path, {}, { DATABASE: {} })).status).toBe(403); + expect((await app().request(path, {}, MARKER_ERA_ENV)).status).toBe(403); expect(mocks.marker).not.toHaveBeenCalled(); mocks.capability.mockResolvedValue({ membership: { role: 'owner' } }); mocks.access.mockResolvedValue({ session: null, access: { found: false } }); - expect((await app().request(path, {}, { DATABASE: {} })).status).toBe(404); + expect((await app().request(path, {}, MARKER_ERA_ENV)).status).toBe(404); expect(mocks.marker).not.toHaveBeenCalled(); }); }); diff --git a/apps/api/tests/unit/connector/protocol.test.ts b/apps/api/tests/unit/connector/protocol.test.ts index 3c5022bce5..6cca319f09 100644 --- a/apps/api/tests/unit/connector/protocol.test.ts +++ b/apps/api/tests/unit/connector/protocol.test.ts @@ -62,6 +62,7 @@ beforeEach(async () => { sqlite = new Database(':memory:'); createSchemaTables(sqlite, [ schema.users, + schema.asks, schema.projects, schema.projectMembers, schema.tasks, diff --git a/apps/api/tests/unit/durable-objects/reconciliation.test.ts b/apps/api/tests/unit/durable-objects/reconciliation.test.ts index aaf6d3d3c6..3a48690396 100644 --- a/apps/api/tests/unit/durable-objects/reconciliation.test.ts +++ b/apps/api/tests/unit/durable-objects/reconciliation.test.ts @@ -69,6 +69,8 @@ interface MockTaskRow { completed_at?: string | null; execution_step?: string | null; terminal_transition_id?: string | null; + /** The candidate query's open-question probe over D1 `asks` (inbox slice G). */ + open_question?: number; } interface MockWorkspaceRow { @@ -625,6 +627,39 @@ describe('Task Reconciliation Module', () => { expect(candidates).toHaveLength(0); }); + it('holds the check-in one lease while the chat has an open question in D1 asks', async () => { + setupTaskSession(); + const env = envWithRows({ + 'task-1': { task_mode: 'task', status: 'in_progress', open_question: 1 }, + }); + await expect(getReconciliationCandidates(sql, env)).resolves.toEqual([]); + const gate = JSON.parse( + String( + db + .prepare(`SELECT value FROM do_meta WHERE key = 'taskReconciliationGate:session-1'`) + .get()?.value + ) + ) as { attempts: number; nextAttemptAt: number }; + // Deferred, without spending a probe attempt. + expect(gate.attempts).toBe(0); + expect(gate.nextAttemptAt).toBeGreaterThan(Date.now()); + // The query that decided it carries the session and the time. + const query = vi + .mocked(env.DATABASE.prepare) + .mock.calls.find(([sql]) => String(sql).includes('open_question')); + expect(String(query?.[0])).toContain("a.kind = 'question' AND a.status = 'open'"); + }); + + it('control: without an open question the same session is a candidate', async () => { + setupTaskSession(); + await expect( + getReconciliationCandidates( + sql, + envWithRows({ 'task-1': { task_mode: 'task', status: 'in_progress', open_question: 0 } }) + ) + ).resolves.toEqual([expect.objectContaining({ sessionId: 'session-1' })]); + }); + it('excludes sessions with active needs_input marker', async () => { setupTaskSession(); createAttentionMarker(sql, { diff --git a/apps/api/tests/unit/operations/inbox-operations.test.ts b/apps/api/tests/unit/operations/inbox-operations.test.ts index c1e2672225..cda04a696f 100644 --- a/apps/api/tests/unit/operations/inbox-operations.test.ts +++ b/apps/api/tests/unit/operations/inbox-operations.test.ts @@ -152,6 +152,10 @@ beforeEach(() => { sqlite, new URL('../../../src/db/migrations/0245_asks.sql', import.meta.url) ); + applySqliteMigration( + sqlite, + new URL('../../../src/db/migrations/0247_asks_questions.sql', import.meta.url) + ); for (const [id, role] of [ ['owner', 'user'], ['colleague', 'user'], diff --git a/apps/api/tests/unit/operations/operational-operations.test.ts b/apps/api/tests/unit/operations/operational-operations.test.ts index 8aac467d78..8d7c44b374 100644 --- a/apps/api/tests/unit/operations/operational-operations.test.ts +++ b/apps/api/tests/unit/operations/operational-operations.test.ts @@ -85,6 +85,7 @@ describe('operational MCP evidence with real SQLite authorization and persistenc sqlite = new Database(':memory:'); createSchemaTables(sqlite, [ schema.users, + schema.asks, schema.projects, schema.projectMembers, schema.tasks, @@ -387,6 +388,43 @@ describe('operational MCP evidence with real SQLite authorization and persistenc }); }); + it('shows a question held in D1 asks (slice G) beside markers, bound to its project and chat', async () => { + const insertAsk = (id: string, projectId: string, sessionId: string, createdAt: number) => + sqlite + .prepare( + `INSERT INTO asks (id, project_id, assignee_kind, assignee_user_id, kind, blocking, title, + body_md, answer_spec_json, category, source_session_id, source_task_id, status, + expires_at, max_expires_at, escalation_count, next_escalation_at, notification_id, + created_at, updated_at) + VALUES (?, ?, 'user', 'owner', 'question', 1, 'Pick a region', 'Pick a region for the deploy.', + '{"type":"options","options":["eu","us"],"allowText":false}', 'decision', ?, 'task', + 'open', 9000, 20000, 1, 6000, 'n-ask', ?, ?)` + ) + .run(id, projectId, sessionId, createdAt, createdAt); + insertAsk('ask-1', 'p', 'chat', 3_000); + // Attack fixtures: same chat id under another project, and another chat of this project. + insertAsk('ask-foreign', 'foreign', 'chat', 4_000); + insertAsk('ask-other-chat', 'p', 'other-chat', 4_000); + mocks.attention.mockResolvedValue([question()]); + const read = await samChatRead.run(ctx('grantee'), session); + expect(read.pendingAttention?.map((item) => item.markerId)).toEqual(['ask-1', 'marker-1']); + expect(read.pendingAttention?.[0]).toMatchObject({ + markerId: 'ask-1', + kind: 'needs_input', + source: 'request_human_input', + answerable: true, + category: 'decision', + options: ['eu', 'us'], + reminders: 1, + notification: { notificationId: 'n-ask', deviceDelivery: 'not_recorded' }, + }); + expect(read.pendingAttention?.[0]?.question.text).toContain('Pick a region for the deploy.'); + // An answered question is not pending. + sqlite.prepare("UPDATE asks SET status = 'answered' WHERE id = 'ask-1'").run(); + const after = await samChatRead.run(ctx('grantee'), session); + expect(after.pendingAttention?.map((item) => item.markerId)).toEqual(['marker-1']); + }); + it('reports a new question as a change and says when questions could not be read', async () => { const initial = await samWorkChanges.run(ctx(), session); mocks.attention.mockResolvedValue([question()]); diff --git a/apps/api/tests/unit/routes/chat-prompt-cancel.test.ts b/apps/api/tests/unit/routes/chat-prompt-cancel.test.ts index c66c214f71..1857d6b77d 100644 --- a/apps/api/tests/unit/routes/chat-prompt-cancel.test.ts +++ b/apps/api/tests/unit/routes/chat-prompt-cancel.test.ts @@ -27,6 +27,12 @@ const mocks = vi.hoisted(() => ({ snapshotInteractions: vi.fn(), })); +// These answer routes test questions still held as attention markers (asked before inbox slice G); +// an asks-era question is covered on SQLite in `tests/unit/services/inbox/question-asks.test.ts`. +vi.mock('../../../src/services/inbox/question-asks', async (original) => ({ + ...(await original()), + loadQuestionAsk: vi.fn(async () => null), +})); vi.mock('drizzle-orm/d1', () => ({ drizzle: mocks.drizzle, })); diff --git a/apps/api/tests/unit/routes/mcp.test.ts b/apps/api/tests/unit/routes/mcp.test.ts index 2c0d9cc75a..28da5c1b24 100644 --- a/apps/api/tests/unit/routes/mcp.test.ts +++ b/apps/api/tests/unit/routes/mcp.test.ts @@ -47,6 +47,13 @@ const instantSessionMocks = vi.hoisted(() => ({ launchInstantSession: vi.fn(), })); +// request_human_input files its question as a D1 `asks` row (inbox slice G); the real create +// path is covered on SQLite in `tests/unit/services/inbox/question-asks.test.ts`. +const questionAskMocks = vi.hoisted(() => ({ + fileQuestionAsk: vi.fn(), + linkQuestionNotification: vi.fn(), +})); +vi.mock('../../../src/services/inbox/question-asks', () => questionAskMocks); const agentActivityMocks = vi.hoisted(() => ({ listAgentActivityTasks: vi.fn(), })); @@ -4667,6 +4674,12 @@ describe('MCP Routes', () => { beforeEach(() => { vi.clearAllMocks(); mockKV.get.mockResolvedValue({ ...validTokenData, chatSessionId: 'session-1' }); + questionAskMocks.fileQuestionAsk.mockResolvedValue({ + id: 'ask-1', + createdAt: 1, + expiresAt: 2, + }); + questionAskMocks.linkQuestionNotification.mockResolvedValue(undefined); }); it('should send notification and return success', async () => { @@ -4691,19 +4704,36 @@ describe('MCP Routes', () => { const body = await res.json(); const payload = JSON.parse(body.result.content[0].text); expect(payload.message).toContain('Human input request recorded'); - // The chat card reads the question from this marker; it must point at the stored one. - expect(payload.humanInputRequest).toEqual({ id: 'marker-1', sessionId: 'session-1' }); + // The chat card reads the question by this id; it must be the stored ask's. + expect(payload.humanInputRequest).toEqual({ id: 'ask-1', sessionId: 'session-1' }); expect(payload.notificationScheduled).toBe(true); + expect(questionAskMocks.fileQuestionAsk).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + sessionId: 'session-1', + userId: 'user-789', + context: 'Should I use approach A or B for the database migration?', + category: 'decision', + options: ['Approach A', 'Approach B'], + }) + ); + expect(mockDoStub.createAttentionMarker).not.toHaveBeenCalled(); expect(mockNotificationStub.createNotification).toHaveBeenCalledWith( 'user-789', expect.objectContaining({ type: 'needs_input', metadata: expect.objectContaining({ - attentionMarkerId: 'marker-1', + attentionMarkerId: 'ask-1', options: ['Approach A', 'Approach B'], }), }) ); + expect(questionAskMocks.linkQuestionNotification).toHaveBeenCalledWith( + expect.anything(), + expect.any(String), + 'ask-1', + expect.any(String) + ); }); it('should reject empty context', async () => { @@ -4826,8 +4856,9 @@ describe('MCP Routes', () => { expect(payload.message).toContain('notification delivery was not scheduled'); expect(payload.notificationScheduled).toBe(false); // The question is still recorded, so the chat card can still be answered. - expect(payload.humanInputRequest).toEqual({ id: 'marker-1', sessionId: 'session-1' }); - expect(mockDoStub.createAttentionMarker).toHaveBeenCalledOnce(); + expect(payload.humanInputRequest).toEqual({ id: 'ask-1', sessionId: 'session-1' }); + expect(questionAskMocks.fileQuestionAsk).toHaveBeenCalledOnce(); + expect(questionAskMocks.linkQuestionNotification).not.toHaveBeenCalled(); }); it('returns an error instead of claiming safety when no chat session exists', async () => { @@ -4851,7 +4882,26 @@ describe('MCP Routes', () => { const body = await res.json(); expect(body.error.message).toContain('chat session is missing'); expect(mockNotificationStub.createNotification).not.toHaveBeenCalled(); - expect(mockDoStub.createAttentionMarker).not.toHaveBeenCalled(); + expect(questionAskMocks.fileQuestionAsk).not.toHaveBeenCalled(); + }); + + it('tells the agent which inbox limit it hit (per-chat cap) instead of an internal error', async () => { + mockD1._stmt.first.mockResolvedValueOnce({ user_id: 'user-789', title: 'Fix the bug' }); + const { OperationError } = await import('@simple-agent-manager/operations'); + questionAskMocks.fileQuestionAsk.mockRejectedValueOnce( + new OperationError('rate_limited', 'This chat already has 20 open inbox items') + ); + const res = await mcpRequest( + app, + jsonRpcRequest('tools/call', { + name: 'request_human_input', + arguments: { context: 'One more question?' }, + }) + ); + const body = await res.json(); + expect(body.error.code).toBe(-32602); + expect(body.error.message).toBe('This chat already has 20 open inbox items'); + expect(mockNotificationStub.createNotification).not.toHaveBeenCalled(); }); it('should reject context that is only whitespace', async () => { diff --git a/apps/api/tests/unit/services/inbox/question-asks.test.ts b/apps/api/tests/unit/services/inbox/question-asks.test.ts new file mode 100644 index 0000000000..c5a0c57960 --- /dev/null +++ b/apps/api/tests/unit/services/inbox/question-asks.test.ts @@ -0,0 +1,560 @@ +/** + * Agent questions held in D1 `asks` (inbox slice G), on a real SQL engine (`.claude/rules/28`, + * `.claude/rules/11`): filing through `request_human_input`'s create path, the answer + * compare-and-set and its caller outcomes, concurrent answers, tenancy (attack cases paired with + * owner controls), the typed-chat-message close, and the sweep's reminders, undelivered grace and + * expiry. Replaced edges only: ProjectData RPCs (prompt delivery, live events, expiry outcome), + * the agent-wake policy, the shared-answer audit and push receipts. + */ +import { answerInboxItem, archiveInboxItem } from '@simple-agent-manager/operations'; +import Database from 'better-sqlite3'; +import { Hono } from 'hono'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const edges = vi.hoisted(() => ({ + acceptPromptDelivery: vi.fn(), + recordQuestionAsked: vi.fn(), + expireQuestionAsk: vi.fn(), + getSessionAccess: vi.fn(), + prepareAttentionAnswer: vi.fn(), + authorizeAgentWake: vi.fn(), + recordSharedSessionAnswer: vi.fn(), + hasConfirmedPushDelivery: vi.fn(), + resendPush: vi.fn(), +})); +vi.mock('../../../../src/services/project-data', async () => ({ + ...(await vi.importActual( + '../../../../src/services/project-data' + )), + acceptPromptDelivery: edges.acceptPromptDelivery, + recordQuestionAsked: edges.recordQuestionAsked, + expireQuestionAsk: edges.expireQuestionAsk, + getSessionAccess: edges.getSessionAccess, + prepareAttentionAnswer: edges.prepareAttentionAnswer, +})); +vi.mock('../../../../src/services/agent-wake-authorization', () => ({ + authorizeAgentWake: edges.authorizeAgentWake, +})); +vi.mock('../../../../src/services/session-access', async () => ({ + ...(await vi.importActual( + '../../../../src/services/session-access' + )), + recordSharedSessionAnswer: edges.recordSharedSessionAnswer, +})); +vi.mock('../../../../src/project-data-ports/notifications', () => ({ + notificationsPort: { + hasConfirmedPushDelivery: edges.hasConfirmedPushDelivery, + resendPush: edges.resendPush, + }, +})); +vi.mock('../../../../src/middleware/auth', () => ({ getUserId: () => 'owner' })); + +import { closeQuestionAsksForHumanMessage } from '@simple-agent-manager/project-data/internal/do/question-asks'; + +import * as schema from '../../../../src/db/schema'; +import type { Env } from '../../../../src/env'; +import { createOperationPorts } from '../../../../src/operation-ports'; +import { answerAttention, registerChatAttentionRoute } from '../../../../src/routes/chat-attention'; +import { + fileQuestionAsk, + linkQuestionNotification, +} from '../../../../src/services/inbox/question-asks'; +import { runInboxAskSweep } from '../../../../src/services/inbox/sweep'; +import { + applySqliteMigration, + createAllSchemaTables, + createSqliteD1, +} from '../../../helpers/sqlite-d1'; + +const P1 = 'proj-1'; +const P2 = 'proj-2'; +const MINUTE = 60_000; +let sqlite: Database.Database; +let env: Env; + +function insert(table: string, row: Record) { + const keys = Object.keys(row); + sqlite + .prepare(`INSERT INTO ${table} (${keys.join(',')}) VALUES (${keys.map(() => '?').join(',')})`) + .run(...Object.values(row)); +} + +function askRow(id: string) { + return sqlite.prepare('SELECT * FROM asks WHERE id = ?').get(id) as Record; +} + +function setting(key: string, value: string) { + insert('platform_settings', { key, value, updated_at: '2026-11-16T00:00:00Z' }); +} + +const question = (overrides: Partial[1]> = {}) => + fileQuestionAsk(env, { + projectId: P1, + sessionId: 'chat-1', + taskId: 'task-1', + workspaceId: 'ws-1', + userId: 'owner', + context: 'Which region should the deploy use? EU keeps latency low for our users.', + category: 'decision', + options: ['eu', 'us'], + ...overrides, + }); + +beforeEach(() => { + vi.useRealTimers(); + for (const edge of Object.values(edges)) edge.mockReset(); + edges.acceptPromptDelivery.mockResolvedValue({ message: { id: 'd' } }); + edges.recordQuestionAsked.mockResolvedValue(undefined); + edges.expireQuestionAsk.mockResolvedValue({ outcome: 'expired' }); + edges.getSessionAccess.mockResolvedValue({ + session: { topic: 'Deploy chat' }, + access: { found: true, role: 'owner', ownerUserId: 'owner' }, + }); + edges.prepareAttentionAnswer.mockResolvedValue({ status: 'not_found' }); + edges.authorizeAgentWake.mockResolvedValue({ + writer: { ownerUserId: 'owner', role: 'owner' }, + wake: { allowed: true }, + }); + edges.recordSharedSessionAnswer.mockResolvedValue(undefined); + edges.hasConfirmedPushDelivery.mockResolvedValue(false); + edges.resendPush.mockResolvedValue(undefined); + sqlite = new Database(':memory:'); + createAllSchemaTables(sqlite, schema); + sqlite.exec('DROP TABLE asks'); + applySqliteMigration( + sqlite, + new URL('../../../../src/db/migrations/0245_asks.sql', import.meta.url) + ); + applySqliteMigration( + sqlite, + new URL('../../../../src/db/migrations/0247_asks_questions.sql', import.meta.url) + ); + env = { DATABASE: createSqliteD1(sqlite) } as unknown as Env; + for (const id of ['owner', 'outsider']) + insert('users', { id, email: `${id}@x.test`, name: id, role: 'user', status: 'active' }); + insert('projects', { id: P1, user_id: 'owner', name: 'One', repository: 'o/one' }); + insert('projects', { id: P2, user_id: 'outsider', name: 'Two', repository: 'o/two' }); + insert('project_members', { project_id: P1, user_id: 'owner', role: 'owner', status: 'active' }); + insert('project_members', { + project_id: P2, + user_id: 'outsider', + role: 'owner', + status: 'active', + }); + insert('tasks', { + id: 'task-1', + project_id: P1, + user_id: 'owner', + title: 'Deploy', + status: 'in_progress', + chat_session_id: 'chat-1', + }); + insert('tasks', { + id: 'task-2', + project_id: P2, + user_id: 'outsider', + title: 'Other', + status: 'in_progress', + chat_session_id: 'chat-2', + }); +}); + +describe('filing a question (request_human_input)', () => { + it('writes one asks row with the question, its options and today’s schedule, and shows it live', async () => { + const before = Date.now(); + const filed = await question(); + const row = askRow(filed.id); + expect(row).toMatchObject({ + project_id: P1, + kind: 'question', + blocking: 1, + assignee_kind: 'user', + assignee_user_id: 'owner', + status: 'open', + title: 'Which region should the deploy use?', + body_md: 'Which region should the deploy use? EU keeps latency low for our users.', + category: 'decision', + source_session_id: 'chat-1', + source_task_id: 'task-1', + source_workspace_id: 'ws-1', + escalation_count: 0, + notified_at: null, + }); + expect(JSON.parse(String(row.answer_spec_json))).toEqual({ + type: 'options', + options: ['eu', 'us'], + allowText: false, + }); + // Defaults: a 2 h window, reminders at 25 % and 75 %, a 24 h hard limit. + const created = Number(row.created_at); + expect(created).toBeGreaterThanOrEqual(before); + expect(Number(row.expires_at) - created).toBeCloseTo(120 * MINUTE, -3); + expect(Number(row.next_escalation_at) - created).toBeCloseTo(30 * MINUTE, -3); + expect(Number(row.max_expires_at) - created).toBeCloseTo(1_440 * MINUTE, -3); + expect(edges.recordQuestionAsked).toHaveBeenCalledWith(env, P1, { + sessionId: 'chat-1', + askId: filed.id, + createdAt: filed.createdAt, + expiresAt: filed.expiresAt, + reason: 'Which region should the deploy use? EU keeps latency low for our users.', + options: ['eu', 'us'], + }); + }); + + it('reads the schedule from the admin settings', async () => { + setting('inbox.questionTimeoutMinutes', '10'); + setting('inbox.questionFirstReminderPercent', '50'); + setting('inbox.questionMaxWaitMinutes', '20'); + const filed = await question({ options: null }); + const row = askRow(filed.id); + const created = Number(row.created_at); + expect(Number(row.expires_at) - created).toBe(10 * MINUTE); + expect(Number(row.next_escalation_at) - created).toBe(5 * MINUTE); + expect(Number(row.max_expires_at) - created).toBe(20 * MINUTE); + expect(JSON.parse(String(row.answer_spec_json))).toEqual({ type: 'text' }); + }); + + it('applies the per-chat cap from the admin setting', async () => { + setting('inbox.openItemsPerChat', '1'); + await question(); + await expect(question()).rejects.toMatchObject({ code: 'rate_limited' }); + }); + + it('refuses a task of another project (the source task must belong to the project)', async () => { + await expect(question({ taskId: 'task-2' })).rejects.toMatchObject({ code: 'invalid_input' }); + expect(sqlite.prepare('SELECT COUNT(*) AS n FROM asks').get()).toEqual({ n: 0 }); + }); + + it('a live-update failure does not lose the filed question', async () => { + edges.recordQuestionAsked.mockRejectedValue(new Error('DO down')); + const filed = await question(); + expect(askRow(filed.id).status).toBe('open'); + }); +}); + +describe('answering a question', () => { + const answer = (askId: string, text: string, projectId = P1, sessionId = 'chat-1') => + answerAttention(env, 'owner', projectId, sessionId, askId, text); + + it('accepts an answer: one compare-and-set, the answer delivered as a durable prompt, notified_at recorded', async () => { + const { id } = await question(); + await expect(answer(id, 'eu')).resolves.toEqual({ + resolved: true, + alreadyResolved: false, + answer: 'eu', + }); + const row = askRow(id); + expect(row).toMatchObject({ status: 'answered', resolved_by_user_id: 'owner' }); + expect(JSON.parse(String(row.answer_json))).toEqual({ text: 'eu' }); + expect(row.notified_at).not.toBeNull(); + expect(edges.acceptPromptDelivery).toHaveBeenCalledOnce(); + const [, projectId, delivery] = edges.acceptPromptDelivery.mock.calls[0]!; + expect(projectId).toBe(P1); + expect(delivery).toMatchObject({ + deliveryId: `inbox-ask:${id}`, + targetSessionId: 'chat-1', + sourceTaskId: 'task-1', + sourceKind: 'inbox_ask', + metadata: expect.objectContaining({ questionAskId: id, outcome: 'answered' }), + }); + expect(delivery.deliveryContent).toContain('eu'); + expect(delivery.deliveryContent).toContain('Which region should the deploy use?'); + // A marker-era lookup is never reached for an asks-era question. + expect(edges.prepareAttentionAnswer).not.toHaveBeenCalled(); + }); + + it('keeps today’s outcomes: already answered, conflicting answer, invalid option', async () => { + const { id } = await question(); + await expect(answer(id, 'mars')).rejects.toMatchObject({ statusCode: 400 }); + expect(askRow(id).status).toBe('open'); + await answer(id, 'eu'); + await expect(answer(id, 'eu')).resolves.toEqual({ + resolved: true, + alreadyResolved: true, + answer: 'eu', + }); + await expect(answer(id, 'us')).rejects.toMatchObject({ + statusCode: 409, + message: 'Attention request is already resolved', + }); + expect(edges.acceptPromptDelivery).toHaveBeenCalledOnce(); + }); + + it('reports an answer whose delivery was not queued as still being delivered; the sweep delivers it', async () => { + const { id } = await question(); + edges.acceptPromptDelivery.mockRejectedValueOnce(new Error('DO unavailable')); + await expect(answer(id, 'eu')).resolves.toEqual({ + resolved: false, + alreadyResolved: false, + inFlight: true, + answer: 'eu', + }); + expect(askRow(id)).toMatchObject({ status: 'answered', notified_at: null }); + // The same answer again is still in flight; a different one conflicts with it. + await expect(answer(id, 'eu')).resolves.toMatchObject({ inFlight: true }); + await expect(answer(id, 'us')).rejects.toMatchObject({ + statusCode: 409, + message: 'A different answer is already being delivered', + }); + // The sweep retries the notice once it is past the inline grace. + await runInboxAskSweep(env, Number(askRow(id).resolved_at) + 2 * MINUTE); + expect(askRow(id).notified_at).not.toBeNull(); + expect(edges.acceptPromptDelivery).toHaveBeenCalledTimes(2); + }); + + it('two people answering at once: exactly one wins, the other gets the conflict', async () => { + const { id } = await question(); + const results = await Promise.allSettled([answer(id, 'eu'), answer(id, 'us')]); + const won = results.filter((result) => result.status === 'fulfilled'); + const lost = results.filter((result) => result.status === 'rejected'); + expect(won).toHaveLength(1); + expect(lost).toHaveLength(1); + expect((lost[0] as PromiseRejectedResult).reason).toMatchObject({ statusCode: 409 }); + const winner = (won[0] as PromiseFulfilledResult<{ answer: string }>).value.answer; + expect(JSON.parse(String(askRow(id).answer_json))).toEqual({ text: winner }); + expect(edges.acceptPromptDelivery).toHaveBeenCalledOnce(); + }); + + it('refuses an expired question', async () => { + const { id } = await question(); + sqlite.prepare('UPDATE asks SET expires_at = ? WHERE id = ?').run(Date.now() - 1, id); + await expect(answer(id, 'eu')).rejects.toMatchObject({ statusCode: 409 }); + expect(askRow(id).status).toBe('open'); + }); + + it('attack: an ask id addressed through another project or chat is not answered; owner control answers it', async () => { + const { id } = await question(); + // Foreign project (the caller is a member there) and another chat of the same project. + insert('project_members', { + project_id: P2, + user_id: 'owner', + role: 'owner', + status: 'active', + }); + await expect(answer(id, 'eu', P2, 'chat-2')).rejects.toMatchObject({ statusCode: 404 }); + await expect(answer(id, 'eu', P1, 'chat-other')).rejects.toMatchObject({ statusCode: 404 }); + expect(askRow(id).status).toBe('open'); + expect(edges.acceptPromptDelivery).not.toHaveBeenCalled(); + // Owner control. + await expect(answer(id, 'eu')).resolves.toMatchObject({ resolved: true }); + }); + + it('the inbox answer route goes through the same path and outcomes', async () => { + const { id } = await question(); + const ctx = { + env, + ports: createOperationPorts(env), + actor: { + userId: 'owner', + via: 'web' as const, + scopes: new Set(['sam.read', 'sam.write'] as const), + }, + requestId: 't', + }; + await expect( + answerInboxItem(ctx, { projectId: P1, ref: `ask:${id}`, answer: 'us' }) + ).resolves.toEqual({ ref: `ask:${id}`, outcome: 'answered', agentNotified: true }); + expect(JSON.parse(String(askRow(id).answer_json))).toEqual({ text: 'us' }); + // A second inbox answer meets the closed row. + await expect( + answerInboxItem(ctx, { projectId: P1, ref: `ask:${id}`, answer: 'eu' }) + ).rejects.toMatchObject({ code: 'conflict' }); + }); + + it('archiving from the inbox closes it and tells the agent in question words', async () => { + const { id } = await question(); + const ctx = { + env, + ports: createOperationPorts(env), + actor: { + userId: 'owner', + via: 'web' as const, + scopes: new Set(['sam.read', 'sam.write'] as const), + }, + requestId: 't', + }; + await expect(archiveInboxItem(ctx, { projectId: P1, ref: `ask:${id}` })).resolves.toMatchObject( + { outcome: 'archived', agentNotified: true } + ); + expect(askRow(id).status).toBe('archived'); + const delivery = edges.acceptPromptDelivery.mock.calls[0]![2]; + expect(delivery.deliveryContent).toContain('archived your question'); + expect(delivery.metadata).toMatchObject({ questionAskId: id, outcome: 'archived' }); + // A late answer from the chat card meets the archived row. + await expect(answer(id, 'eu')).rejects.toMatchObject({ statusCode: 409 }); + }); +}); + +describe('the chat card read (GET …/attention/:id)', () => { + function app() { + const app = new Hono<{ Bindings: Env }>(); + const routes = new Hono<{ Bindings: Env }>(); + registerChatAttentionRoute(routes); + app.route('/api/projects/:projectId/sessions', routes); + app.onError((error, c) => + c.json({ message: error.message }, 'statusCode' in error ? (error.statusCode as 404) : 500) + ); + return app; + } + const read = (projectId: string, sessionId: string, id: string) => + app().request(`/api/projects/${projectId}/sessions/${sessionId}/attention/${id}`, {}, env); + + it('returns the shape a marker read had, answerable by the chat’s writer', async () => { + const { id, createdAt } = await question(); + const response = await read(P1, 'chat-1', id); + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ + request: { + id, + reason: 'Which region should the deploy use? EU keeps latency low for our users.', + options: ['eu', 'us'], + category: 'decision', + createdAt, + resolvedAt: null, + resolvedAnswer: null, + expired: false, + canAnswer: true, + }, + session: { id: 'chat-1', topic: 'Deploy chat' }, + messages: [], + since: null, + }); + await answer(id, 'eu'); + const settled = await (await read(P1, 'chat-1', id)).json(); + expect(settled.request).toMatchObject({ resolvedAnswer: 'eu', canAnswer: false }); + expect(settled.request.resolvedAt).not.toBeNull(); + }); + + it('attack: the id read through another project is not found; owner control reads it', async () => { + const { id } = await question(); + insert('project_members', { + project_id: P2, + user_id: 'owner', + role: 'owner', + status: 'active', + }); + edges.getSessionAccess.mockResolvedValue({ session: null, access: { found: false } }); + // Falls through to the marker path, which knows no such marker either. + vi.spyOn( + await import('../../../../src/services/project-data'), + 'getAttentionRequest' + ).mockResolvedValue({ + session: null, + access: { found: false, role: null, ownerUserId: null, grant: null }, + marker: null, + } as never); + expect((await read(P2, 'chat-2', id)).status).toBe(404); + edges.getSessionAccess.mockResolvedValue({ + session: { topic: 'Deploy chat' }, + access: { found: true, role: 'owner', ownerUserId: 'owner' }, + }); + expect((await read(P1, 'chat-1', id)).status).toBe(200); + }); + + function answer(id: string, text: string) { + return answerAttention(env, 'owner', P1, 'chat-1', id, text); + } +}); + +describe('a typed chat message answers the chat’s open questions', () => { + it('closes the chat’s open questions only, bound to project and chat, without a notice', async () => { + const a = await question(); + const b = await question({ context: 'Second question?' }); + const otherChat = await question({ sessionId: 'chat-x', taskId: 'task-x' }).catch(() => null); + expect(otherChat).toBeNull(); // task-x is not a task of the project + insert('asks', { + id: 'foreign', + project_id: P2, + assignee_kind: 'user', + assignee_user_id: 'outsider', + kind: 'question', + blocking: 1, + title: 'Same chat id, other project', + source_session_id: 'chat-1', + status: 'open', + created_at: 1, + updated_at: 1, + }); + const broadcast = vi.fn(); + const closed = await closeQuestionAsksForHumanMessage( + env as never, + { projectId: P1, sessionId: 'chat-1', messageId: 'msg-1' }, + broadcast + ); + expect(closed).toBe(2); + for (const id of [a.id, b.id]) { + expect(askRow(id)).toMatchObject({ status: 'answered' }); + expect(askRow(id).notified_at).not.toBeNull(); + } + expect(askRow('foreign').status).toBe('open'); + expect(broadcast).toHaveBeenCalledWith( + 'attention.resolved', + expect.objectContaining({ sessionId: 'chat-1', markerId: a.id, reason: 'human_message' }), + 'chat-1' + ); + // The card now reads it as resolved without an answer, as a marker resolved by a message. + await expect(answerAttention(env, 'owner', P1, 'chat-1', a.id, 'eu')).rejects.toMatchObject({ + statusCode: 409, + }); + }); +}); + +describe('the sweep runs a question’s schedule from asks', () => { + it('sends each reminder once at its point and then none', async () => { + const { id } = await question(); + await linkQuestionNotification(env, P1, id, 'notif-1'); + const created = Number(askRow(id).created_at); + // Before the first point: nothing. + await runInboxAskSweep(env, created + 29 * MINUTE); + expect(edges.resendPush).not.toHaveBeenCalled(); + await runInboxAskSweep(env, created + 31 * MINUTE); + expect(edges.resendPush).toHaveBeenCalledWith(env, 'owner', 'notif-1'); + expect(askRow(id)).toMatchObject({ escalation_count: 1 }); + expect(Number(askRow(id).next_escalation_at) - created).toBeCloseTo(90 * MINUTE, -3); + // A second tick at the same time does not send it again. + await runInboxAskSweep(env, created + 32 * MINUTE); + expect(edges.resendPush).toHaveBeenCalledOnce(); + await runInboxAskSweep(env, created + 91 * MINUTE); + expect(edges.resendPush).toHaveBeenCalledTimes(2); + expect(askRow(id)).toMatchObject({ escalation_count: 2, next_escalation_at: null }); + }); + + it('extends an undelivered question by the grace, then expires it at the hard limit', async () => { + const { id } = await question(); + await linkQuestionNotification(env, P1, id, 'notif-1'); + const created = Number(askRow(id).created_at); + const max = Number(askRow(id).max_expires_at); + await runInboxAskSweep(env, created + 121 * MINUTE); + expect(askRow(id).status).toBe('open'); + expect(Number(askRow(id).expires_at)).toBe(created + 121 * MINUTE + 120 * MINUTE); + expect(askRow(id).next_escalation_at).toBeNull(); + expect(edges.resendPush).toHaveBeenCalledWith(env, 'owner', 'notif-1'); + expect(edges.expireQuestionAsk).not.toHaveBeenCalled(); + // At the hard limit it expires even though no device confirmed the push. + sqlite.prepare('UPDATE asks SET expires_at = ? WHERE id = ?').run(max, id); + await runInboxAskSweep(env, max + 1); + expect(askRow(id).status).toBe('expired'); + expect(edges.expireQuestionAsk).toHaveBeenCalledWith(env, P1, { + askId: id, + sessionId: 'chat-1', + taskId: 'task-1', + workspaceId: 'ws-1', + createdAt: created, + }); + expect(askRow(id).notified_at).not.toBeNull(); + expect(edges.acceptPromptDelivery).not.toHaveBeenCalled(); + }); + + it('expires a delivered question at its deadline with today’s task outcome; a failed outcome is retried', async () => { + const { id } = await question(); + await linkQuestionNotification(env, P1, id, 'notif-1'); + edges.hasConfirmedPushDelivery.mockResolvedValue(true); + edges.expireQuestionAsk.mockRejectedValueOnce(new Error('DO unavailable')); + const deadline = Number(askRow(id).expires_at); + await runInboxAskSweep(env, deadline + 1); + expect(askRow(id)).toMatchObject({ status: 'expired', notified_at: null }); + await runInboxAskSweep(env, deadline + 2 * MINUTE); + expect(edges.expireQuestionAsk).toHaveBeenCalledTimes(2); + expect(askRow(id).notified_at).not.toBeNull(); + }); +}); diff --git a/apps/api/tests/unit/services/session-summary-index.test.ts b/apps/api/tests/unit/services/session-summary-index.test.ts index aeec32b80c..a9971d9fee 100644 --- a/apps/api/tests/unit/services/session-summary-index.test.ts +++ b/apps/api/tests/unit/services/session-summary-index.test.ts @@ -537,6 +537,114 @@ describe('listSessionsFromIndex', () => { }); }); + describe('open questions held in D1 asks (inbox slice G)', () => { + function addQuestion( + id: string, + sessionId: string, + opts: { projectId?: string; status?: string; createdAt?: number; expiresAt?: number } = {} + ): void { + sqlite + .prepare( + `INSERT INTO asks (id, project_id, assignee_kind, assignee_user_id, kind, blocking, title, + body_md, answer_spec_json, category, source_session_id, status, expires_at, + created_at, updated_at) + VALUES (?, ?, 'user', ?, 'question', 1, 'Pick one', 'Pick one of these, please.', + '{"type":"options","options":["a","b"],"allowText":false}', 'decision', ?, ?, ?, ?, ?)` + ) + .run( + id, + opts.projectId ?? PROJECT, + OWNER, + sessionId, + opts.status ?? 'open', + opts.expiresAt ?? now + 60_000, + opts.createdAt ?? 3_000, + opts.createdAt ?? 3_000 + ); + } + + it('shows a chat’s open question as its attention, in the shape a marker summary had', async () => { + addSession('chat-q', { status: 'active' }); + addSession('chat-plain', { status: 'active', lastMessageAt: 4000 }); + setCoverage(PROJECT, { sessionCount: 2 }); + addQuestion('ask-1', 'chat-q'); + // Attack fixtures: the same chat id in another project, and a closed question. + addQuestion('ask-foreign', 'chat-plain', { projectId: OTHER_PROJECT }); + addQuestion('ask-closed', 'chat-plain', { status: 'answered' }); + const out = await listSessionsFromIndex(env, { + projectId: PROJECT, + status: null, + limit: 10, + offset: 0, + createdByUserId: null, + }); + if (!('result' in out)) throw new Error('expected a result'); + const byId = new Map(out.result.sessions.map((session) => [session.id, session])); + expect(byId.get('chat-q')?.attention).toEqual({ + markerId: 'ask-1', + kind: 'needs_input', + source: 'request_human_input', + createdAt: 3_000, + expiresAt: now + 60_000, + reason: 'Pick one of these, please.', + options: ['a', 'b'], + category: 'decision', + interactionId: null, + interactionKind: null, + }); + expect(byId.get('chat-plain')?.attention).toBeNull(); + }); + + it('keeps a newer marker question, and puts the ask ahead of an older non-question marker', async () => { + const marker = (kind: string, createdAt: number) => + JSON.stringify({ + markerId: `m-${kind}`, + kind, + createdAt, + expiresAt: null, + reason: 'r', + options: [], + }); + addSession('newer-marker', { attentionJson: marker('needs_input', 9_000) }); + addSession('older-wake-failed', { attentionJson: marker('wake_failed', 9_000) }); + setCoverage(PROJECT, { sessionCount: 2 }); + addQuestion('ask-a', 'newer-marker', { createdAt: 3_000 }); + addQuestion('ask-b', 'older-wake-failed', { createdAt: 3_000 }); + const out = await listSessionsFromIndex(env, { + projectId: PROJECT, + status: null, + limit: 10, + offset: 0, + createdByUserId: null, + }); + if (!('result' in out)) throw new Error('expected a result'); + const byId = new Map(out.result.sessions.map((session) => [session.id, session])); + expect(byId.get('newer-marker')?.attention).toMatchObject({ markerId: 'm-needs_input' }); + expect(byId.get('older-wake-failed')?.attention).toMatchObject({ markerId: 'ask-b' }); + }); + + it('ranks an old chat waiting on a question in the attention group of the live read', async () => { + for (let index = 0; index < 4; index += 1) { + addSession(`quiet-${index}`, { status: 'active', lastMessageAt: 8_000 - index }); + } + addSession('old-asking', { status: 'active', lastMessageAt: 100 }); + setCoverage(PROJECT, { sessionCount: 5 }); + addQuestion('ask-old', 'old-asking'); + const out = await listSessionsFromIndex(env, { + projectId: PROJECT, + status: null, + limit: 2, + offset: 0, + createdByUserId: null, + includeLive: true, + }); + if (!('result' in out)) throw new Error('expected a result'); + expect( + out.result.sessions.find((session) => session.id === 'old-asking')?.attention + ).toMatchObject({ markerId: 'ask-old' }); + }); + }); + describe('includeLive — state-grouped sidebar reads', () => { /** * A page of two, newest first: `new-stopped`, `new-active`. Older than the page: @@ -683,8 +791,8 @@ describe('listSessionsFromIndex', () => { 'old-stopped', 'member-awake', ]); - // Coverage, count and page only. - expect(prepare).toHaveBeenCalledTimes(3); + // Coverage, count, page, and the open questions in `asks` (inbox slice G). + expect(prepare).toHaveBeenCalledTimes(4); }); it('serves the page without live rows when the live read fails', async () => { diff --git a/apps/api/tests/unit/stuck-task-live-runtime.test.ts b/apps/api/tests/unit/stuck-task-live-runtime.test.ts index a9db00c273..03a7551a9d 100644 --- a/apps/api/tests/unit/stuck-task-live-runtime.test.ts +++ b/apps/api/tests/unit/stuck-task-live-runtime.test.ts @@ -339,6 +339,7 @@ beforeEach(() => { d1 = new Database(':memory:'); createSchemaTables(d1, [ schema.agentSessions, + schema.asks, schema.tasks, schema.taskStatusEvents, schema.workspaces, @@ -595,6 +596,44 @@ describe('live-runtime record: what kept the task, and why', () => { expect(cleanupTaskRunMock).not.toHaveBeenCalled(); } ); + // Inbox slice G: a question is a D1 `asks` row; the guard reads it there (real SQLite). + function seedQuestionAsk( + overrides: { status?: string; expiresAt?: number; taskId?: string; projectId?: string } = {} + ) { + d1.prepare( + `INSERT INTO asks (id, project_id, assignee_kind, assignee_user_id, kind, blocking, title, + source_session_id, source_task_id, status, expires_at, created_at, updated_at) + VALUES ('ask-q', ?, 'user', 'user-1', 'question', 1, 'Which way?', ?, ?, ?, ?, ?, ?)` + ).run( + overrides.projectId ?? PROJECT_ID, + CHAT_SESSION_ID, + overrides.taskId ?? TASK_ID, + overrides.status ?? 'open', + overrides.expiresAt ?? T0 + MINUTE, + T0 - MINUTE, + T0 - MINUTE + ); + } + it('preserves a task whose open question is an asks row, without consulting the model', async () => { + quietPrompt(); + seedQuestionAsk(); + const aiRun = vi.fn().mockResolvedValue(stalledVerdict()); + await recoverStuckTasks(env({ AI: { run: aiRun } })); + expect(taskRow().status).toBe('in_progress'); + expect(aiRun).not.toHaveBeenCalled(); + expect(cleanupTaskRunMock).not.toHaveBeenCalled(); + }); + it.each([ + ['answered', { status: 'answered' }], + ['expired by time', { expiresAt: T0 - 1 }], + ['in another project', { projectId: 'other-project' }], + ])('consults the model when the asks question is %s (control)', async (_label, overrides) => { + quietPrompt(); + seedQuestionAsk(overrides); + const aiRun = vi.fn().mockResolvedValue(stalledVerdict()); + await recoverStuckTasks(env({ AI: { run: aiRun } })); + expect(aiRun).toHaveBeenCalledOnce(); + }); it('preserves needs-input even when a newer non-input marker exists', async () => { quietPrompt(); createAttentionMarker(doSql, { diff --git a/apps/api/tests/workers/inbox-capability.test.ts b/apps/api/tests/workers/inbox-capability.test.ts index d12ea8b7b8..66e952dc36 100644 --- a/apps/api/tests/workers/inbox-capability.test.ts +++ b/apps/api/tests/workers/inbox-capability.test.ts @@ -180,14 +180,156 @@ describe('inbox capability through the real entry points', () => { vi.unstubAllGlobals(); }); - it('a request_human_input question reaches the right inbox and archiving tells the agent', async () => { + it('a request_human_input question is one asks row that reaches the right inbox; archiving tells the agent', async () => { const s = await seed(); const result = await callTool(s.token, 'request_human_input', { context: 'Should I deploy the billing fix to staging first?', category: 'decision', options: ['Staging first', 'Straight to prod'], }); - expect(result).toBeTruthy(); + const askId = (result.humanInputRequest as { id: string }).id; + // One record: an asks row, no attention marker, no attention_json copy. + const row = await testEnv.DATABASE.prepare( + 'SELECT kind, status, project_id, source_session_id, blocking FROM asks WHERE id = ?' + ) + .bind(askId) + .first(); + expect(row).toEqual({ + kind: 'question', + status: 'open', + project_id: s.projectId, + source_session_id: s.chatSessionId, + blocking: 1, + }); + expect(await s.project.listActiveAttentionMarkers(s.chatSessionId)).toEqual([]); + await syncSummaries(s.project); + const summary = await testEnv.DATABASE.prepare( + 'SELECT attention_json FROM session_summaries WHERE id = ?' + ) + .bind(s.chatSessionId) + .first<{ attention_json: string | null }>(); + expect(summary?.attention_json ?? null).toBeNull(); + // The chat's own reads still show it as the chat's question (ProjectData session read). + expect(await s.project.getSession(s.chatSessionId)).toMatchObject({ + attention: { markerId: askId, kind: 'needs_input', source: 'request_human_input' }, + }); + + const ref = `ask:${askId}`; + const owner = await get('/api/inbox', s.ownerCookie); + const mine = owner.body.items.filter((item) => item.projectId === s.projectId); + expect(mine.map((item) => item.ref)).toEqual([ref]); + expect(mine[0]).toMatchObject({ kind: 'question', canAct: true }); + const colleague = await get('/api/inbox', s.colleagueCookie); + expect(colleague.body.items.map((item) => item.ref)).not.toContain(ref); + const count = await get<{ needsYou: number; blocking: number }>( + `/api/projects/${s.projectId}/inbox/count`, + s.ownerCookie + ); + expect(count.body).toEqual({ needsYou: 1, blocking: 1 }); + + // The agent ends its turn and the chat sleeps; archiving queues one wake-capable prompt. + expect(await s.project.sleepSession(s.chatSessionId)).toBe(true); + const archived = await post( + `/api/projects/${s.projectId}/inbox/items/${encodeURIComponent(ref)}/archive`, + s.ownerCookie + ); + expect(archived.status).toBe(200); + expect(archived.body).toMatchObject({ outcome: 'archived', agentNotified: true }); + const snapshot = await s.project.getDurableExecutionSnapshot(s.chatSessionId); + const notices = snapshot.deliveries.filter( + (delivery: { id: string }) => delivery.id === `inbox-ask:${askId}` + ); + expect(notices).toEqual([ + expect.objectContaining({ sourceKind: 'inbox_ask', sourceTaskId: s.taskId }), + ]); + const { messages } = await s.project.getMessages(s.chatSessionId, 50); + expect( + messages.filter((message: { content: string }) => + message.content.includes('archived your question') + ) + ).toHaveLength(1); + // The item leaves the inbox; a late answer loses. + const after = await get('/api/inbox', s.ownerCookie); + expect(after.body.items.map((entry) => entry.ref)).not.toContain(ref); + const late = await post( + `/api/projects/${s.projectId}/inbox/items/${encodeURIComponent(ref)}/answer`, + s.ownerCookie, + { answer: 'Staging first' } + ); + expect(late.status).toBe(409); + }); + + it('answering an asks question of a sleeping chat queues the answer once as a wake', async () => { + const s = await seed(); + const result = await callTool(s.token, 'request_human_input', { + context: 'Ship the billing fix now?', + options: ['Yes', 'No'], + }); + const askId = (result.humanInputRequest as { id: string }).id; + expect(await s.project.sleepSession(s.chatSessionId)).toBe(true); + // The chat card path and the inbox path meet at the same compare-and-set. + const [inbox, card] = await Promise.all([ + post( + `/api/projects/${s.projectId}/inbox/items/${encodeURIComponent(`ask:${askId}`)}/answer`, + s.ownerCookie, + { answer: 'Yes' } + ), + SELF.fetch( + `https://api.${testEnv.BASE_DOMAIN}/api/projects/${s.projectId}/sessions/${s.chatSessionId}/attention/${askId}/resolve`, + { + method: 'POST', + headers: { Cookie: s.ownerCookie, 'Content-Type': 'application/json', Origin: ORIGIN }, + body: JSON.stringify({ answer: 'No' }), + } + ), + ]); + const statuses = [inbox.status, card.status].sort(); + expect(statuses).toEqual([200, 409]); + const row = await testEnv.DATABASE.prepare( + 'SELECT status, answer_json, notified_at FROM asks WHERE id = ?' + ) + .bind(askId) + .first<{ status: string; answer_json: string; notified_at: number | null }>(); + expect(row?.status).toBe('answered'); + expect(row?.notified_at).not.toBeNull(); + const winner = (JSON.parse(row!.answer_json) as { text: string }).text; + const snapshot = await s.project.getDurableExecutionSnapshot(s.chatSessionId); + expect( + snapshot.deliveries.filter((delivery: { id: string }) => delivery.id === `inbox-ask:${askId}`) + ).toEqual([expect.objectContaining({ sourceKind: 'inbox_ask', sourceTaskId: s.taskId })]); + const { messages } = await s.project.getMessages(s.chatSessionId, 50); + const answers = messages.filter((message: { content: string }) => + message.content.startsWith('The person answered your question') + ); + expect(answers).toHaveLength(1); + expect(answers[0]!.content).toContain(winner); + // The chat card reads the settled question. + const read = await SELF.fetch( + `https://api.${testEnv.BASE_DOMAIN}/api/projects/${s.projectId}/sessions/${s.chatSessionId}/attention/${askId}`, + { headers: { Cookie: s.ownerCookie } } + ); + expect(await read.json()).toMatchObject({ + request: { id: askId, resolvedAnswer: winner, canAnswer: false }, + }); + }); + + // Overlap (slice G): a question asked before the deploy is still a ProjectData marker and stays + // answerable and archivable through its own path until it resolves or expires. + it('a marker-era question reaches the right inbox and archiving tells the agent', async () => { + const s = await seed(); + await s.project.createAttentionMarker({ + sessionId: s.chatSessionId, + taskId: s.taskId, + workspaceId: s.workspaceId, + kind: 'needs_input', + source: 'request_human_input', + reason: 'Should I deploy the billing fix to staging first?', + metadata: JSON.stringify({ + category: 'decision', + options: ['Staging first', 'Straight to prod'], + }), + expiresAt: Date.now() + 3_600_000, + }); // The colleague's private chat also has an open question; it must not reach the owner. await s.project.createAttentionMarker({ sessionId: s.colleagueSessionId, diff --git a/apps/api/tests/workers/notification-push-do.test.ts b/apps/api/tests/workers/notification-push-do.test.ts index 48553b0cf8..f523dcc1f2 100644 --- a/apps/api/tests/workers/notification-push-do.test.ts +++ b/apps/api/tests/workers/notification-push-do.test.ts @@ -409,8 +409,16 @@ describe('Notification DO Web Push migration and delivery', () => { await vi.waitFor(async () => { expect(await notification.hasConfirmedPushDelivery(userId, pushed.id)).toBe(true); }); - const [marker] = await projectData.listActiveAttentionMarkers(sessionId); - if (!marker) throw new Error('Expected an active needs_input marker'); + // Inbox slice G: the question is one D1 `asks` row; the notification points at it. + const marker = { + id: String((pushed.metadata as { attentionMarkerId: string }).attentionMarkerId), + }; + expect(await projectData.listActiveAttentionMarkers(sessionId)).toEqual([]); + expect( + await env.DATABASE.prepare('SELECT kind, status, notification_id FROM asks WHERE id = ?') + .bind(marker.id) + .first() + ).toEqual({ kind: 'question', status: 'open', notification_id: pushed.id }); const signedBrowserSessionToken = `${browserSessionToken}.${await makeSignature( browserSessionToken, env.BETTER_AUTH_SECRET || env.ENCRYPTION_KEY @@ -454,11 +462,13 @@ describe('Notification DO Web Push migration and delivery', () => { alreadyResolved: false, answer: 'Ship now', }); - expect(promptCalls()).toHaveLength(1); - expect(JSON.parse(String(promptCalls()[0]?.[1]?.body))).toEqual({ - prompt: 'Ship now', - messageId: marker.id, - }); + // The answer goes to the agent as one durable prompt (the wake path), not a direct live prompt. + const snapshot = await projectData.getDurableExecutionSnapshot(sessionId); + expect( + snapshot.deliveries.filter( + (delivery: { id: string }) => delivery.id === `inbox-ask:${marker.id}` + ) + ).toEqual([expect.objectContaining({ sourceKind: 'inbox_ask', sourceTaskId: taskId })]); const replayResponse = await resolveAttention(marker.id, 'Ship now'); expect(replayResponse.status).toBe(200); @@ -468,8 +478,15 @@ describe('Notification DO Web Push migration and delivery', () => { answer: 'Ship now', }); expect((await resolveAttention(marker.id, 'Wait')).status).toBe(409); - expect(promptCalls()).toHaveLength(1); + const answered = await env.DATABASE.prepare( + 'SELECT status, answer_json, notified_at FROM asks WHERE id = ?' + ) + .bind(marker.id) + .first<{ status: string; answer_json: string; notified_at: number | null }>(); + expect(answered).toMatchObject({ status: 'answered', answer_json: '{"text":"Ship now"}' }); + expect(answered?.notified_at).not.toBeNull(); + // Overlap control: a question still held as a marker answers through its own path. const freeFormMarker = await projectData.createAttentionMarker({ sessionId, taskId, @@ -486,25 +503,16 @@ describe('Notification DO Web Push migration and delivery', () => { alreadyResolved: false, answer: 'Use the canary deployment', }); - expect(promptCalls()).toHaveLength(2); - expect(JSON.parse(String(promptCalls()[1]?.[1]?.body))).toEqual({ + const freeFormPrompts = promptCalls().filter( + (call) => JSON.parse(String(call[1]?.body)).messageId === freeFormMarker.id + ); + expect(freeFormPrompts).toHaveLength(1); + expect(JSON.parse(String(freeFormPrompts[0]?.[1]?.body))).toEqual({ prompt: 'Use the canary deployment', messageId: freeFormMarker.id, }); expect(await projectData.listActiveAttentionMarkers(sessionId)).toEqual([]); await runInDurableObject(projectData, async (instance) => { - const rows = (instance as unknown as { sql: SqlStorage }).sql - .exec( - 'SELECT resolved_reason, resolved_answer FROM session_attention_markers WHERE id = ?', - marker.id - ) - .toArray(); - expect(rows).toEqual([ - expect.objectContaining({ - resolved_reason: 'structured_answer', - resolved_answer: 'Ship now', - }), - ]); const freeFormRows = (instance as unknown as { sql: SqlStorage }).sql .exec( 'SELECT resolved_reason, resolved_answer FROM session_attention_markers WHERE id = ?', diff --git a/apps/www/src/content/docs/docs/guides/admin-settings.md b/apps/www/src/content/docs/docs/guides/admin-settings.md index dadbfec641..6434503840 100644 --- a/apps/www/src/content/docs/docs/guides/admin-settings.md +++ b/apps/www/src/content/docs/docs/guides/admin-settings.md @@ -273,6 +273,20 @@ items agents file (`packages/operations/src/inbox-settings-definition.ts`). | `inbox.noticeRetryMinutes` | 60 | 5–1,440 | Minutes the sweep retries telling an agent its item was answered, archived or expired | | `inbox.sweepBatchSize` | 10 | 1–50 | Items one five-minute sweep expires or re-notifies (each is a write and an agent notice) | +A question an agent asks with `request_human_input` is an inbox item, and these settings set its +schedule (`apps/api/src/services/inbox/sweep.ts`, every five minutes): + +| Setting | Default | Range | What it controls | +| --------------------------------------- | ------- | ------- | ------------------------------------------------------------------------------------ | +| `inbox.questionTimeoutMinutes` | 120 | 1–1,440 | Minutes a question stays open once its notification reached you; then the task stops | +| `inbox.questionFirstReminderPercent` | 25 | 0–99 | Point in that window (percent) where the push is sent again; 0 turns it off | +| `inbox.questionSecondReminderPercent` | 75 | 0–99 | Point in that window (percent) where the push is sent a last time; 0 turns it off | +| `inbox.questionUndeliveredGraceMinutes` | 120 | 1–1,440 | Extra minutes, with the push resent, when no device confirmed the notification | +| `inbox.questionMaxWaitMinutes` | 1,440 | 1–4,320 | Most minutes a question stays open even when its notification never arrived | + +A changed setting applies to questions asked afterwards; an open question keeps the deadline it was +given, and its reminders follow the current percentages. + ## Node provisioning This **Operations** setting bounds one durable node-provisioning attempt diff --git a/apps/www/src/content/docs/docs/guides/notifications.md b/apps/www/src/content/docs/docs/guides/notifications.md index eae65f7a38..1b3c6bb881 100644 --- a/apps/www/src/content/docs/docs/guides/notifications.md +++ b/apps/www/src/content/docs/docs/guides/notifications.md @@ -188,10 +188,9 @@ notifies again. | `NOTIFICATION_PAGE_SIZE` | `50` | Default page size for notification list | | `CRON_FAILURE_NOTIFICATION_THROTTLE_MS` | `3600000` (1 hr) | Per-sweep superadmin alert throttle; also how long an archive-breaker alert claim is held | | `CRON_FAILURE_NOTIFICATION_KV_PREFIX` | `cron-failure-notification` | KV prefix used for coarse throttle markers and atomic deduplication keys | -| `HUMAN_INPUT_TIMEOUT_MS` | `7200000` (2 hr) | Initial needs-input response window | -| `HUMAN_INPUT_ESCALATION_FRACTIONS` | `0.25,0.75` | Fractions of the initial window at which reminders fire | -| `HUMAN_INPUT_UNDELIVERED_GRACE_MS` | `7200000` (2 hr) | Extension when no push delivery was confirmed | -| `HUMAN_INPUT_MAX_WAIT_MS` | `86400000` (24 hr) | Hard maximum needs-input marker lifetime | +| `HUMAN_INPUT_ESCALATION_FRACTIONS` | `0.25,0.75` | Reminder points, questions asked before the inbox move only | +| `HUMAN_INPUT_UNDELIVERED_GRACE_MS` | `7200000` (2 hr) | Undelivered grace, questions asked before the inbox move only | +| `HUMAN_INPUT_MAX_WAIT_MS` | `86400000` (24 hr) | Hard limit, questions asked before the inbox move only | | `WEB_PUSH_TTL_SECONDS` | `86400` | Push-service message TTL | | `WEB_PUSH_VAPID_TTL_SECONDS` | `43200` | VAPID authorization-token lifetime | | `WEB_PUSH_DELIVERY_TIMEOUT_MS` | `10000` | Per-attempt push-service timeout | @@ -204,3 +203,10 @@ notifies again. | `WEB_PUSH_MAX_SUBSCRIPTIONS_PER_USER` | `8` | Maximum retained browser endpoints per user | | `WEB_PUSH_USER_AGENT_MAX_LENGTH` | `512` | Maximum stored browser description length | | `RATE_LIMIT_PUSH_SUBSCRIPTION` | `30` | Subscription mutations per user per hour | + +A question an agent asks with `request_human_input` follows the schedule in the admin settings +`inbox.questionTimeoutMinutes`, `inbox.questionFirstReminderPercent`, +`inbox.questionSecondReminderPercent`, `inbox.questionUndeliveredGraceMinutes` and +`inbox.questionMaxWaitMinutes` (see [Admin settings](/docs/guides/admin-settings/)). The three +`HUMAN_INPUT_*` variables above apply only to questions asked before that change, until they are +answered or expire. diff --git a/apps/www/src/content/docs/docs/reference/api.md b/apps/www/src/content/docs/docs/reference/api.md index a3ac19c376..62bd33e5a8 100644 --- a/apps/www/src/content/docs/docs/reference/api.md +++ b/apps/www/src/content/docs/docs/reference/api.md @@ -520,9 +520,10 @@ The list returns `{ pending, settled, cursor }` and needs `task:read` on the pro Everything agents are waiting on from you, one item per ask, across projects (`apps/api/src/routes/inbox.ts`, operations in `packages/operations/src/inbox-*.ts`). The list reads -each ask where it is stored: questions and permission requests from the chat index -(`session_summaries`), [secret requests](/docs/guides/secret-execution/#let-the-agent-ask-you-for-a-secret), -Operations approvals, and inbox asks (reviews and tasks agents file). Nothing is copied. +each ask where it is stored: inbox asks (questions agents ask with `request_human_input`, and the +reviews and tasks they file), permission requests from the chat index (`session_summaries`), +[secret requests](/docs/guides/secret-execution/#let-the-agent-ask-you-for-a-secret) and Operations +approvals. Nothing is copied. | Method | Endpoint | Purpose | | ------ | --------------------------------------------------- | ---------------------------------------------- | @@ -543,8 +544,8 @@ that could not be read. You see an ask assigned to you (or an unclaimed team ask chats you created, secret requests your agents made (and, when the member whose agent asked cannot supply secrets, the requests of members who cannot, if you can), and, as an active superadmin, Operations approvals in projects you belong to. Opening, answering or archiving an -item by `ref` follows the same rules; a question is also open to anyone the chat is shared with. Until questions move into inbox asks, a chat lists only its -newest open question. +item by `ref` follows the same rules. A question asked before questions became inbox asks is listed +from the chat index (`attention:` ref, the newest one per chat) until it is answered or expires. Each item has a `ref` naming its store (`ask:`, `attention::`, `secret:`, `approval:`), `kind` (`question`, `permission`, `form`, `url`, `secret`, @@ -556,13 +557,15 @@ looks like: `options` or `text` (`{ "answer": "…" }`), `interaction` (`{ "opti (`{ "secret": { "value": "…", "replaceExisting": true, "expectedExistingVersion": "…" } }` or `{ "decline": true }`), `approval` (`{ "decision": "approve" | "deny", "note": "…" }`) or `acknowledge` (`{}` or `{ "answer": "comment" }`). Answers go through the existing path for each -store: the question answer, the permission answer, secret fulfil/decline, and the approval decision. +store: the question answer (the same one the chat card uses, so two answers meet at one +compare-and-set and the loser gets `409`), the permission answer, secret fulfil/decline, and the +approval decision. Secret values and Operations approval decisions are accepted only from the SAM app, never through an app connected to the Connector (`403`). Answering or archiving an item filed from a chat needs the same right to wake that chat's agent as answering in the chat. -Archive closes an item for every kind: an inbox ask becomes `archived`, a question is resolved -with reason `archived`, a permission or approval is denied, and a secret request is declined. Each +Archive closes an item for every kind: an inbox ask (a question too) becomes `archived`, a +question asked before that change is resolved with reason `archived`, a permission or approval is denied, and a secret request is declined. Each tells the agent you will not act. Both writes return `{ ref, outcome, agentNotified }`; `agentNotified: false` on an ask means its notice was not queued yet, and SAM retries it for `inbox.noticeRetryMinutes`. Writes must come from the app's own origin with @@ -586,7 +589,7 @@ A chat's creator can give another project member the same controls in that one c Comment threads and replies accept an optional `mentions: [{ "userId": "..." }]`. The server keeps active project members only, stores each person's display name at the time, and returns `400` above `collaboration.commentMentionsMax`. -`GET /api/projects/:id/sessions/:sessionId/attention/:markerId` returns the full saved question an agent asked with `request_human_input`, for the question card in the conversation (`apps/api/src/routes/chat-attention.ts`): the request (its text, choices, `category` (`decision`, `clarification`, `approval`, `error_help`, or `null`), whether it is resolved or expired, and `canAnswer`) and the session's id and topic. It needs `task:read`. `canAnswer` is true only for the chat's owner, or a teammate it is shared with, while the question is open. Add `?context=true` for the messages before it (`messages`): `collaboration.commentContextMessages` of them by default, or `limit`, capped by the session message limit; and for what the agent did since asking (`since`: the messages after it, `activityCount` tool runs, and `truncated` when more happened than the read covers). A question from another chat, or one that isn't an agent question, returns `404`. Answer it with `POST .../attention/:markerId/resolve`. +`GET /api/projects/:id/sessions/:sessionId/attention/:markerId` returns the full saved question an agent asked with `request_human_input`, for the question card in the conversation (`apps/api/src/routes/chat-attention.ts`): the request (its text, choices, `category` (`decision`, `clarification`, `approval`, `error_help`, or `null`), whether it is resolved or expired, and `canAnswer`) and the session's id and topic. It needs `task:read`. `canAnswer` is true only for the chat's owner, or a teammate it is shared with, while the question is open. Add `?context=true` for the messages before it (`messages`): `collaboration.commentContextMessages` of them by default, or `limit`, capped by the session message limit; and for what the agent did since asking (`since`: the messages after it, `activityCount` tool runs, and `truncated` when more happened than the read covers). A question from another chat, or one that isn't an agent question, returns `404`. Answer it with `POST .../attention/:markerId/resolve` and `{ "answer": "…" }`: `200` with `{ resolved: true, alreadyResolved, answer }` once it reached the agent (or the same answer already had), `202` with `{ inFlight: true }` while the answer is still being delivered (SAM retries it), `409` when a different answer is being delivered or the question is closed, and `400` for an answer outside the choices. `:markerId` is the question's inbox ask id, the id `request_human_input` returns (`apps/api/src/services/inbox/question-asks.ts`); a question asked before questions became inbox asks is read and answered by its attention marker id until it is answered or expires. `GET /api/projects/:id/secret-requests/:requestId` returns one agent [secret request](/docs/guides/secret-execution/#let-the-agent-ask-you-for-a-secret) for the card in the conversation (`apps/api/src/routes/projects/secret-requests.ts`): the variable name, the agent's reason, the requested expiry, its status (`pending`, `fulfilled`, `declined`, `expired`), who answered it, whether a project variable with that name already exists, and `canResolve`. It needs `secret:read`, and never includes a value. `POST .../fulfill` with `{ "value": "…", "replaceExisting": true, "expectedExistingVersion": "…" }` stores the value as an encrypted project secret and wakes the requesting agent with a notice that names the variable only; it needs `secret:write`, and `replaceExisting` is required when the name already exists (`409` otherwise). `expectedExistingVersion` (the `existing.version` the person confirmed, an opaque fingerprint) is required with it; if it is missing, or the stored value has changed since (or changes before the write), the request returns `409` and stays open. `POST .../decline` closes the request. Both return `{ request, agentNotified }`; `agentNotified: false` means the agent's notice could not be queued yet (SAM retries it for `secrets.notifyRetryMinutes`, and the card asks you to tell the agent). Both are writes from the app's own browser flow: they require an `Origin` header equal to the app origin (`https://app.`; any other or missing origin returns `403`) and `Content-Type: application/json` (`415` otherwise), so another site, including a workspace port on the same domain, cannot submit one on your behalf. An empty value or one over the runtime variable size limit returns `400`, as does a project already at its variable limit; the request stays open. A request that was already answered returns `409`; one past its deadline returns `410`. A request from another project returns `404`. diff --git a/apps/www/src/content/docs/docs/reference/configuration.md b/apps/www/src/content/docs/docs/reference/configuration.md index 12f26acecb..42a3789cdc 100644 --- a/apps/www/src/content/docs/docs/reference/configuration.md +++ b/apps/www/src/content/docs/docs/reference/configuration.md @@ -769,10 +769,9 @@ aggregate operator-visible counters. | `MAX_NOTIFICATIONS_PER_USER` | `500` | Max stored notifications per user | | `NOTIFICATION_PAGE_SIZE` | `50` | Default page size for notification list | | `MAX_NOTIFICATION_PAGE_SIZE` | `100` | Max allowed page size | -| `HUMAN_INPUT_TIMEOUT_MS` | `7200000` (2 hr) | Initial needs-input response window | -| `HUMAN_INPUT_ESCALATION_FRACTIONS` | `0.25,0.75` | Reminder points within the initial response window | -| `HUMAN_INPUT_UNDELIVERED_GRACE_MS` | `7200000` (2 hr) | Extension without confirmed push delivery | -| `HUMAN_INPUT_MAX_WAIT_MS` | `86400000` (24 hr) | Hard maximum needs-input marker lifetime | +| `HUMAN_INPUT_ESCALATION_FRACTIONS` | `0.25,0.75` | Reminder points, questions asked before the inbox move only | +| `HUMAN_INPUT_UNDELIVERED_GRACE_MS` | `7200000` (2 hr) | Undelivered grace, questions asked before the inbox move only | +| `HUMAN_INPUT_MAX_WAIT_MS` | `86400000` (24 hr) | Hard limit, questions asked before the inbox move only | | `WEB_PUSH_TTL_SECONDS` | `86400` | Push-service message TTL | | `WEB_PUSH_VAPID_TTL_SECONDS` | `43200` | VAPID authorization-token lifetime | | `WEB_PUSH_DELIVERY_TIMEOUT_MS` | `10000` | Per-attempt push-service timeout | diff --git a/packages/operations/src/inbox-ask-create-core.ts b/packages/operations/src/inbox-ask-create-core.ts new file mode 100644 index 0000000000..5f8c39803c --- /dev/null +++ b/packages/operations/src/inbox-ask-create-core.ts @@ -0,0 +1,166 @@ +/** + * File one inbox ask (`asks` row): the internal create operation agent tools and SAM call + * (`request_human_input` since slice G). Split out of `inbox-write-core.ts` + * (`.claude/rules/18-file-size-limits.md`). + */ +import { + ASK_ASSIGNEE_KINDS, + ASK_KINDS, + HUMAN_INPUT_CATEGORIES, +} from '@simple-agent-manager/shared'; +import { ulid } from '@simple-agent-manager/worker-core'; +import * as v from 'valibot'; + +import { OperationError } from './errors'; +import { AskAnswerSpecSchema, InboxLinksSchema } from './inbox-rows'; +import { getInboxLimits } from './inbox-settings'; +import type { OperationContext } from './types'; + +const id = v.pipe(v.string(), v.minLength(1), v.maxLength(128)); + +export const CreateAskInputSchema = v.object({ + projectId: id, + assigneeKind: v.optional(v.picklist(ASK_ASSIGNEE_KINDS), 'user'), + assigneeUserId: v.optional(id), + kind: v.picklist(ASK_KINDS), + blocking: v.optional(v.boolean(), false), + title: v.pipe(v.string(), v.trim(), v.minLength(1)), + body: v.optional(v.string()), + answerSpec: v.optional(AskAnswerSpecSchema), + steps: v.optional( + v.pipe(v.array(v.pipe(v.string(), v.minLength(1), v.maxLength(500))), v.maxLength(50)), + [] + ), + links: v.optional(InboxLinksSchema, []), + dueHint: v.optional(v.pipe(v.string(), v.maxLength(200))), + dueAt: v.optional(v.pipe(v.number(), v.safeInteger())), + expiresAt: v.optional(v.pipe(v.number(), v.safeInteger())), + sourceSessionId: v.optional(id), + sourceTaskId: v.optional(id), + sourceMessageId: v.optional(id), + agentProfileId: v.optional(id), + groupKey: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(200))), + dedupeKey: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(200))), + // Questions (`request_human_input`, slice G): reminders and the expiry outcome. + sourceWorkspaceId: v.optional(id), + category: v.optional(v.picklist(HUMAN_INPUT_CATEGORIES)), + nextEscalationAt: v.optional(v.pipe(v.number(), v.safeInteger())), + maxExpiresAt: v.optional(v.pipe(v.number(), v.safeInteger())), +}); +export type CreateAskInput = v.InferInput; + +/** + * File one ask. Internal: later slices call it (agent tools, system errors); no surface exposes + * it yet. The assignee must be an active member, a source task must belong to the project, and + * a chat may hold at most `inbox.openItemsPerChat` open items. A repeated `dedupeKey` returns the + * existing row instead of filing a second one. + */ +export async function createAsk( + ctx: OperationContext, + rawInput: CreateAskInput, + /** Filing time; a caller that computed a schedule from it passes the same instant. */ + now: number = Date.now() +): Promise<{ ref: string; id: string; created: boolean }> { + const input = v.parse(CreateAskInputSchema, rawInput); + const limits = await getInboxLimits(ctx); + if (input.title.length > limits.titleMaxChars) + throw new OperationError('invalid_input', `title exceeds ${limits.titleMaxChars} characters`); + if (input.body && input.body.length > limits.bodyMaxChars) + throw new OperationError('invalid_input', `body exceeds ${limits.bodyMaxChars} characters`); + if (input.links.length > limits.linksMax) + throw new OperationError('invalid_input', `at most ${limits.linksMax} links`); + if (input.assigneeKind === 'user' && !input.assigneeUserId) + throw new OperationError('invalid_input', 'assigneeUserId is required for a user assignee'); + if (input.assigneeKind === 'team' && input.assigneeUserId) + throw new OperationError('invalid_input', 'A team item has no assigneeUserId'); + if (input.sourceSessionId && !input.sourceTaskId) + throw new OperationError('invalid_input', 'sourceTaskId is required with sourceSessionId'); + + const db = ctx.env.DATABASE; + if (input.assigneeUserId) { + const member = await db + .prepare( + `SELECT 1 AS ok FROM project_members + WHERE project_id = ? AND user_id = ? AND status = 'active'` + ) + .bind(input.projectId, input.assigneeUserId) + .first(); + if (!member) + throw new OperationError('invalid_input', 'The assignee is not an active project member'); + } + if (input.sourceTaskId) { + const task = await db + .prepare('SELECT chat_session_id FROM tasks WHERE id = ? AND project_id = ?') + .bind(input.sourceTaskId, input.projectId) + .first<{ chat_session_id: string | null }>(); + if (!task) + throw new OperationError('invalid_input', 'sourceTaskId is not a task of this project'); + // The chat must be the task's own (a task that handed its chat to a recovery successor has none). + if ( + input.sourceSessionId && + task.chat_session_id && + task.chat_session_id !== input.sourceSessionId + ) + throw new OperationError('invalid_input', 'sourceSessionId is not the chat of sourceTaskId'); + } + + const askId = ulid(); + // One statement: the per-chat cap and the insert cannot interleave with another filing. + const inserted = await db + .prepare( + `INSERT INTO asks (id, project_id, assignee_kind, assignee_user_id, kind, blocking, title, + body_md, answer_spec_json, steps_json, links_json, due_hint, due_at, source_session_id, + source_task_id, source_message_id, agent_profile_id, group_key, dedupe_key, status, + expires_at, source_workspace_id, category, next_escalation_at, max_expires_at, + created_at, updated_at) + SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?, ?, ?, ?, ? + WHERE ? IS NULL + OR (SELECT COUNT(*) FROM asks WHERE source_session_id = ? AND project_id = ? AND status = 'open') < ? + ON CONFLICT (project_id, dedupe_key) WHERE dedupe_key IS NOT NULL DO NOTHING` + ) + .bind( + askId, + input.projectId, + input.assigneeKind, + input.assigneeUserId ?? null, + input.kind, + input.blocking ? 1 : 0, + input.title, + input.body ?? null, + input.answerSpec ? JSON.stringify(input.answerSpec) : null, + input.steps.length ? JSON.stringify(input.steps) : null, + input.links.length ? JSON.stringify(input.links) : null, + input.dueHint ?? null, + input.dueAt ?? null, + input.sourceSessionId ?? null, + input.sourceTaskId ?? null, + input.sourceMessageId ?? null, + input.agentProfileId ?? null, + input.groupKey ?? null, + input.dedupeKey ?? null, + input.expiresAt ?? null, + input.sourceWorkspaceId ?? null, + input.category ?? null, + input.nextEscalationAt ?? null, + input.maxExpiresAt ?? null, + now, + now, + input.sourceSessionId ?? null, + input.sourceSessionId ?? null, + input.projectId, + limits.openItemsPerChat + ) + .run(); + if ((inserted.meta?.changes ?? 0) === 1) return { ref: `ask:${askId}`, id: askId, created: true }; + if (input.dedupeKey) { + const existing = await db + .prepare('SELECT id FROM asks WHERE project_id = ? AND dedupe_key = ?') + .bind(input.projectId, input.dedupeKey) + .first<{ id: string }>(); + if (existing) return { ref: `ask:${existing.id}`, id: existing.id, created: false }; + } + throw new OperationError( + 'rate_limited', + `This chat already has ${limits.openItemsPerChat} open inbox items` + ); +} diff --git a/packages/operations/src/inbox-operations.ts b/packages/operations/src/inbox-operations.ts index dcf1c115b6..38138801cf 100644 --- a/packages/operations/src/inbox-operations.ts +++ b/packages/operations/src/inbox-operations.ts @@ -9,13 +9,12 @@ import * as v from 'valibot'; import { authorizeProjectOperation } from './authorization'; import { ConnectorAnswerFields } from './connector-answer-input'; import { requireReadScope } from './connector-read-core'; +import { createAsk, CreateAskInputSchema } from './inbox-ask-create-core'; import { getInboxItem } from './inbox-item-core'; import { countInbox, listInbox } from './inbox-list-core'; import { answerInboxItem, archiveInboxItem, - createAsk, - CreateAskInputSchema, prepareInboxAnswer, prepareInboxArchive, } from './inbox-write-core'; diff --git a/packages/operations/src/inbox-write-core.ts b/packages/operations/src/inbox-write-core.ts index 7255f3077b..b0327fb4ff 100644 --- a/packages/operations/src/inbox-write-core.ts +++ b/packages/operations/src/inbox-write-core.ts @@ -1,5 +1,5 @@ /** - * Inbox writes: file an `asks` row (internal; no agent tool yet), answer and archive any item. + * Inbox writes: answer and archive any item (filing an ask is `inbox-ask-create-core.ts`). * * `asks` rows are written here with compare-and-set on the previous status and `project_id` in * every predicate (rule 11). Every other store is answered and archived through the path it @@ -8,172 +8,18 @@ */ import { type AcpInteractionBrowserAnswer, - ASK_ASSIGNEE_KINDS, - ASK_KINDS, - HUMAN_INPUT_CATEGORIES, type InboxActionResponse, type InboxItem, type ParsedInboxRef, } from '@simple-agent-manager/shared'; -import { ulid } from '@simple-agent-manager/worker-core'; -import * as v from 'valibot'; import { authorizeProjectOperation } from './authorization'; import { OperationError } from './errors'; import { INBOX_NOT_FOUND, resolveInboxItem } from './inbox-item-core'; -import { AskAnswerSpecSchema, InboxLinksSchema } from './inbox-rows'; import { getInboxLimits } from './inbox-settings'; import type { InboxAskNoticeOutcome, InboxAskNoticeRow } from './ports'; import type { OperationContext } from './types'; -const id = v.pipe(v.string(), v.minLength(1), v.maxLength(128)); - -export const CreateAskInputSchema = v.object({ - projectId: id, - assigneeKind: v.optional(v.picklist(ASK_ASSIGNEE_KINDS), 'user'), - assigneeUserId: v.optional(id), - kind: v.picklist(ASK_KINDS), - blocking: v.optional(v.boolean(), false), - title: v.pipe(v.string(), v.trim(), v.minLength(1)), - body: v.optional(v.string()), - answerSpec: v.optional(AskAnswerSpecSchema), - steps: v.optional( - v.pipe(v.array(v.pipe(v.string(), v.minLength(1), v.maxLength(500))), v.maxLength(50)), - [] - ), - links: v.optional(InboxLinksSchema, []), - dueHint: v.optional(v.pipe(v.string(), v.maxLength(200))), - dueAt: v.optional(v.pipe(v.number(), v.safeInteger())), - expiresAt: v.optional(v.pipe(v.number(), v.safeInteger())), - sourceSessionId: v.optional(id), - sourceTaskId: v.optional(id), - sourceMessageId: v.optional(id), - agentProfileId: v.optional(id), - groupKey: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(200))), - dedupeKey: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(200))), - // Questions (`request_human_input`, slice G): reminders and the expiry outcome. - sourceWorkspaceId: v.optional(id), - category: v.optional(v.picklist(HUMAN_INPUT_CATEGORIES)), - nextEscalationAt: v.optional(v.pipe(v.number(), v.safeInteger())), - maxExpiresAt: v.optional(v.pipe(v.number(), v.safeInteger())), -}); -export type CreateAskInput = v.InferInput; - -/** - * File one ask. Internal: later slices call it (agent tools, system errors); no surface exposes - * it yet. The assignee must be an active member, a source task must belong to the project, and - * a chat may hold at most `inbox.openItemsPerChat` open items. A repeated `dedupeKey` returns the - * existing row instead of filing a second one. - */ -export async function createAsk( - ctx: OperationContext, - rawInput: CreateAskInput -): Promise<{ ref: string; id: string; created: boolean }> { - const input = v.parse(CreateAskInputSchema, rawInput); - const limits = await getInboxLimits(ctx); - if (input.title.length > limits.titleMaxChars) - throw new OperationError('invalid_input', `title exceeds ${limits.titleMaxChars} characters`); - if (input.body && input.body.length > limits.bodyMaxChars) - throw new OperationError('invalid_input', `body exceeds ${limits.bodyMaxChars} characters`); - if (input.links.length > limits.linksMax) - throw new OperationError('invalid_input', `at most ${limits.linksMax} links`); - if (input.assigneeKind === 'user' && !input.assigneeUserId) - throw new OperationError('invalid_input', 'assigneeUserId is required for a user assignee'); - if (input.assigneeKind === 'team' && input.assigneeUserId) - throw new OperationError('invalid_input', 'A team item has no assigneeUserId'); - if (input.sourceSessionId && !input.sourceTaskId) - throw new OperationError('invalid_input', 'sourceTaskId is required with sourceSessionId'); - - const db = ctx.env.DATABASE; - if (input.assigneeUserId) { - const member = await db - .prepare( - `SELECT 1 AS ok FROM project_members - WHERE project_id = ? AND user_id = ? AND status = 'active'` - ) - .bind(input.projectId, input.assigneeUserId) - .first(); - if (!member) - throw new OperationError('invalid_input', 'The assignee is not an active project member'); - } - if (input.sourceTaskId) { - const task = await db - .prepare('SELECT chat_session_id FROM tasks WHERE id = ? AND project_id = ?') - .bind(input.sourceTaskId, input.projectId) - .first<{ chat_session_id: string | null }>(); - if (!task) - throw new OperationError('invalid_input', 'sourceTaskId is not a task of this project'); - // The chat must be the task's own (a task that handed its chat to a recovery successor has none). - if ( - input.sourceSessionId && - task.chat_session_id && - task.chat_session_id !== input.sourceSessionId - ) - throw new OperationError('invalid_input', 'sourceSessionId is not the chat of sourceTaskId'); - } - - const now = Date.now(); - const askId = ulid(); - // One statement: the per-chat cap and the insert cannot interleave with another filing. - const inserted = await db - .prepare( - `INSERT INTO asks (id, project_id, assignee_kind, assignee_user_id, kind, blocking, title, - body_md, answer_spec_json, steps_json, links_json, due_hint, due_at, source_session_id, - source_task_id, source_message_id, agent_profile_id, group_key, dedupe_key, status, - expires_at, source_workspace_id, category, next_escalation_at, max_expires_at, - created_at, updated_at) - SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?, ?, ?, ?, ? - WHERE ? IS NULL - OR (SELECT COUNT(*) FROM asks WHERE source_session_id = ? AND project_id = ? AND status = 'open') < ? - ON CONFLICT (project_id, dedupe_key) WHERE dedupe_key IS NOT NULL DO NOTHING` - ) - .bind( - askId, - input.projectId, - input.assigneeKind, - input.assigneeUserId ?? null, - input.kind, - input.blocking ? 1 : 0, - input.title, - input.body ?? null, - input.answerSpec ? JSON.stringify(input.answerSpec) : null, - input.steps.length ? JSON.stringify(input.steps) : null, - input.links.length ? JSON.stringify(input.links) : null, - input.dueHint ?? null, - input.dueAt ?? null, - input.sourceSessionId ?? null, - input.sourceTaskId ?? null, - input.sourceMessageId ?? null, - input.agentProfileId ?? null, - input.groupKey ?? null, - input.dedupeKey ?? null, - input.expiresAt ?? null, - input.sourceWorkspaceId ?? null, - input.category ?? null, - input.nextEscalationAt ?? null, - input.maxExpiresAt ?? null, - now, - now, - input.sourceSessionId ?? null, - input.sourceSessionId ?? null, - input.projectId, - limits.openItemsPerChat - ) - .run(); - if ((inserted.meta?.changes ?? 0) === 1) return { ref: `ask:${askId}`, id: askId, created: true }; - if (input.dedupeKey) { - const existing = await db - .prepare('SELECT id FROM asks WHERE project_id = ? AND dedupe_key = ?') - .bind(input.projectId, input.dedupeKey) - .first<{ id: string }>(); - if (existing) return { ref: `ask:${existing.id}`, id: existing.id, created: false }; - } - throw new OperationError( - 'rate_limited', - `This chat already has ${limits.openItemsPerChat} open inbox items` - ); -} - export interface InboxAnswerInput { projectId: string; ref: string; diff --git a/packages/operations/src/index.ts b/packages/operations/src/index.ts index 5e75edd5c0..96246d61c0 100644 --- a/packages/operations/src/index.ts +++ b/packages/operations/src/index.ts @@ -63,6 +63,7 @@ export { validateIdeaStatusTransition, } from './idea-transitions'; export { addIdeaUpdate, deleteIdeaUpdate, listIdeaUpdates } from './idea-update-core'; +export { createAsk, type CreateAskInput } from './inbox-ask-create-core'; export { getInboxItem, resolveInboxItem } from './inbox-item-core'; export { countInbox, listInbox } from './inbox-list-core'; export { @@ -86,8 +87,6 @@ export { INBOX_SETTINGS, type InboxSettingName } from './inbox-settings-definiti export { answerInboxItem, archiveInboxItem, - createAsk, - type CreateAskInput, type InboxAnswerInput, loadAskNoticeRow, notifyClosedAsk, diff --git a/packages/project-data/src/do/reconciliation-candidates.ts b/packages/project-data/src/do/reconciliation-candidates.ts index 8307b42113..d3ead3bdaf 100644 --- a/packages/project-data/src/do/reconciliation-candidates.ts +++ b/packages/project-data/src/do/reconciliation-candidates.ts @@ -161,13 +161,13 @@ async function resolveCandidateProjectId( `SELECT task_mode, status, project_id, workspace_id, chat_session_id, admission_state, EXISTS ( SELECT 1 FROM asks a - WHERE a.project_id = tasks.project_id AND a.source_session_id = ? + WHERE a.project_id = tasks.project_id AND a.source_session_id = ?2 AND a.kind = 'question' AND a.status = 'open' - AND (a.expires_at IS NULL OR a.expires_at > ?) + AND (a.expires_at IS NULL OR a.expires_at > ?3) ) AS open_question - FROM tasks WHERE id = ? LIMIT 1` + FROM tasks WHERE id = ?1 LIMIT 1` ) - .bind(sessionId, now, taskId) + .bind(taskId, sessionId, now) .first<{ task_mode: string | null; admission_state?: string | null; diff --git a/packages/project-data/tests/unit/attention.test.ts b/packages/project-data/tests/unit/attention.test.ts index ccbb3ba591..0448e40586 100644 --- a/packages/project-data/tests/unit/attention.test.ts +++ b/packages/project-data/tests/unit/attention.test.ts @@ -10,7 +10,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { completeAttentionAnswer, computeAttentionAlarmTime, - computeHumanInputExpiry, createAttentionMarker, getAttentionMarker, getAttentionSummary, @@ -662,34 +661,4 @@ describe('Attention Markers Module', () => { }); }); - describe('computeHumanInputExpiry', () => { - it('uses default 2-hour timeout when env is undefined', () => { - const before = Date.now(); - const expiry = computeHumanInputExpiry(undefined); - const after = Date.now(); - const twoHours = 2 * 60 * 60 * 1000; - - expect(expiry).toBeGreaterThanOrEqual(before + twoHours); - expect(expiry).toBeLessThanOrEqual(after + twoHours); - }); - - it('uses custom timeout from env var', () => { - const before = Date.now(); - const expiry = computeHumanInputExpiry('60000'); // 1 minute - const after = Date.now(); - - expect(expiry).toBeGreaterThanOrEqual(before + 60000); - expect(expiry).toBeLessThanOrEqual(after + 60000); - }); - - it('falls back to default on non-numeric env var', () => { - const before = Date.now(); - const expiry = computeHumanInputExpiry('not-a-number'); - const after = Date.now(); - const twoHours = 2 * 60 * 60 * 1000; - - expect(expiry).toBeGreaterThanOrEqual(before + twoHours); - expect(expiry).toBeLessThanOrEqual(after + twoHours); - }); - }); }); diff --git a/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md b/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md index def797b256..0bf3d95958 100644 --- a/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md +++ b/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md @@ -83,30 +83,65 @@ exist at deploy time stay answerable and archivable until they resolve or expire ## Implementation checklist -- [ ] Rule 44 inventory written below and in the PR -- [ ] Migration 0247 + drizzle columns -- [ ] Admin settings `inbox.questionTimeoutMinutes`, `inbox.questionFirstReminderPercent`, +- [x] Rule 44 inventory written below and in the PR +- [x] Migration 0247 + drizzle columns +- [x] Admin settings `inbox.questionTimeoutMinutes`, `inbox.questionFirstReminderPercent`, `inbox.questionSecondReminderPercent`, `inbox.questionUndeliveredGraceMinutes`, `inbox.questionMaxWaitMinutes` -- [ ] `createAsk` accepts question fields; `request_human_input` writes an ask, links notification -- [ ] Shared question answer operation (CAS + outcomes + durable delivery + notified_at) -- [ ] Inbox answer of a question goes through it; inbox archive of a question unchanged (asks) -- [ ] Attention GET/resolve adapters (ask first, marker fallback) -- [ ] Typed human message closes open question asks (both DO paths) -- [ ] Sweep: question reminders, undelivered-grace extension, expiry with task outcome -- [ ] Chat list overlay (index + DO fallback) and live-read ranking -- [ ] Connector pending attention merges question asks -- [ ] Stalled-task classifier reads asks -- [ ] Remove code that only served new needs_input question markers +- [x] `createAsk` accepts question fields; `request_human_input` writes an ask, links notification +- [x] Shared question answer operation (CAS + outcomes + durable delivery + notified_at) +- [x] Inbox answer of a question goes through it; inbox archive of a question unchanged (asks) +- [x] Attention GET/resolve adapters (ask first, marker fallback) +- [x] Typed human message closes open question asks (both DO paths) +- [x] Sweep: question reminders, undelivered-grace extension, expiry with task outcome +- [x] Chat list overlay (index + DO fallback) and live-read ranking +- [x] Connector pending attention merges question asks +- [x] Stalled-task classifier reads asks +- [x] Remove code that only served new needs_input question markers - [ ] Tests: capability (ask → sleep → answer via inbox → woken once; archive), concurrent answers, marker-era vs asks-era overlap, tenancy attack/owner pairs on real SQL (discriminating), expiry/reminder schedule, chat list overlay, Connector projection -- [ ] Docs: API reference / admin settings / any doc describing request_human_input storage -- [ ] Idea for removing marker-era question code after overlap +- [x] Docs: API reference / admin settings / any doc describing request_human_input storage +- [x] Idea for removing marker-era question code after overlap: `01M7HC7CN5WY6GEP9G0PP4DG7B` ## Rule 44 inventory -(filled in from the code inventory) +Every writer and reader of question markers (kind `needs_input`) and of +`session_summaries.attention_json`, and what it does after this slice. "Marker-era" = keeps +serving questions that existed as markers at deploy until they resolve (max 24 h by default); +removal tracked in the follow-up idea filed with this PR. + +### Writers + +| Path | Before | After | +| --- | --- | --- | +| `routes/mcp/human-input-tool.ts` (`request_human_input`) | `createAttentionMarker` + `linkAttentionNotification` | `fileQuestionAsk` → `createAsk` (asks row) + `linkQuestionNotification` (`asks.notification_id`); no marker | +| `ProjectData.createAttentionMarker` RPC (request_human_input branch: resolves check-ins) | ran for questions | branch removed; check-in resolution moved to `ProjectData.recordQuestionAsked` | +| `ProjectData.linkAttentionNotification` + client | question notification link | removed (no caller) | +| `answerAttention` (`routes/chat-attention.ts`; callers: resolve route, `ports.chat.answerAttention` → `sam_agent_answer`, inbox answer) | DO claim → live prompt → complete | ask first: `answerQuestionAsk` CAS + durable prompt + `notified_at`; marker-era fallback unchanged | +| `archiveAttention` (inbox port, `attention:` refs) | DO archive claim | marker-era only; asks archive via `archiveInboxItem` (`closeAsk` + notice) | +| `message-persistence.ts:resolveAttentionForRoles`, `durability-foundation.ts` (human message) | resolve all markers | unchanged for markers; also `closeQuestionAsksForHumanMessage` (asks → answered, notified) | +| `attention-expiry.ts` (DO alarm: expiry, escalation, undelivered grace, task outcome) | questions | marker-era only; asks: inbox sweep (`services/inbox/sweep.ts`) + `ProjectData.expireQuestionAsk` (reuses `failExpiredTaskMarker`) | +| `interaction-store-attention.ts` (permission mirrors), `reconciliation*.ts`, `idle-cleanup*.ts`, `wake-failure.ts`, `provider-limit-attention.ts` | own kinds/sources | unaffected (not questions) | +| `session-summary-sync.ts` (writes `attention_json`) | copies newest marker | unchanged; asks are never copied into it | + +### Readers + +| Reader | After | +| --- | --- | +| `GET …/attention/:id` (chat card, notification reader) | ask first (same response shape), marker fallback | +| Chat list D1 index (`services/session-summary-index.ts`) | one project read of open question asks merged into `attention`; live ranking counts chats with an open question | +| ProjectData `listSessions` / `getSessionsByTaskIds` / `getSession` (chat list fallback, team status `team-core.ts`, account map `routes/account-map.ts`) | `withQuestionAttention` merges open question asks | +| Web `useSessionReducer` live events | `attention.created` from `recordQuestionAsked`; `attention.resolved` from answer/archive delivery accept, typed message, expiry | +| Inbox list/count (`inbox-list-core.ts`) | asks part lists questions; attention part lists permission mirrors + marker-era questions | +| Connector `sam_chat_read` / `sam_chat_interactions` / `sam_work_changes` (`attention-core.ts`) | markers + open question asks, one projection | +| Connector `sam_chats_list` / `sam_projects_list` (`connector-read-core.ts`) | attention merged / count includes open question asks | +| Stalled-task classifier (`scheduled/stalled-task-classifier.ts`) | `hasOpenQuestionAsk` (D1) + marker check | +| Reconciliation candidates (check-in hold) | candidate deferred one lease while an open question ask exists (`resolveCandidateProjectId` D1 query) | +| Idea "question" status (`idea-work.ts`) | `mergeQuestionAsks` | +| Archive sharding (`archive-sharding.ts`) | unaffected: asks expire within `inbox.questionMaxWaitMinutes` (≤ 3 days) long before the 7-day archive grace | +| VM agent | no reference (verified) | +| `HUMAN_INPUT_TIMEOUT_MS` | removed (replaced by `inbox.questionTimeoutMinutes`); the other three `HUMAN_INPUT_*` remain for marker-era questions | ## Acceptance criteria From 8795e3c01765e15b38129f4238df6595d986712c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 05:37:07 +0000 Subject: [PATCH 04/13] fix(inbox): slice G review findings - check-in hold lasts until the question's deadline and is released when it closes (no lease-cadence alarms while a question is open); gate marker questionHold so a release never ends a claim lease or quarantine - typed-message close runs after the broadcast and alarm, only closes questions filed before the message - getSession no longer reads D1 (no consumer renders it; list reads do) - sweep steps get their own budget; throughput stated - same-answer replay retries an undelivered answer - request_human_input: empty context/options and validation errors are INVALID_PARAMS, not internal errors - partial index idx_asks_open_question; expiry predicate in the ranking EXISTS and the Connector projection; shared chat-writer check - HUMAN_INPUT_TIMEOUT_MS retired in the deploy-script binding test - tests: real-SQL hold, shared reads in every mode, conjunct-isolating and forged-snapshot attacks, Connector lists, idea merge, real-DO typed close, check-in resolution, expiry outcome, authz through real routes Co-Authored-By: Claude Opus 5.5 --- .../src/db/migrations/0247_asks_questions.sql | 6 +- apps/api/src/routes/chat-attention.ts | 37 +-- apps/api/src/routes/mcp/human-input-tool.ts | 28 ++- apps/api/src/services/inbox/question-asks.ts | 18 +- apps/api/src/services/inbox/sweep.ts | 25 +- .../api/src/services/session-summary-index.ts | 16 +- .../durable-objects/reconciliation.test.ts | 119 +++++++--- .../operations/connector-operations.test.ts | 37 +++ .../operations/operational-operations.test.ts | 2 +- .../inbox/open-question-reads.test.ts | 222 ++++++++++++++++++ .../unit/services/inbox/question-asks.test.ts | 71 +++++- .../tests/workers/inbox-capability.test.ts | 210 ++++++++++++++++- .../docs/docs/guides/admin-settings.md | 22 +- packages/operations/src/attention-core.ts | 3 +- packages/operations/src/inbox-list-core.ts | 12 +- .../src/inbox-settings-definition.ts | 2 +- .../src/do/durability-foundation.ts | 34 +-- packages/project-data/src/do/index.ts | 22 +- .../src/do/message-persistence.ts | 17 +- packages/project-data/src/do/question-asks.ts | 5 +- .../src/do/reconciliation-candidate-state.ts | 20 +- .../src/do/reconciliation-candidates.ts | 32 ++- .../unit/idea-work-question-asks.test.ts | 76 ++++++ packages/shared/src/types/inbox.ts | 6 +- packages/worker-core/src/schema.ts | 3 + scripts/quality/sync-wrangler-config.test.ts | 4 + 26 files changed, 907 insertions(+), 142 deletions(-) create mode 100644 apps/api/tests/unit/services/inbox/open-question-reads.test.ts create mode 100644 packages/project-data/tests/unit/idea-work-question-asks.test.ts diff --git a/apps/api/src/db/migrations/0247_asks_questions.sql b/apps/api/src/db/migrations/0247_asks_questions.sql index fe2509b046..884df6292c 100644 --- a/apps/api/src/db/migrations/0247_asks_questions.sql +++ b/apps/api/src/db/migrations/0247_asks_questions.sql @@ -10,7 +10,7 @@ -- escalation_count reminders sent -- max_expires_at hard limit for extending an ask whose push was never delivered -- --- Additive only: nullable columns, one integer column with a default, one partial index. +-- Additive only: nullable columns, one integer column with a default, two partial indexes. -- Existing rows (reviews, tasks, errors filed since slice A) keep NULL / 0 and are unaffected: -- the reminder sweep selects only rows with next_escalation_at set. ALTER TABLE asks ADD COLUMN source_workspace_id TEXT; @@ -23,3 +23,7 @@ ALTER TABLE asks ADD COLUMN max_expires_at INTEGER; -- Due reminders. CREATE INDEX idx_asks_open_escalation ON asks (next_escalation_at) WHERE status = 'open' AND next_escalation_at IS NOT NULL; +-- Open questions per project and chat: the chat list, the check-in hold and the stall guard +-- read only these rows (`packages/worker-core/src/question-asks.ts`). +CREATE INDEX idx_asks_open_question ON asks (project_id, source_session_id, created_at) + WHERE kind = 'question' AND status = 'open'; diff --git a/apps/api/src/routes/chat-attention.ts b/apps/api/src/routes/chat-attention.ts index d5a094a294..86f941fbb1 100644 --- a/apps/api/src/routes/chat-attention.ts +++ b/apps/api/src/routes/chat-attention.ts @@ -51,6 +51,27 @@ function parseAttentionCategory(metadata: string | null): HumanInputCategory | n } } +/** + * Whether the viewer may answer the agent in this chat: the owner, or an active grantee whose + * owner can still write, holding `task:write` themselves. One rule for a question held as a + * marker and one held in `asks`. + */ +async function isChatWriter( + db: ReturnType>, + projectId: string, + role: string, + access: { role?: string | null; ownerUserId?: string | null; grant?: unknown } +): Promise { + return ( + Boolean(access.ownerUserId) && + projectRoleHasCapability(role, 'task:write') && + (access.role === 'owner' || + (access.role === 'grantee' && + Boolean(access.grant) && + (await hasProjectCapability(db, projectId, access.ownerUserId ?? '', 'task:write')))) + ); +} + /** * One attention marker with what this viewer may do with it. Shared by the attention read below * and the inbox (`services/inbox/port.ts`), so both answer "can this person answer?" the same way. @@ -71,13 +92,7 @@ export async function loadAttentionForViewer( markerId, userId ); - const writer = - Boolean(access.ownerUserId) && - projectRoleHasCapability(membership.role, 'task:write') && - (access.role === 'owner' || - (access.role === 'grantee' && - Boolean(access.grant) && - (await hasProjectCapability(db, projectId, access.ownerUserId ?? '', 'task:write')))); + const writer = await isChatWriter(db, projectId, membership.role, access); return { canRead: Boolean(session) && access.found && projectRoleHasCapability(membership.role, 'task:read'), @@ -108,13 +123,7 @@ async function questionAskAttentionResponse( ); if (!session || !access.found || !projectRoleHasCapability(role, 'task:read')) throw errors.notFound('Chat session'); - const writer = - Boolean(access.ownerUserId) && - projectRoleHasCapability(role, 'task:write') && - (access.role === 'owner' || - (access.role === 'grantee' && - Boolean(access.grant) && - (await hasProjectCapability(db, ask.projectId, access.ownerUserId ?? '', 'task:write')))); + const writer = await isChatWriter(db, ask.projectId, role, access); const now = Date.now(); const state = questionAskRequestState(ask, now); const context = diff --git a/apps/api/src/routes/mcp/human-input-tool.ts b/apps/api/src/routes/mcp/human-input-tool.ts index 071fc3d492..2a614c4ca3 100644 --- a/apps/api/src/routes/mcp/human-input-tool.ts +++ b/apps/api/src/routes/mcp/human-input-tool.ts @@ -49,7 +49,14 @@ export async function handleRequestHumanInput( } // Sanitize context: strip null bytes, Unicode bidi overrides, and C0/C1 control chars (except \n, \t) - const sanitizedContext = sanitizeUserInput(context.trim()); + const sanitizedContext = sanitizeUserInput(context.trim()).trim(); + if (!sanitizedContext) { + return jsonRpcError( + requestId, + INVALID_PARAMS, + 'context is required and must be a non-empty string' + ); + } // Validate category if provided let category: HumanInputCategory | null = null; @@ -78,7 +85,9 @@ export async function handleRequestHumanInput( } options = (params.options as string[]) .slice(0, MAX_HUMAN_INPUT_OPTIONS_COUNT) - .map((o) => sanitizeUserInput(o).slice(0, MAX_HUMAN_INPUT_OPTION_LENGTH)); + .map((o) => sanitizeUserInput(o).trim().slice(0, MAX_HUMAN_INPUT_OPTION_LENGTH)) + // An option that is empty once cleaned cannot be picked; leave it out. + .filter((o) => o.length > 0); if (options.length === 0) options = null; } @@ -142,14 +151,17 @@ export async function handleRequestHumanInput( error: err instanceof Error ? err.message : String(err), }); // The per-chat cap and length limits are the inbox's; say which one the agent hit. - const limitHit = - err instanceof OperationError && ['rate_limited', 'invalid_input'].includes(err.code); + if (err instanceof OperationError && ['rate_limited', 'invalid_input'].includes(err.code)) { + return jsonRpcError(requestId, INVALID_PARAMS, err.message); + } + // A shape the inbox refuses: the agent can fix its call (the details stay in the log). + if (err instanceof Error && err.name === 'ValiError') { + return jsonRpcError(requestId, INVALID_PARAMS, 'Human input request is not valid'); + } return jsonRpcError( requestId, - limitHit ? INVALID_PARAMS : INTERNAL_ERROR, - limitHit && err instanceof Error - ? err.message - : 'Human input request could not be recorded safely' + INTERNAL_ERROR, + 'Human input request could not be recorded safely' ); } diff --git a/apps/api/src/services/inbox/question-asks.ts b/apps/api/src/services/inbox/question-asks.ts index 511c6c805a..9d59f70f57 100644 --- a/apps/api/src/services/inbox/question-asks.ts +++ b/apps/api/src/services/inbox/question-asks.ts @@ -156,6 +156,13 @@ export async function answerQuestionAsk( } ): Promise { const { ask, answer, userId } = input; + if (ask.status === 'answered' && ask.answer === answer && ask.notifiedAt === null) { + // The same answer again while it has not reached the agent: try the delivery again (the same + // delivery id, so a delivery that did land is not repeated). The person can always unstick it. + return (await deliverAnswer(env, ask)) + ? { resolved: true, alreadyResolved: false, answer } + : { resolved: false, alreadyResolved: false, inFlight: true, answer }; + } if (ask.status !== 'open') return settledOutcome(ask, answer); const now = Date.now(); if (ask.expiresAt !== null && ask.expiresAt <= now) { @@ -193,9 +200,7 @@ export async function answerQuestionAsk( return settledOutcome(current, answer); } - const deps = { env, ports: createOperationPorts(env) }; - const row = await loadAskNoticeRow(deps, ask.projectId, ask.id); - const queued = row ? await notifyClosedAsk(deps, row, 'answered') : false; + const queued = await deliverAnswer(env, ask); // A teammate's answer is recorded on the shared-answer audit event, as for a marker. await recordSharedSessionAnswer(env, input.authorization.writer, { markerId: ask.id, @@ -206,6 +211,13 @@ export async function answerQuestionAsk( : { resolved: false, alreadyResolved: false, inFlight: true, answer }; } +/** Queue the answer to the agent and record `notified_at`; false when it was not queued. */ +async function deliverAnswer(env: Env, ask: QuestionAsk): Promise { + const deps = { env, ports: createOperationPorts(env) }; + const row = await loadAskNoticeRow(deps, ask.projectId, ask.id); + return row ? notifyClosedAsk(deps, row, 'answered') : false; +} + /** `request.resolvedAt` / `resolvedAnswer` as the chat card read them from a marker. */ export function questionAskRequestState(ask: QuestionAsk, now: number) { // An answer that has not reached the agent yet is in flight: a marker showed it as a staged diff --git a/apps/api/src/services/inbox/sweep.ts b/apps/api/src/services/inbox/sweep.ts index cbfc2f8de2..0353e2ab9d 100644 --- a/apps/api/src/services/inbox/sweep.ts +++ b/apps/api/src/services/inbox/sweep.ts @@ -8,8 +8,10 @@ * 2. retry notices that were not queued (`notified_at IS NULL` on a closed ask) for * `inbox.noticeRetryMinutes` after the item closed, the way the secret request sweep retries * `runtime_secret_requests.notified_at`. - * The steps share one budget of `inbox.sweepBatchSize` rows, so a tick is bounded (rule 47); - * every selected row leaves the candidate set: a reminder advances `next_escalation_at`, an + * Each step reads at most `inbox.sweepBatchSize` rows, so a tick is bounded (rule 47) and one step + * cannot starve another. At the default 10 each step drains 120 rows an hour: a question needs one + * row per reminder and one to expire, so a burst of 100 questions expiring together drains in + * about 50 minutes (raise the setting, up to 50, for more). Every selected row leaves the candidate set: a reminder advances `next_escalation_at`, an * extension moves `expires_at`, an expiry closes the row, a notice past its window ages out. * The schedule has the ProjectData marker alarm's precision of one sweep tick (five minutes). */ @@ -199,17 +201,13 @@ async function extendUndeliveredQuestion( export async function runInboxAskSweep(env: Env, now = Date.now()): Promise { const deps = { env, ports: createOperationPorts(env) }; const limits = await getInboxLimits(deps); - let budget = limits.sweepBatchSize; + // Each step has its own budget, so due reminders can never starve expiries or notice retries. + const budget = limits.sweepBatchSize; let expired = 0; let noticesRetried = 0; let extended = 0; const reminders = await sendDueQuestionReminders(env, limits, now, budget); - budget -= reminders.selected; - if (budget <= 0) { - log.info('inbox_ask.sweep', { expired, noticesRetried, remindersSent: reminders.sent }); - return { expired, noticesRetried, remindersSent: reminders.sent, extended }; - } const due = await env.DATABASE.prepare( `SELECT ${SCHEDULE_COLUMNS} FROM asks @@ -250,9 +248,7 @@ export async function runInboxAskSweep(env: Env, now = Date.now()): Promise 0) { + { const unnotified = await env.DATABASE.prepare( `SELECT ${NOTICE_COLUMNS} FROM asks WHERE notified_at IS NULL AND status IN ('answered', 'done', 'archived', 'expired') @@ -271,7 +267,12 @@ export async function runInboxAskSweep(env: Env, now = Date.now()): Promise 0 || noticesRetried > 0 || reminders.sent > 0 || extended > 0) { - log.info('inbox_ask.sweep', { expired, noticesRetried, remindersSent: reminders.sent, extended }); + log.info('inbox_ask.sweep', { + expired, + noticesRetried, + remindersSent: reminders.sent, + extended, + }); } return { expired, noticesRetried, remindersSent: reminders.sent, extended }; } diff --git a/apps/api/src/services/session-summary-index.ts b/apps/api/src/services/session-summary-index.ts index 4492113159..1e48af70d6 100644 --- a/apps/api/src/services/session-summary-index.ts +++ b/apps/api/src/services/session-summary-index.ts @@ -284,7 +284,8 @@ async function readIndex( WHERE status_rank <= ? ${recency}` ) - .bind(...params, ...LIVE_SESSION_STATUSES, query.limit) + // The first bind is the open-question expiry clock (`OPEN_QUESTION_EXISTS`). + .bind(Date.now(), ...params, ...LIVE_SESSION_STATUSES, query.limit) .all>(); } catch (err) { log.warn('session_index.live_read_failed', { @@ -337,13 +338,14 @@ async function readIndex( } /** - * A chat holds an open question in D1 `asks` (inbox slice G). Correlated on the row being ranked; - * `idx_asks_session_status` answers it. + * A chat holds an open, unexpired question in D1 `asks` (inbox slice G). Correlated on the row + * being ranked; `idx_asks_open_question` answers it. */ const OPEN_QUESTION_EXISTS = `EXISTS ( SELECT 1 FROM asks a - WHERE a.source_session_id = session_summaries.id AND a.project_id = session_summaries.project_id - AND a.kind = 'question' AND a.status = 'open')`; + WHERE a.project_id = session_summaries.project_id AND a.source_session_id = session_summaries.id + AND a.kind = 'question' AND a.status = 'open' + AND (a.expires_at IS NULL OR a.expires_at > ?))`; /** Each chat's attention with its open question merged in, as the ProjectData read does. */ function withQuestionAttention( @@ -353,7 +355,9 @@ function withQuestionAttention( if (questions.size === 0) return sessions; return sessions.map((session) => { const question = typeof session.id === 'string' ? questions.get(session.id) : undefined; - return question ? { ...session, attention: preferAttention(session.attention, question) } : session; + return question + ? { ...session, attention: preferAttention(session.attention, question) } + : session; }); } diff --git a/apps/api/tests/unit/durable-objects/reconciliation.test.ts b/apps/api/tests/unit/durable-objects/reconciliation.test.ts index 3a48690396..184c1ae7a8 100644 --- a/apps/api/tests/unit/durable-objects/reconciliation.test.ts +++ b/apps/api/tests/unit/durable-objects/reconciliation.test.ts @@ -17,9 +17,12 @@ import { getReconciliationCandidates, processReconciliationCandidates, } from '@simple-agent-manager/project-data/internal/do/reconciliation'; +import { releaseQuestionHold } from '@simple-agent-manager/project-data/internal/do/reconciliation-candidate-state'; +import * as workerSchema from '@simple-agent-manager/worker-core/schema'; import Database from 'better-sqlite3'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; import { acceptedPromptResponse, missingPromptReceipt, @@ -69,8 +72,6 @@ interface MockTaskRow { completed_at?: string | null; execution_step?: string | null; terminal_transition_id?: string | null; - /** The candidate query's open-question probe over D1 `asks` (inbox slice G). */ - open_question?: number; } interface MockWorkspaceRow { @@ -627,37 +628,91 @@ describe('Task Reconciliation Module', () => { expect(candidates).toHaveLength(0); }); - it('holds the check-in one lease while the chat has an open question in D1 asks', async () => { - setupTaskSession(); - const env = envWithRows({ - 'task-1': { task_mode: 'task', status: 'in_progress', open_question: 1 }, + // Inbox slice G: an open question in D1 `asks` holds SAM's check-in, on a real SQL engine. + describe('the open-question hold (D1 asks, real SQL)', () => { + let d1: Database.Database; + function questionEnv(): ProjectDataEnv { + return { DATABASE: createSqliteD1(d1) } as unknown as ProjectDataEnv; + } + function seedTask() { + d1.prepare( + `INSERT INTO tasks (id, project_id, user_id, title, status, task_mode, workspace_id, + chat_session_id, created_at, updated_at) + VALUES ('task-1', 'project-1', 'user-1', 't', 'in_progress', 'task', 'ws-1', 'session-1', + datetime('now'), datetime('now'))` + ).run(); + } + function seedAsk( + id: string, + overrides: { + projectId?: string; + sessionId?: string; + status?: string; + expiresAt?: number; + } = {} + ) { + d1.prepare( + `INSERT INTO asks (id, project_id, assignee_kind, assignee_user_id, kind, blocking, title, + source_session_id, status, expires_at, created_at, updated_at) + VALUES (?, ?, 'user', 'user-1', 'question', 1, 'q', ?, ?, ?, 1, 1)` + ).run( + id, + overrides.projectId ?? 'project-1', + overrides.sessionId ?? 'session-1', + overrides.status ?? 'open', + overrides.expiresAt ?? Date.now() + 2 * 60 * 60_000 + ); + } + function gate() { + const row = db + .prepare(`SELECT value FROM do_meta WHERE key = 'taskReconciliationGate:session-1'`) + .get() as { value: string } | undefined; + return row ? (JSON.parse(row.value) as Record) : null; + } + + beforeEach(() => { + d1 = new Database(':memory:'); + createSchemaTables(d1, [workerSchema.tasks, workerSchema.asks]); + seedTask(); + }); + + it('holds the chat until the question’s deadline, so the alarm does not poll', async () => { + setupTaskSession(); + const deadline = Date.now() + 2 * 60 * 60_000; + seedAsk('q-1', { expiresAt: deadline }); + await expect(getReconciliationCandidates(sql, questionEnv())).resolves.toEqual([]); + expect(gate()).toMatchObject({ attempts: 0, nextAttemptAt: deadline, questionHold: true }); + // The alarm waits for the deadline instead of re-arming at the lease cadence. + expect(computeReconciliationAlarmTime(sql, questionEnv())).toBeGreaterThanOrEqual(deadline); + // Answering releases it: the chat is a candidate again at once. + expect(releaseQuestionHold(sql, 'session-1')).toBe(true); + d1.prepare(`UPDATE asks SET status = 'answered' WHERE id = 'q-1'`).run(); + await expect(getReconciliationCandidates(sql, questionEnv())).resolves.toEqual([ + expect.objectContaining({ sessionId: 'session-1' }), + ]); + }); + + it.each([ + ['answered', { status: 'answered' }], + ['expired', { expiresAt: Date.now() - 1 }], + ['in another project', { projectId: 'project-2' }], + ['in another chat', { sessionId: 'session-2' }], + ])('does not hold for a question that is %s (control)', async (_label, overrides) => { + setupTaskSession(); + seedAsk('q-1', overrides); + await expect(getReconciliationCandidates(sql, questionEnv())).resolves.toEqual([ + expect.objectContaining({ sessionId: 'session-1' }), + ]); + }); + + it('a release never ends a claim lease or another deferral', () => { + setupTaskSession(); + db.prepare( + `INSERT INTO do_meta (key, value) VALUES ('taskReconciliationGate:session-1', ?)` + ).run(JSON.stringify({ attempts: 2, nextAttemptAt: Date.now() + 60_000 })); + expect(releaseQuestionHold(sql, 'session-1')).toBe(false); + expect(gate()).toMatchObject({ attempts: 2 }); }); - await expect(getReconciliationCandidates(sql, env)).resolves.toEqual([]); - const gate = JSON.parse( - String( - db - .prepare(`SELECT value FROM do_meta WHERE key = 'taskReconciliationGate:session-1'`) - .get()?.value - ) - ) as { attempts: number; nextAttemptAt: number }; - // Deferred, without spending a probe attempt. - expect(gate.attempts).toBe(0); - expect(gate.nextAttemptAt).toBeGreaterThan(Date.now()); - // The query that decided it carries the session and the time. - const query = vi - .mocked(env.DATABASE.prepare) - .mock.calls.find(([sql]) => String(sql).includes('open_question')); - expect(String(query?.[0])).toContain("a.kind = 'question' AND a.status = 'open'"); - }); - - it('control: without an open question the same session is a candidate', async () => { - setupTaskSession(); - await expect( - getReconciliationCandidates( - sql, - envWithRows({ 'task-1': { task_mode: 'task', status: 'in_progress', open_question: 0 } }) - ) - ).resolves.toEqual([expect.objectContaining({ sessionId: 'session-1' })]); }); it('excludes sessions with active needs_input marker', async () => { diff --git a/apps/api/tests/unit/operations/connector-operations.test.ts b/apps/api/tests/unit/operations/connector-operations.test.ts index a08b2d05dc..aa46760171 100644 --- a/apps/api/tests/unit/operations/connector-operations.test.ts +++ b/apps/api/tests/unit/operations/connector-operations.test.ts @@ -239,6 +239,43 @@ describe('connector operations current membership and creator authority', () => expect((await samChatsList.run(ctx('unknown'), {})).chats).toEqual([]); expect((await samChatsList.run(ctx('colleague'), {})).chats[0]?.attention).toBeNull(); }); + it('chats and project counts show questions held in D1 asks (slice G) to the chat creator only', async () => { + const future = Date.now() + 3_600_000; + sqlite.exec(` + INSERT INTO session_summaries (id,project_id,created_by_user_id,updated_at) + VALUES ('asking','project','owner',40); + INSERT INTO asks (id,project_id,assignee_kind,assignee_user_id,kind,blocking,title,body_md, + source_session_id,status,expires_at,created_at,updated_at) + VALUES ('ask-1','project','user','owner','question',1,'Pick','Pick a region.','asking','open',${future},35,35); + -- Attack: the same chat id under another project must not reach it. + INSERT INTO asks (id,project_id,assignee_kind,assignee_user_id,kind,blocking,title,body_md, + source_session_id,status,expires_at,created_at,updated_at) + VALUES ('ask-foreign','secret','user','owner','question',1,'Foreign','Foreign.','chat','open',${future},99,99); + `); + const chats = Object.fromEntries( + (await samChatsList.run(ctx(), {})).chats.map((chat) => [chat.id, chat]) + ); + expect(chats.asking?.attention).toMatchObject({ + markerId: 'ask-1', + kind: 'needs_input', + reason: 'Pick a region.', + }); + // The marker question in 'chat' stays; the foreign ask is not merged into it. + expect(chats.chat?.attention).toMatchObject({ markerId: 'm-chat' }); + // Another member sees no attention on the owner's chat. + const colleague = Object.fromEntries( + (await samChatsList.run(ctx('colleague'), {})).chats.map((chat) => [chat.id, chat]) + ); + expect(colleague.asking?.attention).toBeNull(); + // The project count includes the chat waiting on an asks question (control: closed → not). + const count = async () => + (await samProjectsList.run(ctx(), {})).projects.find((p) => p.id === 'project') + ?.needsAttention; + expect(await count()).toBe(2); + sqlite.prepare("UPDATE asks SET status = 'answered' WHERE id = 'ask-1'").run(); + expect(await count()).toBe(1); + }); + it('chats carry their task state beside the lifecycle label, flagging a stale active label', async () => { sqlite.exec(` INSERT INTO tasks (id,project_id,user_id,title,status,execution_step,parent_task_id,updated_at) diff --git a/apps/api/tests/unit/operations/operational-operations.test.ts b/apps/api/tests/unit/operations/operational-operations.test.ts index 8d7c44b374..3bdd149827 100644 --- a/apps/api/tests/unit/operations/operational-operations.test.ts +++ b/apps/api/tests/unit/operations/operational-operations.test.ts @@ -398,7 +398,7 @@ describe('operational MCP evidence with real SQLite authorization and persistenc created_at, updated_at) VALUES (?, ?, 'user', 'owner', 'question', 1, 'Pick a region', 'Pick a region for the deploy.', '{"type":"options","options":["eu","us"],"allowText":false}', 'decision', ?, 'task', - 'open', 9000, 20000, 1, 6000, 'n-ask', ?, ?)` + 'open', 4102444800000, 4102444800000, 1, 6000, 'n-ask', ?, ?)` ) .run(id, projectId, sessionId, createdAt, createdAt); insertAsk('ask-1', 'p', 'chat', 3_000); diff --git a/apps/api/tests/unit/services/inbox/open-question-reads.test.ts b/apps/api/tests/unit/services/inbox/open-question-reads.test.ts new file mode 100644 index 0000000000..3752a5639e --- /dev/null +++ b/apps/api/tests/unit/services/inbox/open-question-reads.test.ts @@ -0,0 +1,222 @@ +/** + * The shared reads of open questions held in D1 `asks` (inbox slice G, + * `packages/worker-core/src/question-asks.ts`) on a real SQL engine (`.claude/rules/28`): every + * mode is bound to its project, each attack case has an owner control, and one unreadable row + * never hides the others (`.claude/rules/50`). + */ +import { + hasOpenQuestionAsk, + preferAttention, + readOpenQuestionAttention, +} from '@simple-agent-manager/worker-core'; +import * as schema from '@simple-agent-manager/worker-core/schema'; +import Database from 'better-sqlite3'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { createSchemaTables, createSqliteD1 } from '../../../helpers/sqlite-d1'; + +const NOW = 1_800_000_000_000; +let sqlite: Database.Database; +let db: D1Database; + +function ask( + id: string, + overrides: Partial<{ + project: string; + session: string | null; + task: string | null; + assignee: string; + status: string; + kind: string; + expiresAt: number | null; + createdAt: number; + spec: string | null; + }> = {} +) { + sqlite + .prepare( + `INSERT INTO asks (id, project_id, assignee_kind, assignee_user_id, kind, blocking, title, + body_md, answer_spec_json, category, source_session_id, source_task_id, status, + expires_at, created_at, updated_at) + VALUES (?, ?, 'user', ?, ?, 1, 'Pick', 'Pick a region.', ?, 'decision', ?, ?, ?, ?, ?, ?)` + ) + .run( + id, + overrides.project ?? 'p1', + overrides.assignee ?? 'owner', + overrides.kind ?? 'question', + overrides.spec === undefined + ? '{"type":"options","options":["eu","us"],"allowText":false}' + : overrides.spec, + overrides.session === undefined ? 'chat-1' : overrides.session, + overrides.task === undefined ? 'task-1' : overrides.task, + overrides.status ?? 'open', + overrides.expiresAt === undefined ? NOW + 60_000 : overrides.expiresAt, + overrides.createdAt ?? 1_000, + overrides.createdAt ?? 1_000 + ); +} + +beforeEach(() => { + sqlite = new Database(':memory:'); + createSchemaTables(sqlite, [schema.asks]); + db = createSqliteD1(sqlite) as unknown as D1Database; +}); + +describe('readOpenQuestionAttention', () => { + it('returns each chat’s newest open question as an attention summary', async () => { + ask('old', { createdAt: 1_000 }); + ask('new', { createdAt: 2_000 }); + const result = await readOpenQuestionAttention(db, { projectId: 'p1', now: NOW }); + expect([...result.keys()]).toEqual(['chat-1']); + expect(result.get('chat-1')).toEqual({ + markerId: 'new', + kind: 'needs_input', + source: 'request_human_input', + createdAt: 2_000, + expiresAt: NOW + 60_000, + reason: 'Pick a region.', + options: ['eu', 'us'], + category: 'decision', + interactionId: null, + interactionKind: null, + }); + }); + + it('leaves out closed, expired and non-question asks (controls)', async () => { + ask('answered', { status: 'answered' }); + ask('expired', { expiresAt: NOW - 1, session: 'chat-2' }); + ask('review', { kind: 'review', session: 'chat-3' }); + ask('open', { session: 'chat-4' }); + const result = await readOpenQuestionAttention(db, { projectId: 'p1', now: NOW }); + expect([...result.keys()]).toEqual(['chat-4']); + }); + + it('project mode: another project’s question with the same chat id is not read (attack + owner control)', async () => { + ask('foreign', { project: 'p2' }); + expect((await readOpenQuestionAttention(db, { projectId: 'p1', now: NOW })).size).toBe(0); + ask('mine'); + expect( + (await readOpenQuestionAttention(db, { projectId: 'p1', now: NOW })).get('chat-1') + ).toMatchObject({ markerId: 'mine' }); + }); + + it('chat mode reads only the named chats of the project', async () => { + ask('a', { session: 'chat-1' }); + ask('b', { session: 'chat-2' }); + ask('foreign', { project: 'p2', session: 'chat-3' }); + const result = await readOpenQuestionAttention(db, { + projectId: 'p1', + sessionIds: ['chat-2', 'chat-3'], + now: NOW, + }); + expect([...result.keys()]).toEqual(['chat-2']); + expect( + (await readOpenQuestionAttention(db, { projectId: 'p1', sessionIds: [], now: NOW })).size + ).toBe(0); + }); + + it('cross-project mode binds each chat to its own project (attack + owner control)', async () => { + ask('p1-chat-1', { project: 'p1', session: 'chat-1' }); + ask('p2-chat-2', { project: 'p2', session: 'chat-2' }); + // Attack: the pairs swap projects; neither question may be read. + const swapped = await readOpenQuestionAttention(db, { + chats: [ + { projectId: 'p2', sessionId: 'chat-1' }, + { projectId: 'p1', sessionId: 'chat-2' }, + ], + now: NOW, + }); + expect(swapped.size).toBe(0); + const owned = await readOpenQuestionAttention(db, { + chats: [ + { projectId: 'p1', sessionId: 'chat-1' }, + { projectId: 'p2', sessionId: 'chat-2' }, + ], + now: NOW, + }); + expect([...owned.keys()].sort()).toEqual(['chat-1', 'chat-2']); + }); + + it('assignee filter: another person’s question is not read', async () => { + ask('theirs', { assignee: 'colleague' }); + expect( + (await readOpenQuestionAttention(db, { projectId: 'p1', assigneeUserId: 'owner', now: NOW })) + .size + ).toBe(0); + expect( + ( + await readOpenQuestionAttention(db, { + projectId: 'p1', + assigneeUserId: 'colleague', + now: NOW, + }) + ).size + ).toBe(1); + }); + + it('a malformed answer spec yields no options instead of hiding the question (rule 50)', async () => { + ask('bad-spec', { spec: 'not json', session: 'chat-1' }); + ask('good', { session: 'chat-2' }); + const result = await readOpenQuestionAttention(db, { projectId: 'p1', now: NOW }); + expect(result.get('chat-1')).toMatchObject({ markerId: 'bad-spec', options: [] }); + expect(result.get('chat-2')).toMatchObject({ markerId: 'good' }); + }); + + it('a failed read degrades to no questions instead of failing the caller', async () => { + sqlite.exec('DROP TABLE asks'); + await expect(readOpenQuestionAttention(db, { projectId: 'p1', now: NOW })).resolves.toEqual( + new Map() + ); + }); +}); + +describe('hasOpenQuestionAsk (the stalled-task guard)', () => { + const probe = ( + overrides: Partial<{ projectId: string; sessionId: string; taskId: string }> = {} + ) => + hasOpenQuestionAsk(db, { + projectId: 'p1', + sessionId: 'chat-1', + taskId: 'task-1', + now: NOW, + ...overrides, + }); + + it('sees an open question of this chat and task', async () => { + ask('q'); + await expect(probe()).resolves.toBe(true); + }); + + it.each([ + ['another project', { projectId: 'p2' }], + ['another chat', { sessionId: 'chat-2' }], + ['another task of the chat', { taskId: 'task-2' }], + ])('does not see it from %s', async (_label, overrides) => { + ask('q'); + await expect(probe(overrides)).resolves.toBe(false); + }); +}); + +describe('preferAttention', () => { + const question = { + markerId: 'ask', + kind: 'needs_input' as const, + source: 'request_human_input' as const, + createdAt: 2_000, + expiresAt: null, + reason: 'q', + options: [], + category: null, + interactionId: null, + interactionKind: null, + }; + it('a newer marker question wins; an older one, or any other marker, does not', () => { + expect(preferAttention({ kind: 'needs_input', createdAt: 3_000 }, question)).toMatchObject({ + createdAt: 3_000, + }); + expect(preferAttention({ kind: 'needs_input', createdAt: 1_000 }, question)).toBe(question); + expect(preferAttention({ kind: 'wake_failed', createdAt: 9_000 }, question)).toBe(question); + expect(preferAttention(null, undefined)).toBeNull(); + }); +}); diff --git a/apps/api/tests/unit/services/inbox/question-asks.test.ts b/apps/api/tests/unit/services/inbox/question-asks.test.ts index c5a0c57960..9413a3ca07 100644 --- a/apps/api/tests/unit/services/inbox/question-asks.test.ts +++ b/apps/api/tests/unit/services/inbox/question-asks.test.ts @@ -56,8 +56,10 @@ import type { Env } from '../../../../src/env'; import { createOperationPorts } from '../../../../src/operation-ports'; import { answerAttention, registerChatAttentionRoute } from '../../../../src/routes/chat-attention'; import { + answerQuestionAsk, fileQuestionAsk, linkQuestionNotification, + loadQuestionAsk, } from '../../../../src/services/inbox/question-asks'; import { runInboxAskSweep } from '../../../../src/services/inbox/sweep'; import { @@ -282,7 +284,9 @@ describe('answering a question', () => { it('reports an answer whose delivery was not queued as still being delivered; the sweep delivers it', async () => { const { id } = await question(); - edges.acceptPromptDelivery.mockRejectedValueOnce(new Error('DO unavailable')); + edges.acceptPromptDelivery + .mockRejectedValueOnce(new Error('DO unavailable')) + .mockRejectedValueOnce(new Error('DO unavailable')); await expect(answer(id, 'eu')).resolves.toEqual({ resolved: false, alreadyResolved: false, @@ -290,8 +294,9 @@ describe('answering a question', () => { answer: 'eu', }); expect(askRow(id)).toMatchObject({ status: 'answered', notified_at: null }); - // The same answer again is still in flight; a different one conflicts with it. + // The same answer again retries the delivery; still failing, it is still in flight. await expect(answer(id, 'eu')).resolves.toMatchObject({ inFlight: true }); + // A different one conflicts with it. await expect(answer(id, 'us')).rejects.toMatchObject({ statusCode: 409, message: 'A different answer is already being delivered', @@ -299,6 +304,24 @@ describe('answering a question', () => { // The sweep retries the notice once it is past the inline grace. await runInboxAskSweep(env, Number(askRow(id).resolved_at) + 2 * MINUTE); expect(askRow(id).notified_at).not.toBeNull(); + expect(edges.acceptPromptDelivery).toHaveBeenCalledTimes(3); + // Every attempt used one delivery id, so a delivery that did land is not repeated. + expect( + new Set(edges.acceptPromptDelivery.mock.calls.map((call) => call[2].deliveryId)) + ).toEqual(new Set([`inbox-ask:${id}`])); + }); + + it('the person can unstick an answer that was not delivered by sending it again', async () => { + const { id } = await question(); + edges.acceptPromptDelivery.mockRejectedValueOnce(new Error('DO unavailable')); + await expect(answer(id, 'eu')).resolves.toMatchObject({ inFlight: true }); + await expect(answer(id, 'eu')).resolves.toEqual({ + resolved: true, + alreadyResolved: false, + answer: 'eu', + }); + expect(askRow(id).notified_at).not.toBeNull(); + await expect(answer(id, 'eu')).resolves.toMatchObject({ alreadyResolved: true }); expect(edges.acceptPromptDelivery).toHaveBeenCalledTimes(2); }); @@ -332,6 +355,8 @@ describe('answering a question', () => { status: 'active', }); await expect(answer(id, 'eu', P2, 'chat-2')).rejects.toMatchObject({ statusCode: 404 }); + // Each conjunct alone: the right chat under the wrong project, the wrong chat of the project. + await expect(answer(id, 'eu', P2, 'chat-1')).rejects.toMatchObject({ statusCode: 404 }); await expect(answer(id, 'eu', P1, 'chat-other')).rejects.toMatchObject({ statusCode: 404 }); expect(askRow(id).status).toBe('open'); expect(edges.acceptPromptDelivery).not.toHaveBeenCalled(); @@ -339,6 +364,31 @@ describe('answering a question', () => { await expect(answer(id, 'eu')).resolves.toMatchObject({ resolved: true }); }); + it('the final compare-and-set is bound to project and chat (forged snapshot attack, owner control)', async () => { + const { id } = await question(); + const ask = await loadQuestionAsk(env, P1, 'chat-1', id); + if (!ask) throw new Error('expected the ask'); + const authorization = await edges.authorizeAgentWake(); + for (const forged of [ + { ...ask, projectId: P2 }, + { ...ask, sessionId: 'chat-other' }, + ]) { + await expect( + answerQuestionAsk(env, { ask: forged, answer: 'eu', userId: 'owner', authorization }) + ).rejects.toMatchObject({ statusCode: 404 }); + } + expect(askRow(id).status).toBe('open'); + expect(edges.acceptPromptDelivery).not.toHaveBeenCalled(); + // Owner control with the genuine snapshot; a second answer from the same stale snapshot loses. + await expect( + answerQuestionAsk(env, { ask, answer: 'eu', userId: 'owner', authorization }) + ).resolves.toMatchObject({ resolved: true }); + await expect( + answerQuestionAsk(env, { ask, answer: 'us', userId: 'owner', authorization }) + ).rejects.toMatchObject({ statusCode: 409 }); + expect(edges.acceptPromptDelivery).toHaveBeenCalledOnce(); + }); + it('the inbox answer route goes through the same path and outcomes', async () => { const { id } = await question(); const ctx = { @@ -460,8 +510,20 @@ describe('a typed chat message answers the chat’s open questions', () => { it('closes the chat’s open questions only, bound to project and chat, without a notice', async () => { const a = await question(); const b = await question({ context: 'Second question?' }); - const otherChat = await question({ sessionId: 'chat-x', taskId: 'task-x' }).catch(() => null); - expect(otherChat).toBeNull(); // task-x is not a task of the project + // Another chat of the same project: not answered by a message in chat-1. + insert('asks', { + id: 'other-chat', + project_id: P1, + assignee_kind: 'user', + assignee_user_id: 'owner', + kind: 'question', + blocking: 1, + title: 'Other chat', + source_session_id: 'chat-other', + status: 'open', + created_at: 1, + updated_at: 1, + }); insert('asks', { id: 'foreign', project_id: P2, @@ -487,6 +549,7 @@ describe('a typed chat message answers the chat’s open questions', () => { expect(askRow(id).notified_at).not.toBeNull(); } expect(askRow('foreign').status).toBe('open'); + expect(askRow('other-chat').status).toBe('open'); expect(broadcast).toHaveBeenCalledWith( 'attention.resolved', expect.objectContaining({ sessionId: 'chat-1', markerId: a.id, reason: 'human_message' }), diff --git a/apps/api/tests/workers/inbox-capability.test.ts b/apps/api/tests/workers/inbox-capability.test.ts index 66e952dc36..2fb97ea4d1 100644 --- a/apps/api/tests/workers/inbox-capability.test.ts +++ b/apps/api/tests/workers/inbox-capability.test.ts @@ -15,6 +15,7 @@ import { handleAppError } from '../../src/middleware/app-error-handler'; import { requireApproved, requireAuth } from '../../src/middleware/auth'; import { webOperationContext } from '../../src/operation-ports'; import { inboxRoutes, projectInboxRoutes } from '../../src/routes/inbox'; +import { runInboxAskSweep } from '../../src/services/inbox/sweep'; import { storeMcpToken } from '../../src/services/mcp-token'; import { seedAgentSession, @@ -209,8 +210,9 @@ describe('inbox capability through the real entry points', () => { .bind(s.chatSessionId) .first<{ attention_json: string | null }>(); expect(summary?.attention_json ?? null).toBeNull(); - // The chat's own reads still show it as the chat's question (ProjectData session read). - expect(await s.project.getSession(s.chatSessionId)).toMatchObject({ + // The chat list's ProjectData read still shows it as the chat's question. + const listed = await s.project.listSessions(null, 20, 0, null, null); + expect(listed.sessions.find((session) => session.id === s.chatSessionId)).toMatchObject({ attention: { markerId: askId, kind: 'needs_input', source: 'request_human_input' }, }); @@ -524,4 +526,208 @@ describe('inbox capability through the real entry points', () => { const archivedList = await get('/api/inbox?filter=archived', s.ownerCookie); expect(archivedList.body.items.map((item) => item.ref)).toContain(created.ref); }); + + // Inbox slice G: what a question marker did inside ProjectData, through the real Durable Object. + describe('asks-era questions inside ProjectData', () => { + // The expiry path stops the task run on its VM; stub that edge and keep it off the network. + beforeEach(() => { + vi.stubGlobal('fetch', fetchMock); + fetchMock.mockImplementation(async () => Response.json({ ok: true })); + }); + + async function ask(s: Seeded, context = 'Ship the billing fix now?') { + const result = await callTool(s.token, 'request_human_input', { context }); + return (result.humanInputRequest as { id: string }).id; + } + async function askRow(id: string) { + return testEnv.DATABASE.prepare( + 'SELECT status, answer_json, notified_at, resolved_at FROM asks WHERE id = ?' + ) + .bind(id) + .first<{ + status: string; + answer_json: string | null; + notified_at: number | null; + resolved_at: number | null; + }>(); + } + async function taskStatus(taskId: string) { + return testEnv.DATABASE.prepare('SELECT status, error_message FROM tasks WHERE id = ?') + .bind(taskId) + .first<{ status: string; error_message: string | null }>(); + } + + it('another member cannot read-to-answer, answer or archive the owner’s question (attack + owner control)', async () => { + const s = await seed(); + const id = await ask(s); + const card = (cookie: string, path = '') => + SELF.fetch( + `https://api.${testEnv.BASE_DOMAIN}/api/projects/${s.projectId}/sessions/${s.chatSessionId}/attention/${id}${path}`, + path + ? { + method: 'POST', + headers: { Cookie: cookie, 'Content-Type': 'application/json', Origin: ORIGIN }, + body: JSON.stringify({ answer: 'Yes' }), + } + : { headers: { Cookie: cookie } } + ); + // A member who is not the chat's owner (and has no grant) reads it without answer controls. + const read = await card(s.colleagueCookie); + if (read.status === 200) { + expect((await read.json<{ request: { canAnswer: boolean } }>()).request.canAnswer).toBe( + false + ); + } else { + expect(read.status).toBe(404); + } + expect((await card(s.colleagueCookie, '/resolve')).status).toBe(403); + const ref = encodeURIComponent(`ask:${id}`); + expect( + ( + await post(`/api/projects/${s.projectId}/inbox/items/${ref}/answer`, s.colleagueCookie, { + answer: 'Yes', + }) + ).status + ).toBe(404); + expect( + (await post(`/api/projects/${s.projectId}/inbox/items/${ref}/archive`, s.colleagueCookie)) + .status + ).toBe(404); + expect((await askRow(id))?.status).toBe('open'); + const snapshot = await s.project.getDurableExecutionSnapshot(s.chatSessionId); + expect( + snapshot.deliveries.filter((delivery: { id: string }) => delivery.id === `inbox-ask:${id}`) + ).toEqual([]); + // Owner control. + expect((await card(s.ownerCookie, '/resolve')).status).toBe(200); + expect((await askRow(id))?.status).toBe('answered'); + }); + + it('the ProjectData reads behind team status show the question', async () => { + const s = await seed(); + const id = await ask(s); + const [session] = await s.project.getSessionsByTaskIds([s.taskId]); + expect(session).toMatchObject({ attention: { markerId: id, kind: 'needs_input' } }); + }); + + it('a person’s chat message answers the chat’s open questions, and only those', async () => { + const s = await seed(); + const first = await ask(s); + const second = await ask(s, 'And the docs too?'); + // A question in another chat of this project (foreign projects: real-SQL unit test). + await testEnv.DATABASE.prepare( + `INSERT INTO asks (id, project_id, assignee_kind, assignee_user_id, kind, blocking, title, + source_session_id, status, created_at, updated_at) + VALUES ('other-chat-q', ?, 'user', ?, 'question', 1, 'y', ?, 'open', 1, 1)` + ) + .bind(s.projectId, s.ownerId, s.colleagueSessionId) + .run(); + await s.project.persistMessageBatch(s.chatSessionId, [ + { + messageId: `typed-${crypto.randomUUID()}`, + role: 'user', + content: 'Yes, ship it, and the docs.', + toolMetadata: null, + timestamp: new Date(Date.now() + 1_000).toISOString(), + }, + ]); + for (const id of [first, second]) { + const row = await askRow(id); + expect(row?.status).toBe('answered'); + expect(row?.notified_at).not.toBeNull(); + } + expect((await askRow('other-chat-q'))?.status).toBe('open'); + // Liveness: the chat itself is no longer waiting on a person. + const listed = await s.project.listSessions(null, 20, 0, null, null); + expect( + listed.sessions.find((session) => session.id === s.chatSessionId)?.attention ?? null + ).toBeNull(); + }); + + it('an agent’s own message does not answer its question (control)', async () => { + const s = await seed(); + const id = await ask(s); + await s.project.persistMessageBatch(s.chatSessionId, [ + { + messageId: `agent-${crypto.randomUUID()}`, + role: 'assistant', + content: 'Waiting for your answer.', + toolMetadata: null, + timestamp: new Date(Date.now() + 1_000).toISOString(), + }, + ]); + expect((await askRow(id))?.status).toBe('open'); + }); + + it('filing a question answers SAM’s open check-in, as a question marker did', async () => { + const s = await seed(); + await s.project.createAttentionMarker({ + sessionId: s.chatSessionId, + taskId: s.taskId, + workspaceId: s.workspaceId, + kind: 'reconciliation_checkin', + source: 'reconciliation_loop', + reason: 'Are you still working?', + metadata: null, + expiresAt: Date.now() + 3_600_000, + }); + expect( + (await s.project.listActiveAttentionMarkers(s.chatSessionId)).map((marker) => marker.kind) + ).toEqual(['reconciliation_checkin']); + await ask(s); + expect(await s.project.listActiveAttentionMarkers(s.chatSessionId)).toEqual([]); + }); + + it('an expired question stops its task, as a question marker’s expiry did', async () => { + const s = await seed(); + const id = await ask(s); + // The task runs in the chat's workspace, as a dispatched task does. + await testEnv.DATABASE.prepare('UPDATE tasks SET workspace_id = ? WHERE id = ?') + .bind(s.workspaceId, s.taskId) + .run(); + const past = Date.now() - 1_000; + // Past its deadline and its hard limit, so no undelivered grace applies. + await testEnv.DATABASE.prepare( + 'UPDATE asks SET expires_at = ?, max_expires_at = ? WHERE id = ?' + ) + .bind(past, past, id) + .run(); + await runInboxAskSweep(testEnv); + const row = await askRow(id); + expect(row?.status).toBe('expired'); + expect(row?.notified_at).not.toBeNull(); + expect(await taskStatus(s.taskId)).toMatchObject({ + status: 'failed', + error_message: 'Human input request expired after timeout', + }); + }); + + it('a question the person already answered in the chat does not stop the task at expiry', async () => { + const s = await seed(); + const id = await ask(s); + await testEnv.DATABASE.prepare('UPDATE tasks SET workspace_id = ? WHERE id = ?') + .bind(s.workspaceId, s.taskId) + .run(); + await s.project.persistMessageBatch(s.chatSessionId, [ + { + messageId: `typed-${crypto.randomUUID()}`, + role: 'user', + content: 'Yes.', + toolMetadata: null, + timestamp: new Date(Date.now() + 1_000).toISOString(), + }, + ]); + // As if closing the row had failed: the expiry backstop must see the message. + const past = Date.now() - 1_000; + await testEnv.DATABASE.prepare( + `UPDATE asks SET status = 'open', notified_at = NULL, expires_at = ?, max_expires_at = ? + WHERE id = ?` + ) + .bind(past, past, id) + .run(); + await runInboxAskSweep(testEnv); + expect((await askRow(id))?.status).toBe('expired'); + expect((await taskStatus(s.taskId))?.status).toBe('in_progress'); + }); + }); }); diff --git a/apps/www/src/content/docs/docs/guides/admin-settings.md b/apps/www/src/content/docs/docs/guides/admin-settings.md index 6434503840..e458fc3f60 100644 --- a/apps/www/src/content/docs/docs/guides/admin-settings.md +++ b/apps/www/src/content/docs/docs/guides/admin-settings.md @@ -261,17 +261,17 @@ where it says so and the app continues from there. Listed under **Chat**. Bounds for the [inbox](/docs/reference/api/#inbox) list and for the inbox items agents file (`packages/operations/src/inbox-settings-definition.ts`). -| Setting | Default | Range | What it limits | -| -------------------------- | ------- | ---------- | ---------------------------------------------------------------------------------------- | -| `inbox.listPageSize` | 25 | 1–200 | Items one list page returns when the app does not ask for a number | -| `inbox.listPageMax` | 100 | 1–200 | Most items one list page returns | -| `inbox.titleMaxChars` | 200 | 40–1,000 | Characters of an item title; longer titles are refused when the item is filed | -| `inbox.bodyMaxChars` | 4,000 | 200–20,000 | Characters of an item body (the agent's reason) | -| `inbox.linksMax` | 20 | 0–100 | Links one item may carry | -| `inbox.openItemsPerChat` | 20 | 1–500 | Open items one chat may have at once; filing past it is refused | -| `inbox.answerMaxChars` | 4,000 | 100–20,000 | Characters of a typed answer or comment | -| `inbox.noticeRetryMinutes` | 60 | 5–1,440 | Minutes the sweep retries telling an agent its item was answered, archived or expired | -| `inbox.sweepBatchSize` | 10 | 1–50 | Items one five-minute sweep expires or re-notifies (each is a write and an agent notice) | +| Setting | Default | Range | What it limits | +| -------------------------- | ------- | ---------- | -------------------------------------------------------------------------------------- | +| `inbox.listPageSize` | 25 | 1–200 | Items one list page returns when the app does not ask for a number | +| `inbox.listPageMax` | 100 | 1–200 | Most items one list page returns | +| `inbox.titleMaxChars` | 200 | 40–1,000 | Characters of an item title; longer titles are refused when the item is filed | +| `inbox.bodyMaxChars` | 4,000 | 200–20,000 | Characters of an item body (the agent's reason) | +| `inbox.linksMax` | 20 | 0–100 | Links one item may carry | +| `inbox.openItemsPerChat` | 20 | 1–500 | Open items one chat may have at once; filing past it is refused | +| `inbox.answerMaxChars` | 4,000 | 100–20,000 | Characters of a typed answer or comment | +| `inbox.noticeRetryMinutes` | 60 | 5–1,440 | Minutes the sweep retries telling an agent its item was answered, archived or expired | +| `inbox.sweepBatchSize` | 10 | 1–50 | Items each step of the five-minute sweep handles (reminders, expiries, notice retries) | A question an agent asks with `request_human_input` is an inbox item, and these settings set its schedule (`apps/api/src/services/inbox/sweep.ts`, every five minutes): diff --git a/packages/operations/src/attention-core.ts b/packages/operations/src/attention-core.ts index 558d2a16b6..c108b55d79 100644 --- a/packages/operations/src/attention-core.ts +++ b/packages/operations/src/attention-core.ts @@ -134,10 +134,11 @@ async function openQuestionMarkers( notification_id, assignee_user_id FROM asks WHERE project_id = ? AND source_session_id = ? AND kind = 'question' AND status = 'open' + AND (expires_at IS NULL OR expires_at > ?) ORDER BY created_at DESC, id DESC LIMIT ?` ) - .bind(projectId, sessionId, MAX_OPEN_QUESTIONS_PER_READ) + .bind(projectId, sessionId, Date.now(), MAX_OPEN_QUESTIONS_PER_READ) .all>(); const markers: Marker[] = []; for (const row of result.results ?? []) { diff --git a/packages/operations/src/inbox-list-core.ts b/packages/operations/src/inbox-list-core.ts index 3c3a5283e8..831c0e32d9 100644 --- a/packages/operations/src/inbox-list-core.ts +++ b/packages/operations/src/inbox-list-core.ts @@ -1,18 +1,18 @@ /** * The inbox list and count (idea 01M7G03ZCQ6TM6CMEYDRKQ8ST9, spec section 3.2): one D1 statement * over every store that holds an ask today, filtered to the viewer and to active project - * membership, merged and sorted. Nothing is copied: questions and permissions are read from the + * membership, merged and sorted. Nothing is copied: `asks` rows (questions since slice G, + * reviews, tasks, errors), permission requests and questions asked before slice G from the * `session_summaries.attention_json` index the ProjectData DO already writes - * (`packages/project-data/src/do/session-summary-sync.ts`), so the list never calls a Durable - * Object per chat. + * (`packages/project-data/src/do/session-summary-sync.ts`), secret requests and approvals. The + * list never calls a Durable Object per chat. * * Sort: tier 0 items with a live deadline (permissions, asks with a due time), tier 1 blocking, * tier 2 the rest; inside a tier the items of one chat (or group) stay together as a stack, * stacks ordered by their oldest item, items oldest first. * - * Known limit until slices G and J: `attention_json` holds one marker per chat (the newest open - * question, `getAttentionSummary`), so a chat with two open questions lists one; the next appears - * when the first is answered. + * `attention_json` holds one marker per chat, so a chat lists one permission (or one question + * asked before slice G) at a time until slice J moves permissions into `asks`. */ import type { InboxCountResponse, diff --git a/packages/operations/src/inbox-settings-definition.ts b/packages/operations/src/inbox-settings-definition.ts index f906619c1c..7f72858c7d 100644 --- a/packages/operations/src/inbox-settings-definition.ts +++ b/packages/operations/src/inbox-settings-definition.ts @@ -98,7 +98,7 @@ export const INBOX_SETTINGS = [ name: 'inbox.sweepBatchSize', defaultValue: 10, description: - 'Inbox items one five-minute sweep expires or re-notifies at most. Each costs a write and an agent notice.', + 'Inbox items each step of the five-minute sweep handles at most (question reminders, expiries, notice retries). Each costs a write and a notice.', range: { min: 1, max: 50 }, }, ] as const; diff --git a/packages/project-data/src/do/durability-foundation.ts b/packages/project-data/src/do/durability-foundation.ts index 183c294530..b65eb6a2cd 100644 --- a/packages/project-data/src/do/durability-foundation.ts +++ b/packages/project-data/src/do/durability-foundation.ts @@ -13,6 +13,7 @@ import * as mailbox from './mailbox'; import { projectDataPorts } from './ports'; import * as delivery from './prompt-delivery'; import { runPromptDeliveryClaim } from './prompt-delivery-runner'; +import { releaseQuestionHold } from './reconciliation-candidate-state'; import { resetReconciliationEpisode } from './reconciliation-episode'; import { promptDeliveryToolMetadata } from './sam-notice-metadata'; import * as sessionState from './session-state'; @@ -61,9 +62,6 @@ export async function finalizeAcceptedPromptDelivery( let alarmError: unknown = null; try { runAcceptedPromptDeliveryHooks(sql, _env, hooks, input, accepted); - if (accepted.transcriptInserted && input.senderType === 'human') { - await hooks.closeQuestionAsks?.(input.targetSessionId, accepted.transcriptMessageId); - } } catch (error) { hookError = error; } finally { @@ -80,6 +78,11 @@ export async function finalizeAcceptedPromptDelivery( throw hookError; } if (alarmError) throw alarmError; + // A person's prompt answers the chat's open questions in D1 `asks`, after the broadcast and the + // alarm so the D1 round trip delays neither (`question-asks.ts`, never throws). + if (accepted.transcriptInserted && input.senderType === 'human') { + await hooks.closeQuestionAsks?.(input.targetSessionId, accepted.transcriptMessageId); + } } function runAcceptedPromptDeliveryHooks( @@ -94,6 +97,7 @@ function runAcceptedPromptDeliveryHooks( // did when a question marker resolved. const questionAskId = input.sourceKind === 'inbox_ask' ? input.metadata?.questionAskId : null; if (typeof questionAskId === 'string' && questionAskId) { + releaseQuestionHold(sql, input.targetSessionId); hooks.broadcastEvent( 'attention.resolved', { @@ -226,12 +230,12 @@ export function createCheckpointEpisode( const result = hooks.transactionSync(() => checkpoints.createCheckpointEpisode(sql, input)); if (!result.created) return result; projectDataPorts().observability.recordDurableExecutionMetric(env, { - metric: 'checkpoint_episode_transition', - projectId: hooks.getProjectId(), - sessionId: input.sessionId, - checkpointEpisodeId: result.episode.id, - attemptCount: result.episode.attemptCount, - reason: 'planned', + metric: 'checkpoint_episode_transition', + projectId: hooks.getProjectId(), + sessionId: input.sessionId, + checkpointEpisodeId: result.episode.id, + attemptCount: result.episode.attemptCount, + reason: 'planned', }); activityEvents.recordActivityEventInternal( sql, @@ -273,12 +277,12 @@ export function transitionCheckpointEpisode( ); if (!episode || !before || episode.state === before.state) return episode; projectDataPorts().observability.recordDurableExecutionMetric(env, { - metric: 'checkpoint_episode_transition', - projectId: hooks.getProjectId(), - sessionId: episode.sessionId, - checkpointEpisodeId: episode.id, - attemptCount: episode.attemptCount, - reason: `${before.state}->${episode.state}`, + metric: 'checkpoint_episode_transition', + projectId: hooks.getProjectId(), + sessionId: episode.sessionId, + checkpointEpisodeId: episode.id, + attemptCount: episode.attemptCount, + reason: `${before.state}->${episode.state}`, }); activityEvents.recordActivityEventInternal( sql, diff --git a/packages/project-data/src/do/index.ts b/packages/project-data/src/do/index.ts index cf9b8d92e7..7f51070d26 100644 --- a/packages/project-data/src/do/index.ts +++ b/packages/project-data/src/do/index.ts @@ -115,6 +115,7 @@ import { } from './provider-limit-attention'; import * as questionAsks from './question-asks'; import * as reconciliation from './reconciliation'; +import { releaseQuestionHold } from './reconciliation-candidate-state'; import { parseCountCnt, parseMaxLatest, parseMetaValue } from './row-schemas'; import { instrumentRowUsage, RowUsage } from './row-usage'; import { checkRuntimeHeartbeatTimeouts } from './runtime-heartbeat-policy'; @@ -1005,12 +1006,14 @@ export class ProjectData extends DurableObject { } /** A person's chat message answers the chat's open questions in D1 `asks` (inbox slice G). */ - private closeQuestionAsks(sessionId: string, messageId: string | null): Promise { - return questionAsks.closeQuestionAsksForHumanMessage( + private async closeQuestionAsks(sessionId: string, messageId: string | null): Promise { + const closed = await questionAsks.closeQuestionAsksForHumanMessage( this.env, { projectId: this.getProjectId(), sessionId, messageId }, (type, payload, targetSessionId) => this.broadcastEvent(type, payload, targetSessionId) ); + if (closed > 0 && releaseQuestionHold(this.sql, sessionId)) await this.recalculateAlarm(); + return closed; } /** The chats' open questions from D1 `asks`, merged into their attention (inbox slice G). */ @@ -1030,7 +1033,9 @@ export class ProjectData extends DurableObject { if (questions.size === 0) return sessions; return sessions.map((session) => { const question = typeof session.id === 'string' ? questions.get(session.id) : undefined; - return question ? { ...session, attention: preferAttention(session.attention, question) } : session; + return question + ? { ...session, attention: preferAttention(session.attention, question) } + : session; }); } @@ -1119,11 +1124,14 @@ export class ProjectData extends DurableObject { return sessions.map((s) => this.addBaseDomain(s)); } + /** + * One session. Its `attention` is the ProjectData marker summary only: this read sits on many + * control loops, and nothing renders a single session's attention; the list reads above merge + * open questions from D1 `asks` (inbox slice G). + */ async getSession(sessionId: string): Promise | null> { const result = sessionReads.getSession(this.sql, sessionId); - if (!result) return null; - const [session] = await this.withQuestionAttention([result]); - return this.addBaseDomain(session ?? result); + return result ? this.addBaseDomain(result) : null; } async getMessages( @@ -2896,6 +2904,7 @@ export class ProjectData extends DurableObject { { projectId: this.getProjectId(), scheduleSummarySync: () => this.scheduleSummarySync() } ); } + if (releaseQuestionHold(this.sql, input.sessionId)) await this.recalculateAlarm(); this.broadcastEvent( 'attention.resolved', { @@ -2932,7 +2941,6 @@ export class ProjectData extends DurableObject { return result; } - prepareAttentionAnswer(sessionId: string, markerId: string, answer: string) { return attention.prepareAttentionAnswer(this.sql, sessionId, markerId, answer); } diff --git a/packages/project-data/src/do/message-persistence.ts b/packages/project-data/src/do/message-persistence.ts index 6ec301f107..2249234ef0 100644 --- a/packages/project-data/src/do/message-persistence.ts +++ b/packages/project-data/src/do/message-persistence.ts @@ -131,6 +131,7 @@ export async function runPersistedMessageSideEffects( }, sessionId ); + await closeQuestionsForHumanMessage(hooks, sessionId, [{ id: result.id, role }]); } export async function persistMessageBatchWithSideEffects( @@ -200,6 +201,7 @@ export async function persistMessageBatchWithSideEffects( ); for (const append of result.appends) hooks.broadcastEvent('message.append', { ...append }, sessionId); + await closeQuestionsForHumanMessage(hooks, sessionId, result.persistedMessages); return { persisted: result.persisted, duplicates: result.duplicates, @@ -229,7 +231,6 @@ async function resolveAttentionForRoles( 'human_message' ); reason = 'human_message'; - await hooks.closeQuestionAsks?.(sessionId, firstUserMsg.id); } else if (firstAssistantMsg) { resolved = attention.resolveAttentionMarkersByKind( sql, @@ -248,6 +249,20 @@ async function resolveAttentionForRoles( } } +/** + * A person's message answers the chat's open questions in D1 `asks` (inbox slice G), as it + * resolves the chat's markers above. Run after the live broadcast, so a D1 round trip never + * delays it; never throws (`question-asks.ts`). + */ +async function closeQuestionsForHumanMessage( + hooks: MessagePersistenceHooks, + sessionId: string, + persistedMessages: Array<{ id: string; role: string; origin?: string | null }> +): Promise { + const firstUserMsg = persistedMessages.find((m) => m.role === 'user' && m.origin !== 'system'); + if (firstUserMsg) await hooks.closeQuestionAsks?.(sessionId, firstUserMsg.id); +} + function parseToolMetadata(toolMetadata: string | null, sessionId: string): unknown { if (!toolMetadata) return null; try { diff --git a/packages/project-data/src/do/question-asks.ts b/packages/project-data/src/do/question-asks.ts index e6a3844ec3..8fe50863ea 100644 --- a/packages/project-data/src/do/question-asks.ts +++ b/packages/project-data/src/do/question-asks.ts @@ -33,6 +33,7 @@ export async function closeQuestionAsksForHumanMessage( `UPDATE asks SET status = 'answered', answer_json = ?, resolved_at = ?, updated_at = ?, notified_at = ? WHERE project_id = ? AND source_session_id = ? AND kind = 'question' AND status = 'open' + AND created_at <= ? RETURNING id` ) .bind( @@ -41,7 +42,9 @@ export async function closeQuestionAsksForHumanMessage( now, now, input.projectId, - input.sessionId + input.sessionId, + // A question filed after the message is not answered by it. + now ) .all<{ id: string }>(); const ids = (result.results ?? []).map((row) => row.id).filter(Boolean); diff --git a/packages/project-data/src/do/reconciliation-candidate-state.ts b/packages/project-data/src/do/reconciliation-candidate-state.ts index 78aeb17e6e..4a2992d308 100644 --- a/packages/project-data/src/do/reconciliation-candidate-state.ts +++ b/packages/project-data/src/do/reconciliation-candidate-state.ts @@ -25,6 +25,8 @@ export interface ReconciliationGate { nextAttemptAt: number; excludedTaskId: string | null; checkinIntent: ReconciliationCheckinIntent | null; + /** Deferred because the chat has an open question (inbox slice G); released when it closes. */ + questionHold: boolean; } /** @@ -97,6 +99,7 @@ function parseGate(raw: string | null): ReconciliationGate | null { nextAttemptAt: parsed.nextAttemptAt, excludedTaskId: typeof parsed.excludedTaskId === 'string' ? parsed.excludedTaskId : null, checkinIntent: parseCheckinIntent(parsed.checkinIntent), + questionHold: parsed.questionHold === true, }; } catch { return null; @@ -185,7 +188,8 @@ export function deferReconciliationCandidate( export function deferReconciliationCandidateUntil( sql: SqlStorage, sessionId: string, - nextAttemptAt: number + nextAttemptAt: number, + options: { questionHold?: boolean } = {} ): void { const key = gateKey(sessionId); const existing = parseGate(readMeta(sql, key)); @@ -193,6 +197,7 @@ export function deferReconciliationCandidateUntil( ...(existing?.checkinIntent ? { checkinIntent: existing.checkinIntent } : {}), attempts: 0, nextAttemptAt, + ...(options.questionHold ? { questionHold: true } : {}), }); } @@ -221,6 +226,19 @@ export function getOrCreateReconciliationCheckinIntent( return checkinIntent; } +/** + * A chat's open question closed (answered, archived, expired, or the person wrote in the chat): + * a check-in held until the question's deadline is due again from now (inbox slice G). A gate + * that is not deferred is left alone. + */ +export function releaseQuestionHold(sql: SqlStorage, sessionId: string, now = Date.now()): boolean { + const existing = parseGate(readMeta(sql, gateKey(sessionId))); + // Only a question hold: a claim lease or a quarantine on the same gate is not ours to end. + if (!existing?.questionHold || existing.nextAttemptAt <= now) return false; + deferReconciliationCandidateUntil(sql, sessionId, now); + return true; +} + export function clearReconciliationCandidateGate(sql: SqlStorage, sessionId: string): void { sql.exec('DELETE FROM do_meta WHERE key = ?', gateKey(sessionId)); } diff --git a/packages/project-data/src/do/reconciliation-candidates.ts b/packages/project-data/src/do/reconciliation-candidates.ts index d3ead3bdaf..fdb6f063a1 100644 --- a/packages/project-data/src/do/reconciliation-candidates.ts +++ b/packages/project-data/src/do/reconciliation-candidates.ts @@ -159,15 +159,17 @@ async function resolveCandidateProjectId( // marker does in the local candidate query: the agent is waiting on a person, not stalled. const taskRow = await env.DATABASE.prepare( `SELECT task_mode, status, project_id, workspace_id, chat_session_id, admission_state, - EXISTS ( - SELECT 1 FROM asks a - WHERE a.project_id = tasks.project_id AND a.source_session_id = ?2 + ( + -- The task's own chat (checked against this session just below); now in epoch ms. + SELECT MAX(COALESCE(a.expires_at, 0)) FROM asks a + WHERE a.project_id = tasks.project_id AND a.source_session_id = tasks.chat_session_id AND a.kind = 'question' AND a.status = 'open' - AND (a.expires_at IS NULL OR a.expires_at > ?3) - ) AS open_question - FROM tasks WHERE id = ?1 LIMIT 1` + AND (a.expires_at IS NULL + OR a.expires_at > CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)) + ) AS open_question_until + FROM tasks WHERE id = ? LIMIT 1` ) - .bind(taskId, sessionId, now) + .bind(taskId) .first<{ task_mode: string | null; admission_state?: string | null; @@ -175,7 +177,7 @@ async function resolveCandidateProjectId( project_id: string | null; workspace_id: string | null; chat_session_id: string | null; - open_question?: number | null; + open_question_until?: number | null; }>(); if (!taskRow) { recordReconciliationCandidateInconclusive(sql, env, { @@ -217,10 +219,16 @@ async function resolveCandidateProjectId( }); return null; } - if (taskRow.open_question) { - // Looked at again one lease later; answering or expiring the question ends the hold, and - // the deferral spends no probe attempt. - deferReconciliationCandidateUntil(sql, sessionId, now + reconciliationCandidateLeaseMs(env)); + if (taskRow.open_question_until !== null && taskRow.open_question_until !== undefined) { + // Held until the question's own deadline, so an open question costs no alarms (the alarm + // reads this gate time, `computeReconciliationAlarmTime`). Closing the question releases the + // hold at once (`releaseQuestionHold`); the deferral spends no probe attempt. + deferReconciliationCandidateUntil( + sql, + sessionId, + Math.max(taskRow.open_question_until, now + reconciliationCandidateLeaseMs(env)), + { questionHold: true } + ); return null; } return taskRow.project_id; diff --git a/packages/project-data/tests/unit/idea-work-question-asks.test.ts b/packages/project-data/tests/unit/idea-work-question-asks.test.ts new file mode 100644 index 0000000000..47244ba84e --- /dev/null +++ b/packages/project-data/tests/unit/idea-work-question-asks.test.ts @@ -0,0 +1,76 @@ +/** + * Inbox slice G: an idea's "question" status also shows open questions held in D1 `asks`, the + * way it showed question markers (`idea-work.ts:mergeQuestionAsks`). + */ +import { describe, expect, it } from 'vitest'; + +import { + ideaQuestionSessionIds, + type IdeaWorkSnapshot, + mergeQuestionAsks, +} from '../../src/do/idea-work'; + +function snapshot(): IdeaWorkSnapshot { + return { + ideaId: 'idea-1', + sessions: [ + session('strong-chat', true), + session('weak-chat', false), + session('marker-chat', true), + ], + needsInput: [{ sessionId: 'marker-chat', question: 'Marker question', askedAt: 5_000 }], + fileIds: [], + pullRequestUrls: [], + updates: 0, + truncated: { sessions: false }, + } as unknown as IdeaWorkSnapshot; +} + +function session(sessionId: string, strong: boolean) { + return { + sessionId, + topic: null, + sessionStatus: 'active', + sessionTaskId: null, + lastActivityAt: null, + relations: [strong ? 'works_on' : 'read'], + strong, + linkedAt: 1, + }; +} + +describe('idea work: open questions in D1 asks', () => { + it('asks only for the strongly linked chats', () => { + expect(ideaQuestionSessionIds({ 'idea-1': snapshot() }).sort()).toEqual([ + 'marker-chat', + 'strong-chat', + ]); + }); + + it('adds a strong chat’s question, ignores a weak one, and keeps a newer marker question', () => { + const snapshots = { 'idea-1': snapshot() }; + mergeQuestionAsks( + snapshots, + new Map([ + ['strong-chat', { reason: 'Ask question', createdAt: 6_000 }], + ['weak-chat', { reason: 'Weak link question', createdAt: 7_000 }], + ['marker-chat', { reason: 'Older ask', createdAt: 4_000 }], + ]) + ); + expect(snapshots['idea-1'].needsInput).toEqual([ + { sessionId: 'strong-chat', question: 'Ask question', askedAt: 6_000 }, + { sessionId: 'marker-chat', question: 'Marker question', askedAt: 5_000 }, + ]); + }); + + it('a newer ask replaces an older marker question of the same chat', () => { + const snapshots = { 'idea-1': snapshot() }; + mergeQuestionAsks( + snapshots, + new Map([['marker-chat', { reason: 'New ask', createdAt: 9_000 }]]) + ); + expect(snapshots['idea-1'].needsInput).toEqual([ + { sessionId: 'marker-chat', question: 'New ask', askedAt: 9_000 }, + ]); + }); +}); diff --git a/packages/shared/src/types/inbox.ts b/packages/shared/src/types/inbox.ts index 7120c046ad..141a012dd9 100644 --- a/packages/shared/src/types/inbox.ts +++ b/packages/shared/src/types/inbox.ts @@ -4,9 +4,9 @@ * inbox keeps no copy (`packages/operations/src/inbox-list-core.ts`). * * Stores: - * - `ask`: D1 `asks` (reviews, human tasks, errors; questions from slice G) - * - `attention`: a question or permission held as a ProjectData attention marker, read from the - * `session_summaries.attention_json` index until slices G and J move them into `asks` + * - `ask`: D1 `asks` (questions since slice G, reviews, human tasks, errors) + * - `attention`: a permission (until slice J), or a question asked before slice G, held as a + * ProjectData attention marker and read from the `session_summaries.attention_json` index * - `secret`: D1 `runtime_secret_requests` * - `approval`: D1 `operations_action_approvals` */ diff --git a/packages/worker-core/src/schema.ts b/packages/worker-core/src/schema.ts index 7dc8d6c7e8..0b20bd9dc8 100644 --- a/packages/worker-core/src/schema.ts +++ b/packages/worker-core/src/schema.ts @@ -833,6 +833,9 @@ export const asks = sqliteTable( openEscalationIdx: index('idx_asks_open_escalation') .on(table.nextEscalationAt) .where(sql`status = 'open' AND next_escalation_at IS NOT NULL`), + openQuestionIdx: index('idx_asks_open_question') + .on(table.projectId, table.sourceSessionId, table.createdAt) + .where(sql`kind = 'question' AND status = 'open'`), assigneeStatusIdx: index('idx_asks_assignee_status').on( table.assigneeUserId, table.status, diff --git a/scripts/quality/sync-wrangler-config.test.ts b/scripts/quality/sync-wrangler-config.test.ts index dc2c695a4c..0361305ed8 100644 --- a/scripts/quality/sync-wrangler-config.test.ts +++ b/scripts/quality/sync-wrangler-config.test.ts @@ -1322,9 +1322,13 @@ describe('Worker vars omitted because they equal the code default', () => { // The busy-build placement wait it bounded was removed (2026-11-08): a busy node is now ranked by // its startup backlog instead of waited on, so nothing reads the timeout. const RETIRED_WITH_BUSY_BUILD_WAIT = ['VM_ADMISSION_BUSY_BUILD_WAIT_TIMEOUT_MS'] as const; + // A question's window moved to the admin setting `inbox.questionTimeoutMinutes` with inbox + // slice G (2026-11-16): questions are D1 `asks` rows, and nothing reads the variable. + const RETIRED_WITH_QUESTION_ASKS = ['HUMAN_INPUT_TIMEOUT_MS'] as const; const RETIRED_VARS: readonly string[] = [ ...RETIRED_WITH_ANONYMOUS_TRIALS, ...RETIRED_WITH_BUSY_BUILD_WAIT, + ...RETIRED_WITH_QUESTION_ASKS, ]; it('pins original bindings to retained values, deliberate retunes or proven runtime defaults', () => { From 941495d91241aac57ea16938f8df545e3e045695 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 05:43:28 +0000 Subject: [PATCH 05/13] fix(inbox): close questions filed before the message; hold check-ins through the sweep - typed-message close binds the message's own timestamp - the check-in hold covers a question just past its deadline until the sweep extends or expires it - tests: file-wide VM fetch stub, real-DO retry idempotence of the answer notice, just-expired hold case Co-Authored-By: Claude Opus 5.5 --- .../durable-objects/reconciliation.test.ts | 9 +++++- .../unit/services/inbox/question-asks.test.ts | 2 +- .../tests/workers/inbox-capability.test.ts | 32 +++++++++++++++++++ .../src/do/durability-foundation.ts | 12 +++++-- packages/project-data/src/do/index.ts | 14 +++++--- .../src/do/message-persistence.ts | 21 +++++++++--- packages/project-data/src/do/question-asks.ts | 11 +++++-- .../src/do/reconciliation-candidates.ts | 5 ++- 8 files changed, 90 insertions(+), 16 deletions(-) diff --git a/apps/api/tests/unit/durable-objects/reconciliation.test.ts b/apps/api/tests/unit/durable-objects/reconciliation.test.ts index 184c1ae7a8..f62ffb8da7 100644 --- a/apps/api/tests/unit/durable-objects/reconciliation.test.ts +++ b/apps/api/tests/unit/durable-objects/reconciliation.test.ts @@ -694,7 +694,7 @@ describe('Task Reconciliation Module', () => { it.each([ ['answered', { status: 'answered' }], - ['expired', { expiresAt: Date.now() - 1 }], + ['expired more than three sweep ticks ago', { expiresAt: Date.now() - 16 * 60_000 }], ['in another project', { projectId: 'project-2' }], ['in another chat', { sessionId: 'session-2' }], ])('does not hold for a question that is %s (control)', async (_label, overrides) => { @@ -705,6 +705,13 @@ describe('Task Reconciliation Module', () => { ]); }); + it('a question just past its deadline still holds until the sweep handles it', async () => { + setupTaskSession(); + seedAsk('q-1', { expiresAt: Date.now() - 60_000 }); + await expect(getReconciliationCandidates(sql, questionEnv())).resolves.toEqual([]); + expect(gate()).toMatchObject({ questionHold: true }); + }); + it('a release never ends a claim lease or another deferral', () => { setupTaskSession(); db.prepare( diff --git a/apps/api/tests/unit/services/inbox/question-asks.test.ts b/apps/api/tests/unit/services/inbox/question-asks.test.ts index 9413a3ca07..29c76bdc69 100644 --- a/apps/api/tests/unit/services/inbox/question-asks.test.ts +++ b/apps/api/tests/unit/services/inbox/question-asks.test.ts @@ -540,7 +540,7 @@ describe('a typed chat message answers the chat’s open questions', () => { const broadcast = vi.fn(); const closed = await closeQuestionAsksForHumanMessage( env as never, - { projectId: P1, sessionId: 'chat-1', messageId: 'msg-1' }, + { projectId: P1, sessionId: 'chat-1', messageId: 'msg-1', messageCreatedAt: Date.now() }, broadcast ); expect(closed).toBe(2); diff --git a/apps/api/tests/workers/inbox-capability.test.ts b/apps/api/tests/workers/inbox-capability.test.ts index 2fb97ea4d1..7490da6de0 100644 --- a/apps/api/tests/workers/inbox-capability.test.ts +++ b/apps/api/tests/workers/inbox-capability.test.ts @@ -176,6 +176,10 @@ type ListBody = { items: { ref: string; kind: string; canAct: boolean; projectId describe('inbox capability through the real entry points', () => { beforeEach(() => { fetchMock.mockReset(); + // The VM edge is stubbed for every test (task-run stops, live prompts); tests that assert on + // it set their own responses. + vi.stubGlobal('fetch', fetchMock); + fetchMock.mockImplementation(async () => Response.json({ ok: true })); }); afterEach(() => { vi.unstubAllGlobals(); @@ -603,6 +607,34 @@ describe('inbox capability through the real entry points', () => { expect((await askRow(id))?.status).toBe('answered'); }); + it('a retried answer notice does not reach the agent twice', async () => { + const s = await seed(); + const id = await ask(s); + const response = await post( + `/api/projects/${s.projectId}/inbox/items/${encodeURIComponent(`ask:${id}`)}/answer`, + s.ownerCookie, + { answer: 'Yes' } + ); + expect(response.status).toBe(200); + // As if recording the notice had failed after it was queued: the sweep retries it. + const resolvedAt = (await askRow(id))?.resolved_at ?? Date.now(); + await testEnv.DATABASE.prepare('UPDATE asks SET notified_at = NULL WHERE id = ?') + .bind(id) + .run(); + await runInboxAskSweep(testEnv, resolvedAt + 2 * 60_000); + expect((await askRow(id))?.notified_at).not.toBeNull(); + const snapshot = await s.project.getDurableExecutionSnapshot(s.chatSessionId); + expect( + snapshot.deliveries.filter((delivery: { id: string }) => delivery.id === `inbox-ask:${id}`) + ).toHaveLength(1); + const { messages } = await s.project.getMessages(s.chatSessionId, 50); + expect( + messages.filter((message: { content: string }) => + message.content.startsWith('The person answered your question') + ) + ).toHaveLength(1); + }); + it('the ProjectData reads behind team status show the question', async () => { const s = await seed(); const id = await ask(s); diff --git a/packages/project-data/src/do/durability-foundation.ts b/packages/project-data/src/do/durability-foundation.ts index b65eb6a2cd..d2461fb525 100644 --- a/packages/project-data/src/do/durability-foundation.ts +++ b/packages/project-data/src/do/durability-foundation.ts @@ -35,7 +35,11 @@ export interface DurabilityFoundationHooks { /** Release durable messages queued behind the (now ended) turn. */ nudgeDeliveries(chatSessionId: string): number; /** A person's message answers the chat's open questions in D1 `asks` (`question-asks.ts`). */ - closeQuestionAsks?(sessionId: string, messageId: string): Promise; + closeQuestionAsks?( + sessionId: string, + messageId: string, + messageCreatedAt: number + ): Promise; } export async function acceptPromptDelivery( @@ -81,7 +85,11 @@ export async function finalizeAcceptedPromptDelivery( // A person's prompt answers the chat's open questions in D1 `asks`, after the broadcast and the // alarm so the D1 round trip delays neither (`question-asks.ts`, never throws). if (accepted.transcriptInserted && input.senderType === 'human') { - await hooks.closeQuestionAsks?.(input.targetSessionId, accepted.transcriptMessageId); + await hooks.closeQuestionAsks?.( + input.targetSessionId, + accepted.transcriptMessageId, + accepted.transcriptCreatedAt + ); } } diff --git a/packages/project-data/src/do/index.ts b/packages/project-data/src/do/index.ts index 7f51070d26..48a7d15ac1 100644 --- a/packages/project-data/src/do/index.ts +++ b/packages/project-data/src/do/index.ts @@ -1001,15 +1001,20 @@ export class ProjectData extends DurableObject { }, nudgeDeliveries: (chatSessionId) => promptDelivery.nudgePromptDeliveriesForTarget(this.sql, chatSessionId), - closeQuestionAsks: (sessionId, messageId) => this.closeQuestionAsks(sessionId, messageId), + closeQuestionAsks: (sessionId, messageId, messageCreatedAt) => + this.closeQuestionAsks(sessionId, messageId, messageCreatedAt), }; } /** A person's chat message answers the chat's open questions in D1 `asks` (inbox slice G). */ - private async closeQuestionAsks(sessionId: string, messageId: string | null): Promise { + private async closeQuestionAsks( + sessionId: string, + messageId: string | null, + messageCreatedAt: number + ): Promise { const closed = await questionAsks.closeQuestionAsksForHumanMessage( this.env, - { projectId: this.getProjectId(), sessionId, messageId }, + { projectId: this.getProjectId(), sessionId, messageId, messageCreatedAt }, (type, payload, targetSessionId) => this.broadcastEvent(type, payload, targetSessionId) ); if (closed > 0 && releaseQuestionHold(this.sql, sessionId)) await this.recalculateAlarm(); @@ -1063,7 +1068,8 @@ export class ProjectData extends DurableObject { recalculateAlarm: () => this.recalculateAlarm(), scheduleSummarySync: () => this.scheduleSummarySync(), broadcastEvent: (type, payload, sessionId) => this.broadcastEvent(type, payload, sessionId), - closeQuestionAsks: (sessionId, messageId) => this.closeQuestionAsks(sessionId, messageId), + closeQuestionAsks: (sessionId, messageId, messageCreatedAt) => + this.closeQuestionAsks(sessionId, messageId, messageCreatedAt), }; } diff --git a/packages/project-data/src/do/message-persistence.ts b/packages/project-data/src/do/message-persistence.ts index 2249234ef0..afef4ba2ac 100644 --- a/packages/project-data/src/do/message-persistence.ts +++ b/packages/project-data/src/do/message-persistence.ts @@ -33,7 +33,11 @@ export type MessagePersistenceHooks = { * A person's chat message answers the chat's open questions in D1 `asks` (inbox slice G), as it * resolves its attention markers. Never throws (`question-asks.ts`). */ - closeQuestionAsks?: (sessionId: string, messageId: string) => Promise; + closeQuestionAsks?: ( + sessionId: string, + messageId: string, + messageCreatedAt: number + ) => Promise; }; export type MessageBatchPersistenceResult = { @@ -131,7 +135,9 @@ export async function runPersistedMessageSideEffects( }, sessionId ); - await closeQuestionsForHumanMessage(hooks, sessionId, [{ id: result.id, role }]); + await closeQuestionsForHumanMessage(hooks, sessionId, [ + { id: result.id, role, createdAt: result.now }, + ]); } export async function persistMessageBatchWithSideEffects( @@ -257,10 +263,17 @@ async function resolveAttentionForRoles( async function closeQuestionsForHumanMessage( hooks: MessagePersistenceHooks, sessionId: string, - persistedMessages: Array<{ id: string; role: string; origin?: string | null }> + persistedMessages: Array<{ + id: string; + role: string; + origin?: string | null; + createdAt: number; + }> ): Promise { const firstUserMsg = persistedMessages.find((m) => m.role === 'user' && m.origin !== 'system'); - if (firstUserMsg) await hooks.closeQuestionAsks?.(sessionId, firstUserMsg.id); + if (firstUserMsg) { + await hooks.closeQuestionAsks?.(sessionId, firstUserMsg.id, firstUserMsg.createdAt); + } } function parseToolMetadata(toolMetadata: string | null, sessionId: string): unknown { diff --git a/packages/project-data/src/do/question-asks.ts b/packages/project-data/src/do/question-asks.ts index 8fe50863ea..d0409ffe69 100644 --- a/packages/project-data/src/do/question-asks.ts +++ b/packages/project-data/src/do/question-asks.ts @@ -23,7 +23,13 @@ type Broadcast = (type: string, payload: Record, sessionId?: st */ export async function closeQuestionAsksForHumanMessage( env: Env, - input: { projectId: string | null; sessionId: string; messageId: string | null }, + input: { + projectId: string | null; + sessionId: string; + messageId: string | null; + /** When the message was persisted; a question filed after it is not answered by it. */ + messageCreatedAt: number; + }, broadcast: Broadcast ): Promise { if (!input.projectId) return 0; @@ -43,8 +49,7 @@ export async function closeQuestionAsksForHumanMessage( now, input.projectId, input.sessionId, - // A question filed after the message is not answered by it. - now + input.messageCreatedAt ) .all<{ id: string }>(); const ids = (result.results ?? []).map((row) => row.id).filter(Boolean); diff --git a/packages/project-data/src/do/reconciliation-candidates.ts b/packages/project-data/src/do/reconciliation-candidates.ts index fdb6f063a1..431715c49d 100644 --- a/packages/project-data/src/do/reconciliation-candidates.ts +++ b/packages/project-data/src/do/reconciliation-candidates.ts @@ -164,8 +164,11 @@ async function resolveCandidateProjectId( SELECT MAX(COALESCE(a.expires_at, 0)) FROM asks a WHERE a.project_id = tasks.project_id AND a.source_session_id = tasks.chat_session_id AND a.kind = 'question' AND a.status = 'open' + -- Past its deadline still holds for three sweep ticks: the inbox sweep may + -- extend an undelivered question, and expires it within one tick otherwise. AND (a.expires_at IS NULL - OR a.expires_at > CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)) + OR a.expires_at > CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER) + - 15 * 60000) ) AS open_question_until FROM tasks WHERE id = ? LIMIT 1` ) From 493e57d1c9e69e9a5b034a658c4ce27f26a545aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 05:44:31 +0000 Subject: [PATCH 06/13] task: slice G checklist after review Co-Authored-By: Claude Opus 5.5 --- ...11-16-inbox-slice-g-questions-into-asks.md | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md b/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md index 0bf3d95958..0abfdb445f 100644 --- a/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md +++ b/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md @@ -98,12 +98,20 @@ exist at deploy time stay answerable and archivable until they resolve or expire - [x] Connector pending attention merges question asks - [x] Stalled-task classifier reads asks - [x] Remove code that only served new needs_input question markers -- [ ] Tests: capability (ask → sleep → answer via inbox → woken once; archive), concurrent answers, +- [x] Tests: capability (ask → sleep → answer via inbox → woken once; archive), concurrent answers, marker-era vs asks-era overlap, tenancy attack/owner pairs on real SQL (discriminating), expiry/reminder schedule, chat list overlay, Connector projection - [x] Docs: API reference / admin settings / any doc describing request_human_input storage - [x] Idea for removing marker-era question code after overlap: `01M7HC7CN5WY6GEP9G0PP4DG7B` +- [x] Reconciliation check-in hold, idea status, team/account-map reads, Connector lists (from the inventory) +- [ ] Staging: real Claude Code + Codex agents on a VM (and an Instant check): ask, answer from inbox and card, archive, expiry on a shortened setting, sleeping chat wakes + +## Notes + +- Reviews: security-auditor, cloudflare-specialist, test-engineer, task-completion-validator all ADDRESSED (see PR #2780). +- Main rejected the direct task-file push (repository rules), so this file lives on the branch only. + ## Rule 44 inventory Every writer and reader of question markers (kind `needs_input`) and of @@ -145,11 +153,11 @@ removal tracked in the follow-up idea filed with this PR. ## Acceptance criteria -- [ ] A new request_human_input question is one `asks` row; no marker, no `attention_json` change -- [ ] Chat card, chat list needs-input state and the inbox show it as before -- [ ] Answer via chat card and via inbox: one wins under concurrency; same outcomes as today -- [ ] Answer to a sleeping chat wakes it and the agent receives the answer once; archive likewise -- [ ] Expiry and reminders keep today's schedule; expired ask ends `expired` -- [ ] Marker-era questions stay answerable/archivable until resolved or expired -- [ ] Tenancy guards on `asks` proven on real SQL with discriminating attack/owner pairs -- [ ] Limits are admin settings +- [x] A new request_human_input question is one `asks` row; no marker, no `attention_json` change +- [x] Chat card, chat list needs-input state and the inbox show it as before (tests; staging pending) +- [x] Answer via chat card and via inbox: one wins under concurrency; same outcomes as today +- [ ] Answer to a sleeping chat wakes it and the agent receives the answer once; archive likewise (tests prove one wake-capable delivery; live wake: staging) +- [x] Expiry and reminders keep today's schedule; expired ask ends `expired` +- [x] Marker-era questions stay answerable/archivable until resolved or expired +- [x] Tenancy guards on `asks` proven on real SQL with discriminating attack/owner pairs +- [x] Limits are admin settings From 1e27e9df3ff0a5747c0ddb918972c3ace133773d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 05:51:55 +0000 Subject: [PATCH 07/13] fix(inbox): read a question's answer spec through maybeJsonRecord Co-Authored-By: Claude Opus 5.5 --- packages/worker-core/src/question-asks.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/worker-core/src/question-asks.ts b/packages/worker-core/src/question-asks.ts index 3c1df4f286..d5c6f926b9 100644 --- a/packages/worker-core/src/question-asks.ts +++ b/packages/worker-core/src/question-asks.ts @@ -8,6 +8,7 @@ * their consumers see no difference. One home for the record; this module only reads it. */ import { createModuleLogger } from './logger'; +import { maybeJsonRecord } from './runtime-validation'; const log = createModuleLogger('question_asks'); @@ -49,10 +50,8 @@ export const DEFAULT_OPEN_QUESTION_READ_LIMIT = 500; export function questionOptions(answerSpecJson: unknown): string[] { if (typeof answerSpecJson !== 'string' || !answerSpecJson) return []; try { - const spec = JSON.parse(answerSpecJson) as unknown; - if (!spec || typeof spec !== 'object') return []; - const record = spec as Record; - if (record.type !== 'options' || !Array.isArray(record.options)) return []; + const record = maybeJsonRecord(JSON.parse(answerSpecJson) as unknown); + if (!record || record.type !== 'options' || !Array.isArray(record.options)) return []; return record.options.filter((option): option is string => typeof option === 'string'); } catch { return []; From 091d53e1122f675c4b7f0788c6df86370c8a08ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 07:07:30 +0000 Subject: [PATCH 08/13] task: slice G state before usage pause Co-Authored-By: Claude Opus 5.5 --- tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md | 1 + 1 file changed, 1 insertion(+) diff --git a/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md b/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md index 0abfdb445f..8c99925c48 100644 --- a/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md +++ b/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md @@ -110,6 +110,7 @@ exist at deploy time stay answerable and archivable until they resolve or expire ## Notes - Reviews: security-auditor, cloudflare-specialist, test-engineer, task-completion-validator all ADDRESSED (see PR #2780). +- 07:08Z: paused for the account's 5-hour window (77%, resets 09:10Z); resume wake 09:12Z. Remaining: rebase on F1 (#2775) if merged and adapt its overview query (`.tmp/adapt-f1.py` locally, otherwise: count open question asks in RUNNING_SQL has_attention/row filter/WAITING_ON_VIEWER_SQL), staging2 live checks, merge, deploy. - Main rejected the direct task-file push (repository rules), so this file lives on the branch only. ## Rule 44 inventory From 29742a498edcdde3aa624a11abd03b868f03ab6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 09:19:54 +0000 Subject: [PATCH 09/13] fix(inbox): project overview reads open question asks as waiting The Project Overview (F1) found a chat paused on a person only through session_summaries.attention_json, which no longer carries agent questions. Read this project's open, unexpired question asks once in a CTE and treat either signal as paused, for the waiting state, the ranking and the count. Co-Authored-By: Claude Opus 5.5 --- .../unit/operations/project-overview.test.ts | 48 +++++++++++++++++++ packages/operations/src/project-overview.ts | 28 +++++++++-- 2 files changed, 71 insertions(+), 5 deletions(-) diff --git a/apps/api/tests/unit/operations/project-overview.test.ts b/apps/api/tests/unit/operations/project-overview.test.ts index 84755ddd0a..73882176d1 100644 --- a/apps/api/tests/unit/operations/project-overview.test.ts +++ b/apps/api/tests/unit/operations/project-overview.test.ts @@ -267,6 +267,54 @@ describe('projectOverviewGet', () => { expect(mate.running.waitingOnViewerTotal).toBe(1); }); + /** An agent question held in D1 `asks` (inbox slice G): not copied into the chat summary. */ + function question( + id: string, + sessionId: string, + fields: Record = {} + ): void { + const now = Date.now(); + insert('asks', { + id, + project_id: 'p', + assignee_kind: 'user', + assignee_user_id: 'owner', + kind: 'question', + blocking: 1, + title: 'Which region?', + source_session_id: sessionId, + status: 'open', + expires_at: now + HOUR, + created_at: now, + updated_at: now, + ...fields, + }); + } + + it('reads a chat paused on an open question ask as waiting, ranked first and counted', async () => { + // Idle chats with no attention marker: only the ask can make them show. + const idle = { agent_completed_at: NOW - 120_000, last_message_at: NOW - 10 * HOUR }; + running('asked', idle); + question('ask-1', 'asked'); + running('fresh', {}, {}); + // Controls: an expired and an answered question leave the chat idle (not shown). + running('expired-q', idle); + question('ask-expired', 'expired-q', { expires_at: Date.now() - 1 }); + running('answered-q', idle); + question('ask-answered', 'answered-q', { status: 'answered' }); + // Attack: another project's open question naming this project's chat id. + running('foreign-q', idle); + question('ask-foreign', 'foreign-q', { project_id: 'foreign' }); + + const result = await projectOverviewGet(ctx(), { projectId: 'p', runningLimit: 1 }); + // The cap is 1: the waiting chat outranks the newer working one. + expect(result.running.items).toEqual([ + expect.objectContaining({ sessionId: 'asked', state: 'waiting', waitingOnViewer: true }), + ]); + expect(result.running.total).toBe(2); + expect(result.running.waitingOnViewerTotal).toBe(1); + }); + it('skips one malformed row and keeps the rest', async () => { running('good'); running('bad'); diff --git a/packages/operations/src/project-overview.ts b/packages/operations/src/project-overview.ts index b98d2cb45f..f7f9828ef2 100644 --- a/packages/operations/src/project-overview.ts +++ b/packages/operations/src/project-overview.ts @@ -42,13 +42,21 @@ export const OVERVIEW_RUNNING_TASK_STATUSES = [ const sqlList = (values: readonly string[]) => values.map((value) => `'${value}'`).join(', '); +/** + * The chat is paused on a person: a ProjectData attention marker (synced to + * `session_summaries.attention_json`), or an open question held in D1 `asks` (inbox slice G), + * which is not copied into the summary. `open_questions` is the CTE at the head of `RUNNING_SQL`. + */ +const PAUSED_ON_PERSON_SQL = `(ss.attention_json IS NOT NULL + OR ss.id IN (SELECT session_id FROM open_questions))`; + /** * 1 for a chat paused on a question the viewer must answer (they started it, it is past * starting), else 0. Ranked first so the cap can never hide the one exception the page exists to * surface (`apps/api/.claude/rules/65`), and summed so the page can say how many there are. * Binds the viewer id; it appears twice in `RUNNING_SQL` (the sum and the ranking). */ -const WAITING_ON_VIEWER_SQL = `(CASE WHEN ss.attention_json IS NOT NULL AND ss.created_by_user_id = ? +const WAITING_ON_VIEWER_SQL = `(CASE WHEN ${PAUSED_ON_PERSON_SQL} AND ss.created_by_user_id = ? AND t.status NOT IN (${sqlList(OVERVIEW_STARTING_TASK_STATUSES)}) THEN 1 ELSE 0 END)`; /** @@ -58,11 +66,20 @@ const WAITING_ON_VIEWER_SQL = `(CASE WHEN ss.attention_json IS NOT NULL AND ss.c * open question. The task join carries `project_id` so a task id cannot reach across projects * (rule 11), and a profile name is shown only for this project's profiles or the task creator's * own global ones, so a hint naming someone else's global profile reveals nothing. `COUNT(*) OVER ()` gives the total without a second round trip. + * `open_questions` reads this project's open, unexpired question asks once + * (`idx_asks_open_question`), bound to the project like every other predicate here. */ const RUNNING_SQL = ` + WITH open_questions AS ( + SELECT DISTINCT source_session_id AS session_id + FROM asks + WHERE project_id = ? AND kind = 'question' AND status = 'open' + AND source_session_id IS NOT NULL + AND (expires_at IS NULL OR expires_at > ?) + ) SELECT ss.id, ss.task_id, ss.topic, ss.started_at, ss.created_at, ss.last_message_at, ss.agent_completed_at, ss.created_by_user_id, - CASE WHEN ss.attention_json IS NULL THEN 0 ELSE 1 END AS has_attention, + CASE WHEN ${PAUSED_ON_PERSON_SQL} THEN 1 ELSE 0 END AS has_attention, t.status AS task_status, t.agent_profile_hint, ap.name AS profile_name, COUNT(*) OVER () AS total, @@ -77,7 +94,7 @@ const RUNNING_SQL = ` AND t.status IN (${sqlList(OVERVIEW_RUNNING_TASK_STATUSES)}) AND ( t.status IN (${sqlList(OVERVIEW_STARTING_TASK_STATUSES)}) - OR ss.attention_json IS NOT NULL + OR ${PAUSED_ON_PERSON_SQL} OR (ss.agent_completed_at IS NULL AND (t.execution_step IS NULL OR t.execution_step <> 'awaiting_followup')) ) @@ -160,8 +177,9 @@ async function readRunning( limit: number ): Promise { const result = await ctx.env.DATABASE.prepare(RUNNING_SQL) - // Placeholders in order: viewer (sum), project, viewer (ranking), limit. - .bind(ctx.actor.userId, projectId, ctx.actor.userId, limit) + // Placeholders in order: project and clock (open questions), viewer (sum), project, + // viewer (ranking), limit. + .bind(projectId, Date.now(), ctx.actor.userId, projectId, ctx.actor.userId, limit) .all>(); const rows = result.results ?? []; const items: OverviewRunningChat[] = []; From d26f416d6996110ab1e134f302a36f4457df7963 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 09:58:00 +0000 Subject: [PATCH 10/13] task: file staging-found sleep 500 and near-timeout capacity test Co-Authored-By: Claude Opus 5.5 --- ...acity-pool-query-plan-test-near-timeout.md | 18 +++++++++++++++ ...1-16-manual-sleep-hibernate-timeout-500.md | 22 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 tasks/backlog/2026-11-16-capacity-pool-query-plan-test-near-timeout.md create mode 100644 tasks/backlog/2026-11-16-manual-sleep-hibernate-timeout-500.md diff --git a/tasks/backlog/2026-11-16-capacity-pool-query-plan-test-near-timeout.md b/tasks/backlog/2026-11-16-capacity-pool-query-plan-test-near-timeout.md new file mode 100644 index 0000000000..09e5322630 --- /dev/null +++ b/tasks/backlog/2026-11-16-capacity-pool-query-plan-test-near-timeout.md @@ -0,0 +1,18 @@ +# capacity-pool-edit-query-plan test runs at the 5 s default timeout + +## Problem + +`apps/api/tests/unit/services/capacity-pool-edit-query-plan.test.ts` ("pool edit on a large pool > +updates the edited rows and their mirrors, looking every row up by id") timed out on CI +(5,450 ms against the 5,000 ms default) on PR #2780's rebased head, run 43838791321, job 133203179677. +Locally its two cases take 4.6–4.9 s together, so a loaded runner tips it over. + +## Context + +Found during inbox slice G CI. The test seeds a production-sized pool on purpose (rule 69, D1 CPU +ceiling), so the cost is intrinsic; the timeout is not. + +## Acceptance Criteria + +- [ ] The test sets an explicit timeout sized for its fixture, or the fixture setup is made cheaper without shrinking the row count below the production shape it guards +- [ ] Ten consecutive local runs and one CI run pass diff --git a/tasks/backlog/2026-11-16-manual-sleep-hibernate-timeout-500.md b/tasks/backlog/2026-11-16-manual-sleep-hibernate-timeout-500.md new file mode 100644 index 0000000000..a6a564e02b --- /dev/null +++ b/tasks/backlog/2026-11-16-manual-sleep-hibernate-timeout-500.md @@ -0,0 +1,22 @@ +# Manual chat sleep returns 500 when the VM agent's hibernate call exceeds 5 s + +## Problem + +`POST /api/projects/:projectId/sessions/:sessionId/sleep` returned `500 INTERNAL_ERROR` on staging2 +(2026-11-16T09:45:59Z, request `42e1b0f7-9cf7-4ed4-8c15-afe85eb40824`). The platform error log shows +`Request timed out after 5000ms: https://.vm.sammy2.party:8443/workspaces//agent-sessions//hibernate`. +A second attempt ~80 s later succeeded and the chat slept with a snapshot. + +A VM agent that is slow to acknowledge hibernate is an expected, retryable condition, not a server fault. +The route maps it to an opaque 500 and the person gets no indication that retrying will work. + +## Context + +Found while verifying inbox slice G (PR #2780) on staging2: sleeping a freshly started VM chat right +after its agent's first turn. The chat had just finished a prompt (`ACP Prompt completed` at 09:45:50Z). + +## Acceptance Criteria + +- [ ] A hibernate timeout returns a designed, retryable status (for example 503 or 409 with a clear message), not 500 +- [ ] The timeout budget for the hibernate call is checked against how long snapshot capture actually takes, and is configurable (`DEFAULT_*` constant) +- [ ] A route test drives the real handler with a VM agent that answers after the budget and asserts the designed status From 05e47808603e2f726d78d22bbed3bf3a3f73bd27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 09:58:19 +0000 Subject: [PATCH 11/13] task: slice G staging2 evidence Co-Authored-By: Claude Opus 5.5 --- ...11-16-inbox-slice-g-questions-into-asks.md | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md b/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md index 8c99925c48..8564e0b372 100644 --- a/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md +++ b/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md @@ -105,7 +105,8 @@ exist at deploy time stay answerable and archivable until they resolve or expire - [x] Idea for removing marker-era question code after overlap: `01M7HC7CN5WY6GEP9G0PP4DG7B` - [x] Reconciliation check-in hold, idea status, team/account-map reads, Connector lists (from the inventory) -- [ ] Staging: real Claude Code + Codex agents on a VM (and an Instant check): ask, answer from inbox and card, archive, expiry on a shortened setting, sleeping chat wakes +- [x] Rebased on main after F1 (#2775): the Project Overview reads open question asks as "waiting" (`open_questions` CTE, project-bound; commit 3e738055a, both guards proven discriminating) +- [x] Staging (staging2, run 43838856327, 2026-11-16 09:39–09:55Z): real Claude Code agents on a VM and on Instant: ask, answer from inbox and card, concurrent answers (one wins), invalid option 400, archive, expiry on a 1-minute setting, sleeping VM chat woke from an inbox answer. Codex: not testable on staging2 (only Claude Code keys are provisioned there); covered by the harness-agnostic MCP path and its tests ## Notes @@ -113,6 +114,22 @@ exist at deploy time stay answerable and archivable until they resolve or expire - 07:08Z: paused for the account's 5-hour window (77%, resets 09:10Z); resume wake 09:12Z. Remaining: rebase on F1 (#2775) if merged and adapt its overview query (`.tmp/adapt-f1.py` locally, otherwise: count open question asks in RUNNING_SQL has_attention/row filter/WAITING_ON_VIEWER_SQL), staging2 live checks, merge, deploy. - Main rejected the direct task-file push (repository rules), so this file lives on the branch only. +### Staging evidence (staging2, 2026-11-16) + +Project `01M7HTM8747B16PHS25TQ6WBZA` (Artifacts, Claude Code), user `staging2-agent-user`. + +| Check | Runtime | Result | +| --- | --- | --- | +| Question filed as one `asks` row; inbox `store: "ask"`; chat list `needs_input` with the ask id; card GET; Project Overview `waiting`, `waitingOnViewer: true` | Instant | pass | +| Concurrent answers (inbox `eu` vs card `us`) | Instant | card won 200; inbox 409 "A different answer is already being delivered"; replay 200 `alreadyResolved`; agent replied `GOT I: us` | +| Archive from inbox | Instant | 200 `archived`, `agentNotified`; later answer 409; agent told and replied | +| Answer from inbox to a SLEEPING chat | VM | chat slept (snapshot), question still shown on it; answer woke it; agent replied `GOT A: eu` | +| Answer from card; invalid option | VM | `medium` 400; `large` 200; agent replied `GOT B: large` | +| Expiry, `inbox.questionTimeoutMinutes` and `questionMaxWaitMinutes` = 1 (reset to defaults after) | Instant | card `expired: true` at the deadline; sweep set `status='expired'` at 09:53:09Z; task failed "Human input request expired after timeout" (marker-era outcome) | +| D1 rows | both | 3 answered, 1 archived, 1 expired; every row `notified_at` set; schedule columns as configured | + +Found while testing (filed): manual sleep 500 on a slow hibernate (`tasks/backlog/2026-11-16-manual-sleep-hibernate-timeout-500.md`); capacity-pool test at the 5 s timeout (`tasks/backlog/2026-11-16-capacity-pool-query-plan-test-near-timeout.md`). A transient upstream `402 AI inference failed` on the VM agent's first turn cleared on retry. Cleanup: both chats stopped, VM node deleted, lease released (run 43844057826). + ## Rule 44 inventory Every writer and reader of question markers (kind `needs_input`) and of @@ -157,7 +174,7 @@ removal tracked in the follow-up idea filed with this PR. - [x] A new request_human_input question is one `asks` row; no marker, no `attention_json` change - [x] Chat card, chat list needs-input state and the inbox show it as before (tests; staging pending) - [x] Answer via chat card and via inbox: one wins under concurrency; same outcomes as today -- [ ] Answer to a sleeping chat wakes it and the agent receives the answer once; archive likewise (tests prove one wake-capable delivery; live wake: staging) +- [x] Answer to a sleeping chat wakes it and the agent receives the answer once; archive likewise (tests prove one wake-capable delivery; live wake verified on staging2: VM chat 70624ba1 slept, inbox answer at 09:47:55Z, awake and replying at 09:49:25Z) - [x] Expiry and reminders keep today's schedule; expired ask ends `expired` - [x] Marker-era questions stay answerable/archivable until resolved or expired - [x] Tenancy guards on `asks` proven on real SQL with discriminating attack/owner pairs From 503d59ec6ec2715e749de0d285bf06ed40bc9a7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 09:59:03 +0000 Subject: [PATCH 12/13] task: archive inbox slice G Co-Authored-By: Claude Opus 5.5 --- .../2026-11-16-inbox-slice-g-questions-into-asks.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tasks/{active => archive}/2026-11-16-inbox-slice-g-questions-into-asks.md (100%) diff --git a/tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md b/tasks/archive/2026-11-16-inbox-slice-g-questions-into-asks.md similarity index 100% rename from tasks/active/2026-11-16-inbox-slice-g-questions-into-asks.md rename to tasks/archive/2026-11-16-inbox-slice-g-questions-into-asks.md From 387e213d2cc7471cc44ae13cfc757f20a996f049 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 10:22:22 +0000 Subject: [PATCH 13/13] test(project-data): give the ingest-cost fixture its project id Every production ProjectData object carries do_meta.projectId before an RPC reaches it (ensureProjectId through the service memo) and reads it from memory afterwards. The fixture never set it, so slice G's question close on a human message re-ran the empty lookup each batch. With the production shape the profile is unchanged from main. Co-Authored-By: Claude Opus 5.5 --- apps/api/tests/workers/project-data-ingest-cost.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/api/tests/workers/project-data-ingest-cost.test.ts b/apps/api/tests/workers/project-data-ingest-cost.test.ts index ad1cb4b826..32f9d3f6b5 100644 --- a/apps/api/tests/workers/project-data-ingest-cost.test.ts +++ b/apps/api/tests/workers/project-data-ingest-cost.test.ts @@ -94,7 +94,10 @@ describe('message ingest row cost in real workerd', () => { maxRowBytes: 65536, recentIds: 200, }); + // Every production ProjectData object carries its project id before any RPC reaches it + // (`ensureProjectId`, through the service layer's memo), and reads it from memory after. const stub = projectDataStub(`ingest-cost-${crypto.randomUUID()}`); + await stub.ensureProjectId('cost-project'); const session = await stub.createSession('cost-workspace', 'Existing topic'); const now = Date.now(); await runInDurableObject(stub, (_instance, state) => {