From 3bf3205497a19848c2772f8b66aa30f82c1ad658 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Fri, 20 Nov 2026 22:42:31 +0000 Subject: [PATCH 01/27] feat(linear): stream task progress into the agent session (#1066) A Linear agent session showed only the start and the end of a task. It now shows what the agent is doing while it works, where the task stands, and whether the reader has to act: - each tool call as an ephemeral action ("Reading `src/app.ts`"), replaced by the next one - the agent's messages as thoughts, clipped to 600 characters - setup steps: issue context gathered, repository cloned, attachments read, nudge picked up - "Queued" and "Still queued (N min so far)" while waiting on the concurrency limit; the admission reconciler re-emits admission_queued every 15 minutes so a long wait does not go stale - the session checklist (Linear's plan): understand the ticket, set up the repository, write the code, open the pull request, ready for your review. The stage is kept on the task record with a forward-only conditional write; the terminal event completes it or cancels what was left - a closing line on the final activity saying whether the reader needs to do anything (review the PR, answer the question, try again) - a task that ends with a pull request moves its issue to In Review, which the setup guide already promised for session tasks Persistent activities are capped at 30 per task with a conditional counter on the task record, so a long run cannot flood the session. Ephemeral tool calls do not count, and only the newest tool call per task in a stream batch is sent. Progress events have their own per-invocation cap, so they cannot crowd out the lifecycle events. Activity ids are derived from the event id, so a stream retry does not post twice. Progress and the checklist are best effort: a failed write is logged, never retried, and nothing is posted after the session's final response or a terminal status. Progress events only route when LINEAR_AGENT_SESSIONS_ENABLED is set, and the comment path ignores them, so comment-path tasks see no change. --- cdk/src/handlers/fanout-task-events.ts | 266 ++++++++++++++++-- cdk/src/handlers/reconcile-admission-queue.ts | 34 +++ .../handlers/shared/linear-agent-session.ts | 17 +- .../shared/linear-session-checklist.ts | 133 +++++++++ .../shared/linear-session-progress.ts | 212 ++++++++++++++ cdk/src/handlers/shared/types.ts | 5 + .../fanout-linear-agent-session.test.ts | 4 +- .../fanout-linear-session-progress.test.ts | 258 +++++++++++++++++ .../reconcile-admission-queue.test.ts | 57 +++- .../shared/linear-session-checklist.test.ts | 69 +++++ .../shared/linear-session-progress.test.ts | 71 +++++ docs/guides/LINEAR_SETUP_GUIDE.md | 10 +- .../content/docs/using/Linear-setup-guide.md | 10 +- 13 files changed, 1116 insertions(+), 30 deletions(-) create mode 100644 cdk/src/handlers/shared/linear-session-checklist.ts create mode 100644 cdk/src/handlers/shared/linear-session-progress.ts create mode 100644 cdk/test/handlers/fanout-linear-session-progress.test.ts create mode 100644 cdk/test/handlers/shared/linear-session-checklist.test.ts create mode 100644 cdk/test/handlers/shared/linear-session-progress.test.ts diff --git a/cdk/src/handlers/fanout-task-events.ts b/cdk/src/handlers/fanout-task-events.ts index 05ad1c409..f3419c4c6 100644 --- a/cdk/src/handlers/fanout-task-events.ts +++ b/cdk/src/handlers/fanout-task-events.ts @@ -66,7 +66,7 @@ import { renderJiraFinishedPointer, type JiraFinishedPointerKind, } from './shared/jira-status-comment'; -import { addAgentSessionExternalUrl, emitAgentActivity, type AgentActivityContent } from './shared/linear-agent-session'; +import { addAgentSessionExternalUrl, emitAgentActivity, setAgentSessionPlan, type AgentActivityContent } from './shared/linear-agent-session'; import { isLinearAgentSessionsEnabled, SESSION_STOP_CANCELLED_VIA } from './shared/linear-agent-session-event'; import { EMOJI_FAILURE, @@ -75,10 +75,27 @@ import { postIssueComment, resolveToken, swapCommentReaction, + transitionIssueState, upsertThreadedReply, type LinearFeedbackContext, type LinearPostResult, } from './shared/linear-feedback'; +import { + checklistKind, + checklistMoveForEvent, + closingLine, + renderChecklist, + type ChecklistEnding, + type ChecklistState, + type SessionOutcome, +} from './shared/linear-session-checklist'; +import { + LINEAR_SESSION_PROGRESS_EVENTS, + LINEAR_SESSION_PROGRESS_MILESTONES, + progressActivityId, + sessionProgressActivity, + type SessionProgressActivity, +} from './shared/linear-session-progress'; import { logger } from './shared/logger'; import { coerceNumericOrNull } from './shared/numeric'; import { loadRepoConfig } from './shared/repo-config'; @@ -219,9 +236,10 @@ export const CHANNEL_DEFAULTS: Record> 'task_timed_out', // Agent-session channel (ADR-018 Phase 2): per-turn events drive the throttled // keep-alive activity that stops a long run's Linear session going `stale` - // (30 min idle). Subscribed only with the flag on, so a default deployment - // does not pay a task read per agent turn. - ...(isLinearAgentSessionsEnabled() ? [LINEAR_SESSION_HEARTBEAT_EVENT] : []), + // (30 min idle), and these plus tool calls, queueing, context and milestones are + // streamed into the session as progress (#1066). Subscribed only with the flag + // on, so a default deployment does not pay a task read per agent turn. + ...(isLinearAgentSessionsEnabled() ? [...LINEAR_SESSION_PROGRESS_EVENTS] : []), ]), // Jira posts a single deterministic final-status comment on terminal // events — the Jira analogue of the Linear default above. @@ -379,7 +397,7 @@ export function parseStreamRecord(record: DynamoDBRecord): FanOutEvent | null { * ``trajectory_uploaded``, ``trace_truncated``. Only ``pr_created`` * is currently in any channel's default filter (§6.2 Slack + GitHub). */ -const ROUTABLE_MILESTONES: ReadonlySet = new Set(['pr_created']); +const ROUTABLE_MILESTONES: ReadonlySet = new Set(['pr_created', ...LINEAR_SESSION_PROGRESS_MILESTONES]); /** * Unwrap ``agent_milestone`` events to their milestone name for @@ -1223,17 +1241,17 @@ async function dispatchToLinear(event: FanOutEvent): Promise { return; } - // Per-turn events reach this dispatcher for EVERY task once the session flag - // is on. Decide from memory before paying a task read: a task known not to - // be a session task never heartbeats, and a session task inside its - // keep-alive window has nothing to post yet. - const isHeartbeat = event.event_type === LINEAR_SESSION_HEARTBEAT_EVENT; - if (isHeartbeat && heartbeatCanSkipTaskRead(event.task_id)) return; + // Session-progress events (per-turn, tool calls, …) reach this dispatcher for + // EVERY task once the session flag is on. Decide from memory before paying a + // task read: a task known not to be a session task has nothing to show, and a + // session task's text-less turn inside its keep-alive window has nothing to post. + const progressOnly = LINEAR_SESSION_PROGRESS_EVENTS.has(effectiveEventType(event)); + if (progressOnly && progressCanSkipTaskRead(event)) return; const task = await loadTaskForComment(event.task_id); // Only a row that was actually read says what kind of task this is: a miss // (not replicated yet, a transient read) must not switch its keep-alive off. - if (isHeartbeat && task) rememberHeartbeatTask(event.task_id, task); + if (progressOnly && task) rememberHeartbeatTask(event.task_id, task); if (!task) { logger.warn('[fanout/linear] task not found — skipping comment', { event: 'fanout.linear.task_missing', @@ -1273,8 +1291,9 @@ async function dispatchToLinear(event: FanOutEvent): Promise { }); return; } - // The per-turn heartbeat only matters to session tasks. - if (event.event_type === LINEAR_SESSION_HEARTBEAT_EVENT) return; + // Session progress only matters to session tasks. (The comment path below would + // otherwise read any `agent_milestone` as the PR milestone.) + if (progressOnly) return; // Iteration-UX: this task is a comment-iteration when it carries a maturing // reply id (set at trigger time). For those, the progress + terminal status @@ -1452,6 +1471,20 @@ interface HeartbeatTaskMemo { const HEARTBEAT_MEMO_MAX_ENTRIES = 2000; const heartbeatMemo = new Map(); +/** + * True when a session-progress event can be dropped without reading the task: the + * task is known not to be a session task, or this is a turn with no text (a bare + * keep-alive) inside the session's keep-alive window. + */ +function progressCanSkipTaskRead(event: FanOutEvent): boolean { + const memo = heartbeatMemo.get(event.task_id); + if (!memo) return false; + if (!memo.sessionTask) return true; + return event.event_type === LINEAR_SESSION_HEARTBEAT_EVENT + && sessionProgressActivity(event.event_type, event.metadata) === null + && heartbeatCanSkipTaskRead(event.task_id); +} + function heartbeatCanSkipTaskRead(taskId: string): boolean { const memo = heartbeatMemo.get(taskId); if (!memo) return false; @@ -1507,6 +1540,16 @@ async function dispatchToLinearAgentSession( ctx: LinearFeedbackContext, ): Promise { const effective = effectiveEventType(event); + await advanceSessionChecklist(event, task, agentSessionId, ctx); + if (LINEAR_SESSION_PROGRESS_EVENTS.has(effective)) { + const progress = sessionProgressActivity(effective, event.metadata); + if (progress) { + await emitLinearSessionProgress(event, task, agentSessionId, ctx, progress); + return; + } + // A turn without text is still the keep-alive below. + if (effective !== LINEAR_SESSION_HEARTBEAT_EVENT) return; + } const isTerminalEvent = LINEAR_SESSION_TERMINAL_EVENTS.has(effective); if (effective !== 'pr_created' && effective !== LINEAR_SESSION_HEARTBEAT_EVENT && !isTerminalEvent) return; const logCtx = { task_id: task.task_id, linear_agent_session_id: agentSessionId, event_type: effective }; @@ -1566,7 +1609,10 @@ async function dispatchToLinearAgentSession( if (result.ok) await saveLinearPrCommentState(task.task_id, event.event_id); } else { result = await emitAgentActivity(token, agentSessionId, linearSessionTerminalActivity(task, event)); - if (result.ok) await saveLinearCommentState(task.task_id, event.event_id); + if (result.ok) { + await saveLinearCommentState(task.task_id, event.event_id); + if (sessionOutcome(task, event) === 'pr') await moveSessionIssueToReview(task, ctx); + } } if (result.ok) { @@ -1585,10 +1631,183 @@ async function dispatchToLinearAgentSession( } } +/** + * How a finished task reads in its session: a pull request to review (also one shipped + * by a run that then stopped early), a question back, no change, a stop, or a failure. + */ +function sessionOutcome(task: TaskRecord, event: FanOutEvent): SessionOutcome { + if (event.event_type === 'task_completed') { + if (task.pr_url) return 'pr'; + // Same shape as the elicitation: no PR and no code change means the run asked a question. + return task.code_changed === false ? 'question' : 'no_change'; + } + if (event.event_type === 'task_cancelled') return 'cancelled'; + return task.pr_url ? 'pr' : 'failed'; +} + +/** ``#12`` from a pull request URL. */ +function prLabel(prUrl: string | undefined): string | undefined { + const n = prUrl?.match(/\/pull\/(\d+)/)?.[1]; + return n ? `#${n}` : undefined; +} + +/** + * Move the session's checklist (#1066). In-flight events move it forward only, with a + * conditional write on ``linear_checklist_stage``; the terminal event completes it, or + * cancels what was left. Best effort: the checklist is a view, never worth a batch retry. + */ +async function advanceSessionChecklist( + event: FanOutEvent, + task: TaskRecord, + agentSessionId: string, + ctx: LinearFeedbackContext, +): Promise { + const kind = checklistKind(task.resolved_workflow?.id); + if (!kind || task.linear_final_comment_event_id) return; + const effective = effectiveEventType(event); + // The document client returns numbers as numbers; coerce in case an older writer stored a string. + const recorded = Number(task.linear_checklist_stage ?? 0); + let state: ChecklistState; + let ending: ChecklistEnding | undefined; + if (LINEAR_SESSION_TERMINAL_EVENTS.has(effective)) { + const outcome = sessionOutcome(task, event); + if (outcome === 'question') { + state = { stage: recorded, note: 'waiting on your answer' }; + } else { + state = { stage: recorded, pr: prLabel(task.pr_url) }; + ending = outcome === 'pr' && event.event_type === 'task_completed' ? 'done' : 'stopped'; + } + } else { + if (TERMINAL_STATUSES.includes(task.status)) return; + const move = checklistMoveForEvent(effective, task.pr_url); + if (!move) return; + state = { ...move, pr: move.pr ?? prLabel(task.pr_url) }; + } + const logCtx = { task_id: task.task_id, linear_agent_session_id: agentSessionId, event_type: effective }; + try { + if (!ending && state.note !== 'waiting on your answer' && !(await claimChecklistStage(task.task_id, state.stage))) return; + const token = await resolveToken(ctx); + if (!token) return; + const result = await setAgentSessionPlan(token, agentSessionId, renderChecklist(kind, state, ending)); + if (!result.ok) logger.warn('[fanout/linear-session] checklist not updated', { ...logCtx, retryable: result.retryable }); + } catch (err) { + logger.warn('[fanout/linear-session] checklist update failed (best effort)', { + ...logCtx, error: err instanceof Error ? err.message : String(err), + }); + } +} + +/** Record a checklist stage if it is past the recorded one; false when it is not (nothing to show). */ +async function claimChecklistStage(taskId: string, stage: number): Promise { + const tableName = process.env.TASK_TABLE_NAME; + if (!tableName) return false; + try { + await ddb.send(new UpdateCommand({ + TableName: tableName, + Key: { task_id: taskId }, + UpdateExpression: 'SET linear_checklist_stage = :s', + ConditionExpression: 'attribute_exists(task_id) AND (attribute_not_exists(linear_checklist_stage) OR linear_checklist_stage < :s)', + ExpressionAttributeValues: { ':s': stage }, + })); + return true; + } catch (err) { + if ((err as { name?: string }).name === 'ConditionalCheckFailedException') return false; + throw err; + } +} + +/** + * A session task that ends with a pull request moves its issue to "In Review" (a + * ``started`` state, so a person's later move to Done is never undone). Best effort. + */ +async function moveSessionIssueToReview(task: TaskRecord, ctx: LinearFeedbackContext): Promise { + const issueId = task.channel_metadata?.linear_issue_id; + if (!issueId) return; + try { + await transitionIssueState(ctx, issueId, 'started', ['In Review']); + } catch (err) { + logger.warn('[fanout/linear-session] could not move the issue to In Review (best effort)', { + task_id: task.task_id, error: err instanceof Error ? err.message : String(err), + }); + } +} + +/** Persistent progress activities per session task; ephemeral ones replace each other and are not counted. */ +const LINEAR_SESSION_PROGRESS_CAP = 30; + +/** + * Emit one progress activity into the task's session (#1066). Best effort: a failure is + * logged and never retried through the batch, since the next event supersedes it. Never + * posts after the session's final activity or into a finished task, because an activity + * after the closing `response` would reopen the session. Persistent activities are capped + * per task by a conditional counter on the task row; the activity id is derived from the + * event id, so a re-run record emits the same activity. + */ +async function emitLinearSessionProgress( + event: FanOutEvent, + task: TaskRecord, + agentSessionId: string, + ctx: LinearFeedbackContext, + progress: SessionProgressActivity, +): Promise { + if (task.linear_final_comment_event_id || TERMINAL_STATUSES.includes(task.status)) return; + const logCtx = { task_id: task.task_id, linear_agent_session_id: agentSessionId, event_type: effectiveEventType(event) }; + try { + if (!progress.ephemeral && !(await claimProgressSlot(task.task_id))) return; + const token = await resolveToken(ctx); + if (!token) return; + const result = await emitAgentActivity(token, agentSessionId, progress.content, { + ephemeral: progress.ephemeral, + id: progressActivityId(event.event_id), + }); + if (!result.ok) logger.warn('[fanout/linear-session] progress activity not emitted', { ...logCtx, retryable: result.retryable }); + } catch (err) { + logger.warn('[fanout/linear-session] progress activity failed (best effort)', { + ...logCtx, error: err instanceof Error ? err.message : String(err), + }); + } +} + +/** Take one of the task's persistent progress slots; false once the cap is reached. */ +async function claimProgressSlot(taskId: string): Promise { + const tableName = process.env.TASK_TABLE_NAME; + if (!tableName) return false; + try { + await ddb.send(new UpdateCommand({ + TableName: tableName, + Key: { task_id: taskId }, + UpdateExpression: 'ADD linear_session_progress_count :one', + ConditionExpression: 'attribute_exists(task_id) AND (attribute_not_exists(linear_session_progress_count) OR linear_session_progress_count < :cap)', + ExpressionAttributeValues: { ':one': 1, ':cap': LINEAR_SESSION_PROGRESS_CAP }, + })); + return true; + } catch (err) { + if ((err as { name?: string }).name === 'ConditionalCheckFailedException') return false; + throw err; + } +} + +/** + * Event ids of tool calls that a later tool call of the same task in this batch + * supersedes. Only the newest one is shown (it is an ephemeral "currently doing" line, + * replaced by the next activity anyway), which keeps a busy agent's Linear calls down. + */ +export function supersededToolCallIds(records: DynamoDBStreamEvent['Records']): Set { + const latest = new Map(); + const all: Array<{ taskId: string; eventId: string }> = []; + for (const record of records) { + const ev = parseStreamRecord(record); + if (!ev || ev.event_type !== 'agent_tool_call') continue; + all.push({ taskId: ev.task_id, eventId: ev.event_id }); + latest.set(ev.task_id, ev.event_id); + } + return new Set(all.filter((c) => latest.get(c.taskId) !== c.eventId).map((c) => c.eventId)); +} + /** The session's final activity for a terminal event. */ export function linearSessionTerminalActivity(task: TaskRecord, event: FanOutEvent): AgentActivityContent { const args = linearFinalStatusArgs(task, event); - const body = renderLinearFinalStatusComment(args); + const body = `${renderLinearFinalStatusComment(args)}\n\n${closingLine(sessionOutcome(task, event))}`; if (event.event_type === 'task_completed') { return args.needsInput ? { type: 'elicitation', body } : { type: 'response', body }; } @@ -2360,6 +2579,10 @@ export const handler = async ( event: DynamoDBStreamEvent, ): Promise => { const perTaskCounts = new Map(); + // Session-progress events have their own per-task budget, so a burst of them can + // never push a task's PR or terminal event out of the batch. + const perTaskProgressCounts = new Map(); + const supersededToolCalls = supersededToolCallIds(event.Records); const batchItemFailures: DynamoDBBatchItemFailure[] = []; let processed = 0; let dispatched = 0; @@ -2382,8 +2605,15 @@ export const handler = async ( dropped++; continue; } + // Only the latest tool call of a task in this batch is shown: the session's + // "currently doing" line would replace the earlier ones at once anyway. + if (supersededToolCalls.has(ev.event_id)) { + dropped++; + continue; + } - const seen = perTaskCounts.get(ev.task_id) ?? 0; + const counts = LINEAR_SESSION_PROGRESS_EVENTS.has(effectiveEventType(ev)) ? perTaskProgressCounts : perTaskCounts; + const seen = counts.get(ev.task_id) ?? 0; if (seen >= MAX_EVENTS_PER_TASK_PER_INVOCATION) { logger.warn('[fanout] per-task cap hit — dropping event', { event: 'fanout.rate_limit.hit', @@ -2396,7 +2626,7 @@ export const handler = async ( dropped++; continue; } - perTaskCounts.set(ev.task_id, seen + 1); + counts.set(ev.task_id, seen + 1); const outcome = await routeEvent(ev, overrides); if (outcome.dispatched.length > 0) dispatched++; diff --git a/cdk/src/handlers/reconcile-admission-queue.ts b/cdk/src/handlers/reconcile-admission-queue.ts index 0b08c48bf..6a23af582 100644 --- a/cdk/src/handlers/reconcile-admission-queue.ts +++ b/cdk/src/handlers/reconcile-admission-queue.ts @@ -353,6 +353,38 @@ async function expireQueuedTask(task: QueuedTask): Promise { return true; } +/** How often a task still waiting in the queue re-announces itself. */ +const QUEUE_HEARTBEAT_MINUTES = 15; +const QUEUE_HEARTBEAT_SECONDS = QUEUE_HEARTBEAT_MINUTES * 60; +/** The pickup schedule's interval (the default; see AdmissionQueuePickup). */ +const PICKUP_INTERVAL_SECONDS = 60; + +/** + * True when a task queued for ``ageSeconds`` crossed another heartbeat mark in the + * last pickup interval, so each mark fires once on a 1-minute schedule. + * @param ageSeconds - how long the task has been queued. + */ +export function isQueueHeartbeatDue(ageSeconds: number): boolean { + return ageSeconds >= QUEUE_HEARTBEAT_SECONDS && ageSeconds % QUEUE_HEARTBEAT_SECONDS < PICKUP_INTERVAL_SECONDS; +} + +/** + * Re-emit ``admission_queued`` (with ``waited_s``) for tasks that stay queued past a + * heartbeat mark (#1066). A Linear agent session shows it as "Still queued (N min so + * far)", and the activity keeps a long wait from turning the session stale. Best effort + * (``emitEvent`` logs and swallows a failed write). + * @param waiting - tasks this cycle leaves in the queue. + */ +async function emitQueueHeartbeats(waiting: readonly QueuedTask[]): Promise { + for (const task of waiting) { + if (!isQueueHeartbeatDue(task.age_seconds)) continue; + await emitEvent(task.task_id, 'admission_queued', { + reason: { S: 'concurrency_limit' }, + waited_s: { N: String(Math.floor(task.age_seconds)) }, + }); + } +} + export async function handler(): Promise { const now = new Date(); const summary: PickupSummary = { @@ -428,6 +460,7 @@ export async function handler(): Promise { if (available <= 0) { summary.skipped_no_capacity += live.length; + await emitQueueHeartbeats(live); continue; } @@ -459,6 +492,7 @@ export async function handler(): Promise { } } summary.skipped_no_capacity += Math.max(0, live.length - available); + await emitQueueHeartbeats(live.slice(available)); } // Escalate to ERROR when the cycle made no forward progress despite a diff --git a/cdk/src/handlers/shared/linear-agent-session.ts b/cdk/src/handlers/shared/linear-agent-session.ts index 532bf0f8a..d333d1478 100644 --- a/cdk/src/handlers/shared/linear-agent-session.ts +++ b/cdk/src/handlers/shared/linear-agent-session.ts @@ -76,11 +76,12 @@ export async function emitAgentActivity( accessToken: string, agentSessionId: string, content: AgentActivityContent, - options: { readonly ephemeral?: boolean } = {}, + options: { readonly ephemeral?: boolean; readonly id?: string } = {}, ): Promise { const ephemeral = options.ephemeral === true && (content.type === 'thought' || content.type === 'action'); return graphqlRequest(accessToken, AGENT_ACTIVITY_CREATE_MUTATION, { - input: { agentSessionId, content, ...(ephemeral && { ephemeral: true }) }, + // `id` (a version-4 UUID) makes a retried emit the same activity rather than a second one. + input: { agentSessionId, content, ...(ephemeral && { ephemeral: true }), ...(options.id && { id: options.id }) }, }); } @@ -99,6 +100,18 @@ export async function addAgentSessionExternalUrl( }); } +/** + * Replace the session's checklist (Linear's ``plan``, technology preview). The whole + * list goes on every call. + */ +export async function setAgentSessionPlan( + accessToken: string, + agentSessionId: string, + steps: readonly { readonly content: string; readonly status: string }[], +): Promise { + return graphqlRequest(accessToken, AGENT_SESSION_UPDATE_MUTATION, { id: agentSessionId, input: { plan: steps } }); +} + export interface AgentSessionIssue { readonly id: string; readonly identifier: string | null; diff --git a/cdk/src/handlers/shared/linear-session-checklist.ts b/cdk/src/handlers/shared/linear-session-checklist.ts new file mode 100644 index 000000000..a48d4940b --- /dev/null +++ b/cdk/src/handlers/shared/linear-session-checklist.ts @@ -0,0 +1,133 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * The session checklist (Linear's ``AgentSession.plan``) and the closing line of the + * session's final message (#1066). Pure: the fan-out consumer does the writes. + * + * The checklist lists the stages a person cares about, from understanding the ticket + * to "ready for your review". Its position is kept on the task record + * (``linear_checklist_stage``), so it only moves forward whichever Lambda instance + * sees an event. + * + * The ``plan`` shape follows the Linear developer docs ("Agent Plans", technology + * preview): the whole list, replaced on every update, each step + * ``{ content, status: 'pending' | 'inProgress' | 'completed' | 'canceled' }``. + */ + +export type ChecklistStepStatus = 'pending' | 'inProgress' | 'completed' | 'canceled'; + +export interface ChecklistStep { + readonly content: string; + readonly status: ChecklistStepStatus; +} + +/** A new change, or an update to an existing pull request. */ +export type ChecklistKind = 'new' | 'iteration'; + +const PR_ITERATION_WORKFLOW = 'coding/pr-iteration-v1'; +const NEW_TASK_WORKFLOW = 'coding/new-task-v1'; + +/** Stage positions (the index of the step in progress). */ +export const CHECKLIST_STAGE = { understand: 0, setup: 1, code: 2, pr: 3, review: 4 } as const; + +const LABELS: Readonly> = { + new: ['Understand the ticket', 'Set up the repository', 'Write the code', 'Open the pull request', 'Ready for your review'], + iteration: ['Read the request', 'Set up the repository', 'Update the code', 'Push to the pull request', 'Ready for your review'], +}; + +/** + * The checklist a task's session gets, or null for a workflow that has no such stages + * (a repo-less workflow, a review). Records that predate ``resolved_workflow`` are coding tasks. + * @param workflowId - the task's resolved workflow id. + */ +export function checklistKind(workflowId: string | undefined): ChecklistKind | null { + if (workflowId === PR_ITERATION_WORKFLOW) return 'iteration'; + if (workflowId === undefined || workflowId === NEW_TASK_WORKFLOW) return 'new'; + return null; +} + +/** Where the checklist stands. */ +export interface ChecklistState { + readonly stage: number; + /** A few words on the step in progress ("queued for a free slot"). */ + readonly note?: string; + /** ``#12`` once the pull request exists. */ + readonly pr?: string; +} + +/** How the task ended: every step done, or the step in progress and the rest cancelled. */ +export type ChecklistEnding = 'done' | 'stopped'; + +/** + * The steps for ``state``: steps before the stage are completed, the stage is in + * progress (with its note), the rest are pending. + * @param kind - which wording. + * @param state - the stage, note and pull request. + * @param ending - set on the task's last write. + */ +export function renderChecklist(kind: ChecklistKind, state: ChecklistState, ending?: ChecklistEnding): ChecklistStep[] { + const labels = LABELS[kind]; + const stage = ending === 'done' ? labels.length : Math.max(0, Math.min(state.stage, labels.length - 1)); + return labels.map((label, i) => { + let status: ChecklistStepStatus = 'pending'; + if (i < stage) status = 'completed'; + else if (ending === 'stopped') status = 'canceled'; + else if (i === stage) status = 'inProgress'; + const extra = [i === CHECKLIST_STAGE.pr ? state.pr : undefined, i === stage ? state.note : undefined] + .filter((s): s is string => Boolean(s)).join(' · '); + return { content: extra ? `${label} — ${extra}` : label, status }; + }); +} + +/** + * Where an event moves the checklist, or null when it does not. + * @param effectiveType - the event type, or a milestone's name. + * @param prUrl - the task's pull request, for ``pr_created``. + */ +export function checklistMoveForEvent(effectiveType: string, prUrl?: string): ChecklistState | null { + switch (effectiveType) { + case 'admission_queued': return { stage: CHECKLIST_STAGE.understand, note: 'queued for a free slot' }; + case 'hydration_complete': return { stage: CHECKLIST_STAGE.setup }; + case 'repo_setup_complete': return { stage: CHECKLIST_STAGE.code }; + case 'agent_execution_complete': return { stage: CHECKLIST_STAGE.pr }; + case 'pr_created': { + const n = prUrl?.match(/\/pull\/(\d+)/)?.[1]; + return { stage: CHECKLIST_STAGE.review, ...(n && { pr: `#${n}` }) }; + } + default: return null; + } +} + +/** How a finished task reads to the person who asked for it. */ +export type SessionOutcome = 'pr' | 'question' | 'no_change' | 'cancelled' | 'failed'; + +/** + * The last line of the session's final message: whether the reader has to act. + * @param outcome - how the task ended. + */ +export function closingLine(outcome: SessionOutcome): string { + switch (outcome) { + case 'pr': return '_Your turn: review the pull request. Reply here if it needs changes._'; + case 'question': return '**Waiting on you.** Nothing continues until you reply here.'; + case 'no_change': return '_Nothing needed from you. Reply here if you want a change after all._'; + case 'cancelled': return '_Nothing needed from you. Reply here to start again._'; + case 'failed': return '_Reply here to try again._'; + } +} diff --git a/cdk/src/handlers/shared/linear-session-progress.ts b/cdk/src/handlers/shared/linear-session-progress.ts new file mode 100644 index 000000000..e92930a96 --- /dev/null +++ b/cdk/src/handlers/shared/linear-session-progress.ts @@ -0,0 +1,212 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Task progress → Linear agent-session activities (ADR-018, #1066). + * + * The session already shows the acknowledgement, the PR, a throttled keep-alive and the + * final outcome (fanout-task-events.ts). This maps the events in between onto + * activities, so a run is visible while it happens: + * + * - the agent's own messages become persistent thoughts; + * - tool calls become an ephemeral action: the "currently doing" line, replaced + * by the next one rather than stacking up; + * - platform steps (queued, sandbox, context, clone) and agent milestones become + * persistent steps, except the queue and sandbox lines, which are ephemeral. + * + * Pure: no I/O. The dispatcher decides what to emit, caps the persistent ones per task + * and keeps them idempotent. + */ + +import { createHash } from 'node:crypto'; +import type { AgentActivityContent } from './linear-agent-session'; + +/** One activity to emit; ephemeral ones are replaced by the session's next activity. */ +export interface SessionProgressActivity { + readonly content: AgentActivityContent; + readonly ephemeral: boolean; +} + +/** + * Event types (as routed: an agent_milestone carries its milestone name) that matter + * only to agent sessions. The comment path ignores them, and the fan-out counts them + * apart from the events every channel needs, so a burst of them never pushes a PR or a + * terminal event out of a batch. + */ +export const LINEAR_SESSION_PROGRESS_EVENTS: ReadonlySet = new Set([ + 'agent_turn', + 'agent_tool_call', + 'admission_queued', + 'hydration_complete', + 'repo_setup_complete', + 'nudge_acknowledged', + 'attachments_downloaded', + 'agent_execution_complete', +]); + +/** Milestones the session uses; each must also be routable by name (ROUTABLE_MILESTONES). */ +export const LINEAR_SESSION_PROGRESS_MILESTONES: readonly string[] = [ + 'repo_setup_complete', + 'nudge_acknowledged', + 'attachments_downloaded', + // No activity of its own: it moves the session checklist to "Open the pull request". + 'agent_execution_complete', +]; + +const THOUGHT_MAX = 600; +const TOOL_PARAMETER_MAX = 120; +const BRANCH_MAX = 80; +const UUID_VARIANTS = '89ab'; +const HEX = 16; +/** The first 32 hex digits of a digest, grouped as a UUID's fields (the version nibble dropped). */ +const UUID_LAYOUT = /^(.{8})(.{4}).(.{3})(.)(.{3})(.{12}).*$/; + +function clip(value: string, max: number): string { + const flat = value.replace(/\s+/g, ' ').trim(); + return flat.length <= max ? flat : `${flat.slice(0, max - 1).trimEnd()}…`; +} + +/** `k=v k=v` milestone details → a map (values without spaces). */ +function parseDetails(details: unknown): Record { + const out: Record = {}; + if (typeof details !== 'string') return out; + for (const m of details.matchAll(/(\w+)=(\S+)/g)) out[m[1]] = m[2]; + return out; +} + +/** + * One field of a tool-input preview. The agent writes the input dict's Python repr + * (`{'file_path': '...'}`), cut at a fixed length, so the field's string value is read + * directly, in either quote style, rather than parsed. + */ +function inputField(preview: unknown, keys: readonly string[]): string | undefined { + if (typeof preview !== 'string' || preview.length === 0) return undefined; + for (const k of keys) { + // Key and value quote independently: repr switches a value to double quotes when + // it contains a single quote. + const m = preview.match(new RegExp(`['"]${k}['"]\\s*:\\s*(['"])((?:(?!\\1)[^\\\\]|\\\\.)*)`)); + if (m?.[2]) return m[2].replace(/\\(['"])/g, '$1').replace(/\\n/g, ' '); + } + return undefined; +} + +const WORKSPACE_PREFIX = /\/workspace\/[^/\s'"]+\/?/g; + +/** `/workspace//src/app.ts` → `src/app.ts`. */ +function repoRelative(p: string): string { + return p.replace(WORKSPACE_PREFIX, ''); +} + +/** `cd /workspace/; npm test` → `npm test`. */ +function readableCommand(cmd: string): string { + return cmd.replace(/^\s*cd\s+\/workspace\/[^\s;&]+\s*(?:;|&&)\s*/, '').replace(WORKSPACE_PREFIX, ''); +} + +const TOOL_VERBS: Readonly> = { + Read: { action: 'Reading', keys: ['file_path', 'path'], path: true }, + Edit: { action: 'Editing', keys: ['file_path'], path: true }, + MultiEdit: { action: 'Editing', keys: ['file_path'], path: true }, + Write: { action: 'Writing', keys: ['file_path'], path: true }, + NotebookEdit: { action: 'Editing', keys: ['notebook_path'], path: true }, + Bash: { action: 'Running', keys: ['command'] }, + Grep: { action: 'Searching', keys: ['pattern'] }, + Glob: { action: 'Finding files', keys: ['pattern'] }, + WebFetch: { action: 'Fetching', keys: ['url'] }, + WebSearch: { action: 'Searching the web', keys: ['query'] }, + Task: { action: 'Delegating', keys: ['description'] }, + TodoWrite: { action: 'Updating its plan', keys: [] }, +}; + +function toolActivity(meta: Record): SessionProgressActivity | null { + const tool = typeof meta.tool_name === 'string' ? meta.tool_name : ''; + if (!tool) return null; + const verb = TOOL_VERBS[tool]; + if (!verb) { + // An MCP or unknown tool: name it, without guessing at its input. + return { content: { type: 'action', action: `Using ${clip(tool, TOOL_PARAMETER_MAX)}`, parameter: '' }, ephemeral: true }; + } + const raw = inputField(meta.tool_input_preview, verb.keys); + const value = raw === undefined ? '' : verb.path ? repoRelative(raw) : readableCommand(raw); + const parameter = value ? `\`${clip(value, TOOL_PARAMETER_MAX).replace(/`/g, "'")}\`` : ''; + return { content: { type: 'action', action: verb.action, parameter }, ephemeral: true }; +} + +function milestoneActivity(name: string, details: unknown): SessionProgressActivity | null { + const d = parseDetails(details); + switch (name) { + case 'repo_setup_complete': + return { + content: { type: 'action', action: 'Cloned the repository', parameter: d.branch ? `on branch \`${clip(d.branch, BRANCH_MAX)}\`` : '' }, + ephemeral: false, + }; + case 'attachments_downloaded': + return { content: { type: 'action', action: 'Read the issue attachments', parameter: d.count ? `${d.count} file(s)` : '' }, ephemeral: false }; + case 'nudge_acknowledged': + return { content: { type: 'thought', body: 'Picked up your message and working it in.' }, ephemeral: false }; + default: + return null; + } +} + +/** + * The activity for one progress event, or null when it has nothing to show. + * @param effectiveType - the routed type (an `agent_milestone` carries its milestone name). + * @param metadata - the event's metadata. + */ +export function sessionProgressActivity( + effectiveType: string, + metadata: Record | undefined, +): SessionProgressActivity | null { + const meta = metadata ?? {}; + switch (effectiveType) { + case 'agent_turn': { + const text = typeof meta.text_preview === 'string' ? meta.text_preview.trim() : ''; + return text ? { content: { type: 'thought', body: clip(text, THOUGHT_MAX) }, ephemeral: false } : null; + } + case 'agent_tool_call': + return toolActivity(meta); + case 'admission_queued': { + // Ephemeral: the admission reconciler re-emits it with `waited_s` while the task + // waits, which also keeps a long wait from turning the session stale. + const waitedMin = Math.round(Number(meta.waited_s) / 60); + const lead = Number.isFinite(waitedMin) && waitedMin > 0 ? `Still queued (${waitedMin} min so far)` : 'Queued'; + return { + content: { type: 'thought', body: `${lead}: you already have the maximum number of tasks running. This one starts as soon as one finishes.` }, + ephemeral: true, + }; + } + case 'hydration_complete': + return { content: { type: 'action', action: 'Gathered the issue context', parameter: '' }, ephemeral: false }; + default: + return milestoneActivity(effectiveType, meta.details); + } +} + +/** + * A deterministic activity id for an event, so a redelivered or re-run record emits the + * same activity rather than a second one. Linear accepts only version-4 UUIDs, so the + * hash gets the v4 version and variant bits. + * @param seed - unique per activity (the task event id). + */ +export function progressActivityId(seed: string): string { + const hex = createHash('sha256').update(`linear-session-progress:${seed}`).digest('hex'); + // 8-4-4-4-12 hex digits, with version nibble 4 and an RFC 4122 variant nibble (8, 9, a or b). + return hex.replace(UUID_LAYOUT, (_all, a: string, b: string, c: string, variant: string, d: string, e: string) => + `${a}-${b}-4${c}-${UUID_VARIANTS[Number.parseInt(variant, HEX) % UUID_VARIANTS.length]}${d}-${e}`); +} diff --git a/cdk/src/handlers/shared/types.ts b/cdk/src/handlers/shared/types.ts index b0d810d3a..ad7c42f69 100644 --- a/cdk/src/handlers/shared/types.ts +++ b/cdk/src/handlers/shared/types.ts @@ -342,6 +342,11 @@ export interface TaskRecord { * appended link is never duplicated. */ readonly linear_session_pr_link_event_id?: string; + /** + * Stage the Linear agent session's checklist has reached (#1066). Written with a + * forward-only conditional update, so the checklist never moves back. + */ + readonly linear_checklist_stage?: number; /** * Event ID of the terminal event whose ordinary Jira final-status comment * was successfully posted (fan-out plane). This marker makes that create diff --git a/cdk/test/handlers/fanout-linear-agent-session.test.ts b/cdk/test/handlers/fanout-linear-agent-session.test.ts index 3f25f5a0b..d054fa1f9 100644 --- a/cdk/test/handlers/fanout-linear-agent-session.test.ts +++ b/cdk/test/handlers/fanout-linear-agent-session.test.ts @@ -99,8 +99,10 @@ function mockTask(task: Record, updateError?: Error): void { }); } +/** Task-record writes, without the session checklist's stage (covered in fanout-linear-session-progress.test.ts). */ function updates(): Array<{ UpdateExpression: string; ConditionExpression?: string }> { - return mockDdbSend.mock.calls.filter((c) => c[0]._type === 'Update').map((c) => c[0].input); + return mockDdbSend.mock.calls.filter((c) => c[0]._type === 'Update').map((c) => c[0].input) + .filter((u) => !String(u.UpdateExpression).includes('linear_checklist_stage')); } beforeEach(() => { diff --git a/cdk/test/handlers/fanout-linear-session-progress.test.ts b/cdk/test/handlers/fanout-linear-session-progress.test.ts new file mode 100644 index 000000000..059a582b6 --- /dev/null +++ b/cdk/test/handlers/fanout-linear-session-progress.test.ts @@ -0,0 +1,258 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +// Session progress streamed by the fan-out Linear dispatcher (#1066). A separate file +// because the flag is read when the module builds CHANNEL_DEFAULTS, so it must be set +// before import. + +import type { DynamoDBRecord } from 'aws-lambda'; + +const mockDdbSend = jest.fn(); +jest.mock('@aws-sdk/client-dynamodb', () => ({ DynamoDBClient: jest.fn(() => ({})) })); +jest.mock('@aws-sdk/lib-dynamodb', () => ({ + DynamoDBDocumentClient: { from: jest.fn(() => ({ send: mockDdbSend })) }, + GetCommand: jest.fn((input: unknown) => ({ _type: 'Get', input })), + UpdateCommand: jest.fn((input: unknown) => ({ _type: 'Update', input })), + QueryCommand: jest.fn((input: unknown) => ({ _type: 'Query', input })), +})); + +const mockPostIssueComment = jest.fn().mockResolvedValue({ ok: true }); +const mockResolveToken = jest.fn(); +const mockTransitionIssueState = jest.fn().mockResolvedValue({ ok: true }); +jest.mock('../../src/handlers/shared/linear-feedback', () => ({ + transitionIssueState: (...args: unknown[]) => mockTransitionIssueState(...args), + postIssueComment: (...args: unknown[]) => mockPostIssueComment(...args), + replyToComment: jest.fn(), + upsertThreadedReply: jest.fn(), + swapCommentReaction: jest.fn(), + resolveToken: (...args: unknown[]) => mockResolveToken(...args), +})); + +const mockEmitAgentActivity = jest.fn(); +const mockSetPlan = jest.fn(); +jest.mock('../../src/handlers/shared/linear-agent-session', () => ({ + setAgentSessionPlan: (...args: unknown[]) => mockSetPlan(...args), + emitAgentActivity: (...args: unknown[]) => mockEmitAgentActivity(...args), + addAgentSessionExternalUrl: jest.fn().mockResolvedValue({ ok: true }), +})); + +process.env.LINEAR_AGENT_SESSIONS_ENABLED = 'true'; +process.env.TASK_TABLE_NAME = 'Tasks'; +process.env.LINEAR_WORKSPACE_REGISTRY_TABLE_NAME = 'LinearWorkspaceRegistry'; + +import { + CHANNEL_DEFAULTS, + resetLinearHeartbeatMemoForTests, + routeEvent, + supersededToolCallIds, + type FanOutEvent, + type TaskNotificationsConfig, +} from '../../src/handlers/fanout-task-events'; +import { progressActivityId } from '../../src/handlers/shared/linear-session-progress'; + +const LINEAR_ONLY: TaskNotificationsConfig = { + slack: { enabled: false }, github: { enabled: false }, jira: { enabled: false }, email: { enabled: false }, +} as TaskNotificationsConfig; + +const SESSION_TASK = { + task_id: 't-sess', + user_id: 'u-1', + status: 'RUNNING', + repo: 'acme/web', + channel_source: 'linear', + channel_metadata: { linear_issue_id: 'issue-1', linear_workspace_id: 'org-1', linear_agent_session_id: 'session-1' }, +}; +const COMMENT_TASK = { ...SESSION_TASK, channel_metadata: { linear_issue_id: 'issue-1', linear_workspace_id: 'org-1' } }; + +function ev(eventType: string, metadata?: Record, eventId = `e-${eventType}`): FanOutEvent { + return { task_id: 't-sess', event_id: eventId, event_type: eventType, timestamp: '2026-11-20T00:00:00Z', metadata }; +} + +/** Get → the task; Update (the progress slot) → succeeds unless `updateError` is set. */ +function mockTask(task: Record, updateError?: Error): void { + mockDdbSend.mockReset().mockImplementation(async (cmd: { _type: string }) => { + if (cmd._type === 'Get') return { Item: task }; + if (cmd._type === 'Update' && updateError) throw updateError; + return {}; + }); +} +const updates = () => mockDdbSend.mock.calls.filter((c) => c[0]._type === 'Update').map((c) => c[0].input); + +beforeEach(() => { + mockPostIssueComment.mockClear(); + mockResolveToken.mockReset().mockResolvedValue('lin_tok'); + mockEmitAgentActivity.mockReset().mockResolvedValue({ ok: true }); + mockSetPlan.mockReset().mockResolvedValue({ ok: true }); + mockTransitionIssueState.mockClear(); + resetLinearHeartbeatMemoForTests(); +}); + +test('the flag subscribes the Linear channel to the progress events', () => { + for (const type of ['agent_turn', 'agent_tool_call', 'admission_queued', 'hydration_complete', 'repo_setup_complete', 'nudge_acknowledged', 'attachments_downloaded', 'agent_execution_complete']) { + expect(CHANNEL_DEFAULTS.linear.has(type)).toBe(true); + } +}); + +test('a tool call is an ephemeral action with a deterministic id, and takes no persistent slot', async () => { + mockTask(SESSION_TASK); + const outcome = await routeEvent(ev('agent_tool_call', { tool_name: 'Read', tool_input_preview: "{'file_path': '/workspace/t-sess/src/app.ts'}" }), LINEAR_ONLY); + expect(outcome.infraRejections).toEqual([]); + expect(mockEmitAgentActivity).toHaveBeenCalledWith('lin_tok', 'session-1', + { type: 'action', action: 'Reading', parameter: '`src/app.ts`' }, + { ephemeral: true, id: progressActivityId('e-agent_tool_call') }); + expect(updates()).toEqual([]); +}); + +test("the agent's message is a persistent thought that claims one of the task's progress slots", async () => { + mockTask(SESSION_TASK); + await routeEvent(ev('agent_turn', { text_preview: 'Found it: the parser drops the last token.' }), LINEAR_ONLY); + expect(updates()).toEqual([expect.objectContaining({ UpdateExpression: 'ADD linear_session_progress_count :one' })]); + expect(mockEmitAgentActivity).toHaveBeenCalledWith('lin_tok', 'session-1', + { type: 'thought', body: 'Found it: the parser drops the last token.' }, expect.objectContaining({ ephemeral: false })); +}); + +test('past the cap, persistent progress is dropped; the stream never throws', async () => { + mockTask(SESSION_TASK, Object.assign(new Error('cap'), { name: 'ConditionalCheckFailedException' })); + const capped = await routeEvent(ev('hydration_complete'), LINEAR_ONLY); + expect(capped.infraRejections).toEqual([]); + expect(mockEmitAgentActivity).not.toHaveBeenCalled(); + + mockTask(SESSION_TASK); + mockEmitAgentActivity.mockResolvedValueOnce({ ok: false, retryable: true }); + const failed = await routeEvent(ev('agent_tool_call', { tool_name: 'Bash', tool_input_preview: "{'command': 'ls'}" }), LINEAR_ONLY); + expect(failed.infraRejections).toEqual([]); // best effort: no batch retry +}); + +test('nothing is posted once the session has closed, so a late event cannot reopen it', async () => { + for (const task of [{ ...SESSION_TASK, linear_final_comment_event_id: 'e-done' }, { ...SESSION_TASK, status: 'COMPLETED' }]) { + mockTask(task); + mockEmitAgentActivity.mockClear(); + await routeEvent(ev('agent_tool_call', { tool_name: 'Bash', tool_input_preview: "{'command': 'ls'}" }), LINEAR_ONLY); + expect(mockEmitAgentActivity).not.toHaveBeenCalled(); + } +}); + +test('a comment-path Linear task ignores progress milestones (no PR-opened comment from nudge_acknowledged)', async () => { + mockTask({ ...COMMENT_TASK, pr_url: 'https://github.com/acme/web/pull/7' }); + await routeEvent(ev('agent_milestone', { milestone: 'nudge_acknowledged' }), LINEAR_ONLY); + expect(mockPostIssueComment).not.toHaveBeenCalled(); + expect(mockEmitAgentActivity).not.toHaveBeenCalled(); +}); + +test('a task known not to be a session task skips the task read for later progress events', async () => { + mockTask(COMMENT_TASK); + await routeEvent(ev('agent_tool_call', { tool_name: 'Bash' }, 'e-1'), LINEAR_ONLY); + const readsAfterFirst = mockDdbSend.mock.calls.filter((c) => c[0]._type === 'Get').length; + await routeEvent(ev('agent_tool_call', { tool_name: 'Bash' }, 'e-2'), LINEAR_ONLY); + expect(mockDdbSend.mock.calls.filter((c) => c[0]._type === 'Get').length).toBe(readsAfterFirst); +}); + +function toolCallRecord(taskId: string, eventId: string): DynamoDBRecord { + return { + eventID: eventId, + eventName: 'INSERT', + eventSource: 'aws:dynamodb', + dynamodb: { + SequenceNumber: `seq-${eventId}`, + NewImage: { + task_id: { S: taskId }, + event_id: { S: eventId }, + event_type: { S: 'agent_tool_call' }, + timestamp: { S: '2026-11-20T00:00:00Z' }, + metadata: { M: { tool_name: { S: 'Bash' } } }, + }, + }, + } as unknown as DynamoDBRecord; +} + +test('only the newest tool call of each task in a batch is kept', () => { + const records = [toolCallRecord('a', 'a1'), toolCallRecord('b', 'b1'), toolCallRecord('a', 'a2'), toolCallRecord('a', 'a3')]; + expect([...supersededToolCallIds(records)].sort()).toEqual(['a1', 'a2']); +}); + +// --- The session checklist, the closing line and In Review --- + +const planStatuses = () => (mockSetPlan.mock.calls.at(-1)?.[2] as Array<{ status: string }>).map((s) => s.status); +const stageWrites = () => updates().filter((u) => String(u.UpdateExpression).includes('linear_checklist_stage')); + +test('a step that moves the checklist forward records the stage, then replaces the session plan', async () => { + mockTask(SESSION_TASK); + await routeEvent(ev('agent_milestone', { milestone: 'repo_setup_complete' }), LINEAR_ONLY); + expect(stageWrites()).toEqual([expect.objectContaining({ ExpressionAttributeValues: { ':s': 2 } })]); + expect(mockSetPlan).toHaveBeenCalledWith('lin_tok', 'session-1', expect.any(Array)); + expect(planStatuses()).toEqual(['completed', 'completed', 'inProgress', 'pending', 'pending']); +}); + +test('the checklist never moves back: a stale step loses the conditional write and is not shown', async () => { + mockTask({ ...SESSION_TASK, linear_checklist_stage: 3 }, Object.assign(new Error('stale'), { name: 'ConditionalCheckFailedException' })); + await routeEvent(ev('hydration_complete'), LINEAR_ONLY); + expect(mockSetPlan).not.toHaveBeenCalled(); +}); + +test('the agent finishing moves the checklist to the pull request step, with no activity of its own', async () => { + mockTask(SESSION_TASK); + await routeEvent(ev('agent_milestone', { milestone: 'agent_execution_complete' }), LINEAR_ONLY); + expect(planStatuses()).toEqual(['completed', 'completed', 'completed', 'inProgress', 'pending']); + expect(mockEmitAgentActivity).not.toHaveBeenCalled(); +}); + +test('a workflow without coding stages gets no checklist', async () => { + mockTask({ ...SESSION_TASK, resolved_workflow: { id: 'review/pr-review-v1', version: '1' } }); + await routeEvent(ev('hydration_complete'), LINEAR_ONLY); + expect(mockSetPlan).not.toHaveBeenCalled(); +}); + +const PR_URL = 'https://github.com/acme/web/pull/7'; + +test('a task that ends with a pull request completes the checklist, says what is next, and moves the issue to In Review', async () => { + mockTask({ ...SESSION_TASK, status: 'COMPLETED', pr_url: PR_URL, linear_checklist_stage: 4 }); + await routeEvent(ev('task_completed'), LINEAR_ONLY); + expect(planStatuses()).toEqual(Array(5).fill('completed')); + const final = mockEmitAgentActivity.mock.calls.at(-1)?.[2] as { type: string; body: string }; + expect(final.type).toBe('response'); + expect(final.body).toMatch(/_Your turn: review the pull request\. Reply here if it needs changes\._$/); + expect(mockTransitionIssueState).toHaveBeenCalledWith(expect.anything(), 'issue-1', 'started', ['In Review']); +}); + +test('a failed task cancels what was left, offers a retry, and leaves the issue where it is', async () => { + mockTask({ ...SESSION_TASK, status: 'FAILED', linear_checklist_stage: 2, error_message: 'boom' }); + await routeEvent(ev('task_failed'), LINEAR_ONLY); + expect(planStatuses()).toEqual(['completed', 'completed', 'canceled', 'canceled', 'canceled']); + expect((mockEmitAgentActivity.mock.calls.at(-1)?.[2] as { body: string }).body).toMatch(/_Reply here to try again\._$/); + expect(mockTransitionIssueState).not.toHaveBeenCalled(); +}); + +test('a run that stopped to ask a question waits on the reader, and the checklist says so', async () => { + mockTask({ ...SESSION_TASK, status: 'COMPLETED', code_changed: false, answer_text: 'Which page?', linear_checklist_stage: 2 }); + await routeEvent(ev('task_completed'), LINEAR_ONLY); + const final = mockEmitAgentActivity.mock.calls.at(-1)?.[2] as { type: string; body: string }; + expect(final.type).toBe('elicitation'); + expect(final.body).toMatch(/\*\*Waiting on you\.\*\* Nothing continues until you reply here\.$/); + const plan = mockSetPlan.mock.calls.at(-1)?.[2] as Array<{ content: string; status: string }>; + expect(plan[2]).toEqual({ content: 'Write the code — waiting on your answer', status: 'inProgress' }); + expect(mockTransitionIssueState).not.toHaveBeenCalled(); +}); + +test('a failed checklist write never blocks the final response', async () => { + mockTask({ ...SESSION_TASK, status: 'COMPLETED', pr_url: PR_URL }); + mockSetPlan.mockRejectedValueOnce(new Error('linear down')); + const outcome = await routeEvent(ev('task_completed'), LINEAR_ONLY); + expect(outcome.infraRejections).toEqual([]); + expect(mockEmitAgentActivity).toHaveBeenCalledWith('lin_tok', 'session-1', expect.objectContaining({ type: 'response' })); +}); diff --git a/cdk/test/handlers/reconcile-admission-queue.test.ts b/cdk/test/handlers/reconcile-admission-queue.test.ts index 6d3983fe3..597c84997 100644 --- a/cdk/test/handlers/reconcile-admission-queue.test.ts +++ b/cdk/test/handlers/reconcile-admission-queue.test.ts @@ -47,7 +47,7 @@ process.env.MAX_CONCURRENT_TASKS_PER_USER = '3'; process.env.QUEUE_MAX_AGE_SECONDS = '86400'; process.env.TASK_RETENTION_DAYS = '90'; -import { handler } from '../../src/handlers/reconcile-admission-queue'; +import { handler, isQueueHeartbeatDue } from '../../src/handlers/reconcile-admission-queue'; /** A QUEUED StatusIndex row as the DDB low-level client returns it. */ function queuedRow(opts: { @@ -481,3 +481,58 @@ describe('reconcile-admission-queue — #331 regression (fan-out burst)', () => expect(flipped).toEqual(['P1', 'P2']); }); }); + +describe('reconcile-admission-queue — queue heartbeat (#1066)', () => { + test('each 15-minute mark fires once on the 1-minute schedule', () => { + expect(isQueueHeartbeatDue(0)).toBe(false); + expect(isQueueHeartbeatDue(899)).toBe(false); + expect(isQueueHeartbeatDue(900)).toBe(true); + expect(isQueueHeartbeatDue(959)).toBe(true); + expect(isQueueHeartbeatDue(960)).toBe(false); + expect(isQueueHeartbeatDue(1800)).toBe(true); + }); + + test('a task still waiting past a mark gets an admission_queued event with waited_s', async () => { + mockDdbSend.mockImplementation((cmd: SentCommand) => { + if (cmd._type === 'Query') { + return Promise.resolve({ + Items: [ + queuedRow({ task_id: 'LONG', user_id: 'u1', created_at: isoAge(920) }), + queuedRow({ task_id: 'FRESH', user_id: 'u1', created_at: isoAge(120) }), + ], + }); + } + if (cmd._type === 'GetItem') return Promise.resolve({ Item: { active_count: { N: '3' } } }); // full + return Promise.resolve({}); + }); + + await handler(); + const puts = sentDdbCommands('PutItem').map(c => c.input.Item); + expect(puts).toHaveLength(1); + expect(puts[0].task_id).toEqual({ S: 'LONG' }); + expect(puts[0].event_type).toEqual({ S: 'admission_queued' }); + expect(puts[0].metadata.M.reason).toEqual({ S: 'concurrency_limit' }); + expect(Number(puts[0].metadata.M.waited_s.N)).toBeGreaterThanOrEqual(920); + expect(mockLambdaSend).not.toHaveBeenCalled(); + }); + + test('picked-up tasks get no heartbeat; the ones left behind do', async () => { + mockDdbSend.mockImplementation((cmd: SentCommand) => { + if (cmd._type === 'Query') { + return Promise.resolve({ + Items: [ + queuedRow({ task_id: 'FIRST', user_id: 'u1', created_at: isoAge(930) }), + queuedRow({ task_id: 'SECOND', user_id: 'u1', created_at: isoAge(920) }), + ], + }); + } + if (cmd._type === 'GetItem') return Promise.resolve({ Item: { active_count: { N: '2' } } }); // one slot + return Promise.resolve({}); + }); + mockLambdaSend.mockResolvedValue({ StatusCode: 202 }); + + await handler(); + const heartbeats = sentDdbCommands('PutItem').map(c => c.input.Item).filter(i => i.event_type.S === 'admission_queued'); + expect(heartbeats.map(i => i.task_id.S)).toEqual(['SECOND']); + }); +}); diff --git a/cdk/test/handlers/shared/linear-session-checklist.test.ts b/cdk/test/handlers/shared/linear-session-checklist.test.ts new file mode 100644 index 000000000..08a233ec9 --- /dev/null +++ b/cdk/test/handlers/shared/linear-session-checklist.test.ts @@ -0,0 +1,69 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { + CHECKLIST_STAGE, + checklistKind, + checklistMoveForEvent, + closingLine, + renderChecklist, +} from '../../../src/handlers/shared/linear-session-checklist'; + +const statuses = (steps: ReturnType) => steps.map((s) => s.status); + +test('coding tasks get a checklist, other workflows do not', () => { + expect(checklistKind('coding/new-task-v1')).toBe('new'); + expect(checklistKind(undefined)).toBe('new'); + expect(checklistKind('coding/pr-iteration-v1')).toBe('iteration'); + expect(checklistKind('review/pr-review-v1')).toBeNull(); +}); + +test('steps before the stage are done, the stage is in progress with its note', () => { + const steps = renderChecklist('new', { stage: CHECKLIST_STAGE.code, note: 'round 2' }); + expect(statuses(steps)).toEqual(['completed', 'completed', 'inProgress', 'pending', 'pending']); + expect(steps[2].content).toBe('Write the code — round 2'); +}); + +test('the pull request number stays on its step once it exists', () => { + const steps = renderChecklist('iteration', { stage: CHECKLIST_STAGE.review, pr: '#7' }); + expect(steps[3].content).toBe('Push to the pull request — #7'); + expect(steps[4]).toEqual({ content: 'Ready for your review', status: 'inProgress' }); +}); + +test('a finished task completes every step; a stopped one cancels what was left', () => { + expect(statuses(renderChecklist('new', { stage: CHECKLIST_STAGE.review }, 'done'))).toEqual(Array(5).fill('completed')); + expect(statuses(renderChecklist('new', { stage: CHECKLIST_STAGE.code }, 'stopped'))) + .toEqual(['completed', 'completed', 'canceled', 'canceled', 'canceled']); +}); + +test('events move the checklist to their stage; others do not move it', () => { + expect(checklistMoveForEvent('admission_queued')).toEqual({ stage: CHECKLIST_STAGE.understand, note: 'queued for a free slot' }); + expect(checklistMoveForEvent('hydration_complete')).toEqual({ stage: CHECKLIST_STAGE.setup }); + expect(checklistMoveForEvent('repo_setup_complete')).toEqual({ stage: CHECKLIST_STAGE.code }); + expect(checklistMoveForEvent('agent_execution_complete')).toEqual({ stage: CHECKLIST_STAGE.pr }); + expect(checklistMoveForEvent('pr_created', 'https://github.com/acme/web/pull/42')).toEqual({ stage: CHECKLIST_STAGE.review, pr: '#42' }); + expect(checklistMoveForEvent('agent_tool_call')).toBeNull(); +}); + +test('the closing line says whether the reader has to act', () => { + expect(closingLine('question')).toMatch(/^\*\*Waiting on you\.\*\*/); + expect(closingLine('pr')).toContain('review the pull request'); + for (const o of ['no_change', 'cancelled'] as const) expect(closingLine(o)).toContain('Nothing needed from you'); + expect(closingLine('failed')).toContain('try again'); +}); diff --git a/cdk/test/handlers/shared/linear-session-progress.test.ts b/cdk/test/handlers/shared/linear-session-progress.test.ts new file mode 100644 index 000000000..67f2e77b8 --- /dev/null +++ b/cdk/test/handlers/shared/linear-session-progress.test.ts @@ -0,0 +1,71 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { progressActivityId, sessionProgressActivity } from '../../../src/handlers/shared/linear-session-progress'; + +describe('sessionProgressActivity (#1066)', () => { + test('tool calls are an ephemeral "currently doing" line with a readable input', () => { + // The agent's tool_input_preview is the input dict's Python repr, cut at a fixed length. + expect(sessionProgressActivity('agent_tool_call', { tool_name: 'Read', tool_input_preview: "{'file_path': '/workspace/t-1/src/app.ts'}" })) + .toEqual({ content: { type: 'action', action: 'Reading', parameter: '`src/app.ts`' }, ephemeral: true }); + expect(sessionProgressActivity('agent_tool_call', { tool_name: 'Bash', tool_input_preview: "{'command': 'cd /workspace/t-1; npm test', 'description'" })) + .toEqual({ content: { type: 'action', action: 'Running', parameter: '`npm test`' }, ephemeral: true }); + // repr switches a value to double quotes when it contains a single quote. + expect(sessionProgressActivity('agent_tool_call', { tool_name: 'Grep', tool_input_preview: "{'pattern': \"don't\"}" })?.content) + .toEqual({ type: 'action', action: 'Searching', parameter: "`don't`" }); + // An MCP or unknown tool is named, and its input is not guessed at. + expect(sessionProgressActivity('agent_tool_call', { tool_name: 'mcp__gateway__lookup', tool_input_preview: '{}' })?.content) + .toEqual({ type: 'action', action: 'Using mcp__gateway__lookup', parameter: '' }); + expect(sessionProgressActivity('agent_tool_call', {})).toBeNull(); + }); + + test("the agent's own message is a persistent thought; a turn without text is nothing", () => { + expect(sessionProgressActivity('agent_turn', { text_preview: ' I found the bug in the parser. ' })) + .toEqual({ content: { type: 'thought', body: 'I found the bug in the parser.' }, ephemeral: false }); + expect((sessionProgressActivity('agent_turn', { text_preview: 'x'.repeat(2000) })?.content as { body: string }).body).toHaveLength(600); + expect(sessionProgressActivity('agent_turn', { text_preview: ' ', thinking_preview: 'private' })).toBeNull(); + }); + + test('queueing is ephemeral and says how long the task has waited', () => { + expect(sessionProgressActivity('admission_queued', { reason: 'concurrency_limit' })?.content) + .toMatchObject({ type: 'thought', body: expect.stringMatching(/^Queued: /) }); + const still = sessionProgressActivity('admission_queued', { waited_s: 1800 }); + expect(still?.ephemeral).toBe(true); + expect((still?.content as { body: string }).body).toMatch(/^Still queued \(30 min so far\): /); + }); + + test('platform steps and agent milestones are persistent steps', () => { + expect(sessionProgressActivity('hydration_complete', {})).toEqual({ + content: { type: 'action', action: 'Gathered the issue context', parameter: '' }, ephemeral: false, + }); + expect(sessionProgressActivity('repo_setup_complete', { details: 'branch=bgagent/t-1/fix-parser build_before=pass' })?.content) + .toEqual({ type: 'action', action: 'Cloned the repository', parameter: 'on branch `bgagent/t-1/fix-parser`' }); + expect(sessionProgressActivity('attachments_downloaded', { details: 'count=2' })?.content) + .toEqual({ type: 'action', action: 'Read the issue attachments', parameter: '2 file(s)' }); + expect(sessionProgressActivity('nudge_acknowledged', {})?.content).toEqual({ type: 'thought', body: 'Picked up your message and working it in.' }); + expect(sessionProgressActivity('trajectory_uploaded', {})).toBeNull(); + }); + + test('activity ids are deterministic version-4 UUIDs (Linear rejects other versions)', () => { + const id = progressActivityId('evt-1'); + expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + expect(progressActivityId('evt-1')).toBe(id); + expect(progressActivityId('evt-2')).not.toBe(id); + }); +}); diff --git a/docs/guides/LINEAR_SETUP_GUIDE.md b/docs/guides/LINEAR_SETUP_GUIDE.md index 726e9632a..17eb08418 100644 --- a/docs/guides/LINEAR_SETUP_GUIDE.md +++ b/docs/guides/LINEAR_SETUP_GUIDE.md @@ -231,10 +231,12 @@ If you do these the other way round, every mention in the meantime opens a sessi | You do in Linear | ABCA does | |---|---| | @-mention bgagent on an issue, or delegate the issue to it | Acknowledges within seconds with a *thought*, then starts a coding task on the project's mapped repo. If the issue already has an ABCA pull request and your mention carries an instruction, it iterates on that PR instead. The session shows **Started coding task** or **Iterating on pull request**. | +| — the task runs | Keeps the session's checklist current: *Understand the ticket*, *Set up the repository*, *Write the code*, *Open the pull request*, *Ready for your review* (an update to an existing PR has its own wording). The checklist only moves forward. | +| — the agent works | Shows what it's doing right now as one line that the next one replaces ("Reading `src/app.ts`", "Running `npm test`"), the agent's own messages, and its setup steps (issue context gathered, repository cloned, your nudge picked up). At most 30 lasting entries per task; the one-line updates don't count. | | — the agent opens a PR | Attaches the pull request to the session header and posts an **Opened pull request** action. | | — a long run is in progress | Posts a short-lived "Still working" thought at most every 10 minutes, so the session never goes stale (Linear's idle limit is 30 minutes). | -| — the task finishes | Posts one final activity carrying the same outcome, cost, turns and duration as the comment channel: a *response* on success, an *elicitation* if the run stopped to ask you a question, an *error* on failure. Linear turns it into the thread comment. | -| — you're at your concurrency limit | Posts a "Queued" thought in the session. The task starts on its own when a slot frees up. | +| — the task finishes | Posts one final activity carrying the same outcome, cost, turns and duration as the comment channel: a *response* on success, an *elicitation* if the run stopped to ask you a question, an *error* on failure. Its last line says whether you need to do anything. Linear turns it into the thread comment. A task that ends with a pull request moves the issue to *In Review*. | +| — you're at your concurrency limit | Posts a "Queued" thought in the session, and "Still queued (N min so far)" every 15 minutes. The task starts on its own when a slot frees up. | | Reply inside the session while the task runs | Your message goes to the running agent as a nudge (the same guardrail screening, 2,000-character cap and per-minute limit as `bgagent nudge`). The agent picks it up at its next step. Only the task's owner can steer it. | | Reply after the task has finished | Starts a follow-up task. If the run stopped to ask a question, your reply resumes the original request with the answer. Otherwise it's a PR iteration if a PR exists, or new work from your message plus the issue. | | Click **Stop** in the session | Cancels the running task and shuts its agent down, like `bgagent cancel`, then confirms with a final response. Only the task's owner can stop it. | @@ -245,9 +247,9 @@ If you do these the other way round, every mention in the meantime opens a sessi **Who can act.** Every session request, `stop` included, needs a linked ABCA user ([Inviting teammates](#inviting-teammates)). An unlinked user is told to link their account and nothing runs. A refusal closes the session it was made in, unless that is the session a running task reports into; there it's a note, so someone else's run isn't marked finished or failed. A new task is attributed to whoever asked for it. Steering or stopping a *running* task follows the API's rule: only its owner can do it. -**Reactions.** A session task gets no 👀/✅/❌ reactions on the issue, since the session shows that state. The issue still moves to *In Progress* and *In Review*. +**Reactions.** A session task gets no 👀/✅/❌ reactions on the issue, since the session shows that state. The issue still moves to *In Progress* when work starts, and to *In Review* when the task ends with a pull request. -**Not yet supported in sessions:** image and file attachments from the issue description (use a label trigger for those), and Linear's *plan* checklist. +**Not yet supported in sessions:** image and file attachments from the issue description (use a label trigger for those). ## Adding another workspace diff --git a/docs/src/content/docs/using/Linear-setup-guide.md b/docs/src/content/docs/using/Linear-setup-guide.md index 1fb4f5110..ce9d2847e 100644 --- a/docs/src/content/docs/using/Linear-setup-guide.md +++ b/docs/src/content/docs/using/Linear-setup-guide.md @@ -233,10 +233,12 @@ If you do these the other way round, every mention in the meantime opens a sessi | You do in Linear | ABCA does | |---|---| | @-mention bgagent on an issue, or delegate the issue to it | Acknowledges within seconds with a *thought*, then starts a coding task on the project's mapped repo. If the issue already has an ABCA pull request and your mention carries an instruction, it iterates on that PR instead. The session shows **Started coding task** or **Iterating on pull request**. | +| — the task runs | Keeps the session's checklist current: *Understand the ticket*, *Set up the repository*, *Write the code*, *Open the pull request*, *Ready for your review* (an update to an existing PR has its own wording). The checklist only moves forward. | +| — the agent works | Shows what it's doing right now as one line that the next one replaces ("Reading `src/app.ts`", "Running `npm test`"), the agent's own messages, and its setup steps (issue context gathered, repository cloned, your nudge picked up). At most 30 lasting entries per task; the one-line updates don't count. | | — the agent opens a PR | Attaches the pull request to the session header and posts an **Opened pull request** action. | | — a long run is in progress | Posts a short-lived "Still working" thought at most every 10 minutes, so the session never goes stale (Linear's idle limit is 30 minutes). | -| — the task finishes | Posts one final activity carrying the same outcome, cost, turns and duration as the comment channel: a *response* on success, an *elicitation* if the run stopped to ask you a question, an *error* on failure. Linear turns it into the thread comment. | -| — you're at your concurrency limit | Posts a "Queued" thought in the session. The task starts on its own when a slot frees up. | +| — the task finishes | Posts one final activity carrying the same outcome, cost, turns and duration as the comment channel: a *response* on success, an *elicitation* if the run stopped to ask you a question, an *error* on failure. Its last line says whether you need to do anything. Linear turns it into the thread comment. A task that ends with a pull request moves the issue to *In Review*. | +| — you're at your concurrency limit | Posts a "Queued" thought in the session, and "Still queued (N min so far)" every 15 minutes. The task starts on its own when a slot frees up. | | Reply inside the session while the task runs | Your message goes to the running agent as a nudge (the same guardrail screening, 2,000-character cap and per-minute limit as `bgagent nudge`). The agent picks it up at its next step. Only the task's owner can steer it. | | Reply after the task has finished | Starts a follow-up task. If the run stopped to ask a question, your reply resumes the original request with the answer. Otherwise it's a PR iteration if a PR exists, or new work from your message plus the issue. | | Click **Stop** in the session | Cancels the running task and shuts its agent down, like `bgagent cancel`, then confirms with a final response. Only the task's owner can stop it. | @@ -247,9 +249,9 @@ If you do these the other way round, every mention in the meantime opens a sessi **Who can act.** Every session request, `stop` included, needs a linked ABCA user ([Inviting teammates](#inviting-teammates)). An unlinked user is told to link their account and nothing runs. A refusal closes the session it was made in, unless that is the session a running task reports into; there it's a note, so someone else's run isn't marked finished or failed. A new task is attributed to whoever asked for it. Steering or stopping a *running* task follows the API's rule: only its owner can do it. -**Reactions.** A session task gets no 👀/✅/❌ reactions on the issue, since the session shows that state. The issue still moves to *In Progress* and *In Review*. +**Reactions.** A session task gets no 👀/✅/❌ reactions on the issue, since the session shows that state. The issue still moves to *In Progress* when work starts, and to *In Review* when the task ends with a pull request. -**Not yet supported in sessions:** image and file attachments from the issue description (use a label trigger for those), and Linear's *plan* checklist. +**Not yet supported in sessions:** image and file attachments from the issue description (use a label trigger for those). ## Adding another workspace From 9f58ea25f4bc7c2600d8d56813e0135d5646ca89 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 5 Nov 2026 13:06:17 +0000 Subject: [PATCH 02/27] fix(cli): honest Linear vault fallback status and a re-asking identity picker - When `bgagent linear setup` moves a workspace onto the Identity vault it keeps the existing Secrets Manager token. If that token's access token has already expired, setup now says the fallback is unverified (refresh tokens expire when unused and cannot be checked without rotating) instead of printing "Kept the existing Secrets Manager token as a fallback". Seen live: a token dead since 2026-08-27 was reported as a working fallback. - The self-link and teammate pickers re-ask on an empty or invalid answer (up to 3 times). A pasted session id that ends in a newline, followed by Enter, left a stray empty line that silently skipped the self-link. (cherry picked from commit 1fbfad466f1465ca5b9b7c4fcdb5a6f8b32682ea) --- cli/src/commands/linear.ts | 37 ++++++++++++++++++++++++-------- cli/src/linear-oauth.ts | 24 +++++++++++++++++++++ cli/test/commands/linear.test.ts | 25 +++++++++++++++++++++ cli/test/linear-oauth.test.ts | 19 ++++++++++++++++ 4 files changed, 96 insertions(+), 9 deletions(-) diff --git a/cli/src/commands/linear.ts b/cli/src/commands/linear.ts index 71b694ccb..861e064a6 100644 --- a/cli/src/commands/linear.ts +++ b/cli/src/commands/linear.ts @@ -46,6 +46,7 @@ import { resolveStoredGrantFields, readExistingWebhookSecret, StoredLinearOauthToken, + describePreservedFallback, } from '../linear-oauth'; import { clearPendingConsent, @@ -1625,7 +1626,7 @@ export function makeLinearCommand(): Command { console.log(` ✓ (${secretName})`); // After the progress line closes, not during it. if (preservedTokens) { - console.log(' ✓ Kept the existing Secrets Manager token as a fallback'); + console.log(` ${describePreservedFallback(preservedTokens).message}`); } console.log(suppliedWebhookSecret ? ' ✓ Using the webhook signing secret you entered' @@ -2401,10 +2402,9 @@ export function makeLinearCommand(): Command { console.log(` ${i + 1}. ${m.name ?? m.id}${email}`); }); console.log(); - const pickRaw = (await promptLine(` Which one is the teammate? [1-${humans.length}]`)).trim(); - const pickIdx = parseInt(pickRaw, 10) - 1; - if (Number.isNaN(pickIdx) || pickIdx < 0 || pickIdx >= humans.length) { - throw new CliError(`Invalid selection '${pickRaw}'.`); + const pickIdx = await promptChoice(` Which one is the teammate? [1-${humans.length}]`, humans.length); + if (pickIdx === undefined) { + throw new CliError('No valid selection.'); } const picked = humans[pickIdx]; const pickedLabel = `${picked.name ?? picked.id}${picked.email ? ` (${picked.email})` : ''}`; @@ -2827,6 +2827,26 @@ export function makeLinearCommand(): Command { return requireDeployedFeature(linear, 'linear'); } +/** + * Ask for a 1-based choice, re-asking on an empty or invalid answer. A paste that + * ends in a newline followed by Enter leaves a stray line for the NEXT prompt; + * failing on it would silently skip the choice. Returns undefined after `attempts`. + */ +export async function promptChoice( + label: string, + count: number, + ask: (label: string) => Promise = promptLine, + attempts = 3, +): Promise { + for (let attempt = 0; attempt < attempts; attempt++) { + const raw = (await ask(label)).trim(); + const idx = /^\d+$/.test(raw) ? parseInt(raw, 10) - 1 : -1; + if (idx >= 0 && idx < count) return idx; + if (attempt < attempts - 1) process.stderr.write(raw ? ` '${raw}' is not between 1 and ${count}.\n` : ''); + } + return undefined; +} + // ─── Auto-link ─────────────────────────────────────────────────────────────── interface LinearViewer { @@ -3039,10 +3059,9 @@ async function runSelfLinkPicker(args: { console.log(` ${i + 1}. ${m.name ?? m.id}${email}`); }); console.log(); - const pickRaw = (await promptLine(` Which one is you? [1-${humans.length}]`)).trim(); - const pickIdx = parseInt(pickRaw, 10) - 1; - if (Number.isNaN(pickIdx) || pickIdx < 0 || pickIdx >= humans.length) { - console.log(` ⚠ Invalid selection '${pickRaw}'; skipping self-link.`); + const pickIdx = await promptChoice(` Which one is you? [1-${humans.length}]`, humans.length); + if (pickIdx === undefined) { + console.log(' ⚠ No valid selection; skipping self-link.'); console.log(' Re-run setup or pick yourself later via the picker that fires on first failed trigger.'); return false; } diff --git a/cli/src/linear-oauth.ts b/cli/src/linear-oauth.ts index c9e37ce96..9feb8dc7a 100644 --- a/cli/src/linear-oauth.ts +++ b/cli/src/linear-oauth.ts @@ -503,3 +503,27 @@ export async function verifyLinearRefreshAndPersist(args: { } return 'refreshed'; } + +/** + * How setup should describe a Secrets-Manager token it kept when moving onto the + * vault. A refresh token cannot be checked without rotating it, so an expired + * access token is reported as unverified rather than as a working fallback: + * Linear rejects refresh tokens that went unused for too long. + */ +export function describePreservedFallback( + preserved: Pick, + now: Date = new Date(), +): { readonly usable: boolean; readonly message: string } { + const expiresAt = Date.parse(preserved.expires_at); + if (Number.isFinite(expiresAt) && expiresAt <= now.getTime()) { + return { + usable: false, + message: + `⚠ Kept the existing Secrets Manager token, but its access token expired on ${preserved.expires_at}. ` + + 'It only works as a fallback if Linear still accepts its refresh token, which expires when ' + + 'unused. Treat the vault as the only verified credential for this workspace.', + }; + } + return { usable: true, message: '✓ Kept the existing Secrets Manager token as a fallback' }; +} + diff --git a/cli/test/commands/linear.test.ts b/cli/test/commands/linear.test.ts index b2a29d430..e7024cd9d 100644 --- a/cli/test/commands/linear.test.ts +++ b/cli/test/commands/linear.test.ts @@ -25,6 +25,7 @@ import { readStackWideWebhookSecret, queryLinearTeamKeys, parsePastedAuthorization, + promptChoice, renderLinearAppTemplate, } from '../../src/commands/linear'; import { generateInviteCode, INVITE_CODE_ALPHABET } from '../../src/invite-code'; @@ -818,3 +819,27 @@ describe('parsePastedAuthorization', () => { expect(parsePastedAuthorization('code=abc123&state=')).toEqual({ code: 'abc123' }); }); }); + +describe('promptChoice', () => { + const answers = (...values: string[]) => { + const queue = [...values]; + return jest.fn(async () => queue.shift() ?? ''); + }; + + test('re-asks after a stray empty line left by a pasted newline', async () => { + const ask = answers('', '2'); + expect(await promptChoice('Which one is you?', 2, ask)).toBe(1); + expect(ask).toHaveBeenCalledTimes(2); + }); + + test('re-asks on out-of-range or non-numeric answers', async () => { + expect(await promptChoice('Pick', 3, answers('9', 'x2', '3'))).toBe(2); + }); + + test('gives up after the attempt budget instead of looping forever', async () => { + const ask = answers('', '', ''); + expect(await promptChoice('Pick', 2, ask)).toBeUndefined(); + expect(ask).toHaveBeenCalledTimes(3); + }); +}); + diff --git a/cli/test/linear-oauth.test.ts b/cli/test/linear-oauth.test.ts index 347477e84..cd6344aac 100644 --- a/cli/test/linear-oauth.test.ts +++ b/cli/test/linear-oauth.test.ts @@ -21,6 +21,7 @@ import { CliError } from '../src/errors'; import { buildAuthorizationUrl, computeExpiresAt, + describePreservedFallback, exchangeAuthorizationCode, generatePkce, LINEAR_AUTHORIZE_ENDPOINT, @@ -601,3 +602,21 @@ describe('resolveStoredGrantFields — a preserved grant must never be overwritt }); }); }); + +describe('describePreservedFallback', () => { + const now = new Date('2026-11-05T00:00:00Z'); + + test('an expired access token is reported as an unverified fallback, not a working one', () => { + const result = describePreservedFallback({ expires_at: '2026-07-29T10:09:20.000Z' }, now); + expect(result.usable).toBe(false); + expect(result.message).toContain('expired on 2026-07-29T10:09:20.000Z'); + expect(result.message).not.toContain('✓'); + }); + + test('a live access token is kept as a fallback', () => { + expect(describePreservedFallback({ expires_at: '2026-11-06T00:00:00Z' }, now)).toEqual({ + usable: true, message: '✓ Kept the existing Secrets Manager token as a fallback', + }); + }); +}); + From 26786d28e7873a3940a51ccb27f0fb1a7ef91e9c Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Mon, 16 Nov 2026 01:37:16 +0000 Subject: [PATCH 03/27] style(cli): end files with a single newline (end-of-file hook) (cherry picked from commit dd6ff855338ea10ab70ff1793cc4cabcbd3b279c) --- cli/src/linear-oauth.ts | 1 - cli/test/commands/linear.test.ts | 1 - cli/test/linear-oauth.test.ts | 1 - 3 files changed, 3 deletions(-) diff --git a/cli/src/linear-oauth.ts b/cli/src/linear-oauth.ts index 9feb8dc7a..68122e586 100644 --- a/cli/src/linear-oauth.ts +++ b/cli/src/linear-oauth.ts @@ -526,4 +526,3 @@ export function describePreservedFallback( } return { usable: true, message: '✓ Kept the existing Secrets Manager token as a fallback' }; } - diff --git a/cli/test/commands/linear.test.ts b/cli/test/commands/linear.test.ts index e7024cd9d..89080da7e 100644 --- a/cli/test/commands/linear.test.ts +++ b/cli/test/commands/linear.test.ts @@ -842,4 +842,3 @@ describe('promptChoice', () => { expect(ask).toHaveBeenCalledTimes(3); }); }); - diff --git a/cli/test/linear-oauth.test.ts b/cli/test/linear-oauth.test.ts index cd6344aac..4a5729017 100644 --- a/cli/test/linear-oauth.test.ts +++ b/cli/test/linear-oauth.test.ts @@ -619,4 +619,3 @@ describe('describePreservedFallback', () => { }); }); }); - From 25a6e9d3f4d651fdd6db22bb8f7ac5a8fac66a80 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 5 Nov 2026 00:09:35 +0000 Subject: [PATCH 04/27] feat(linear): default the Identity vault on wherever AgentCore is deployed A Secrets Manager workspace that ABCA did not use for a while let its Linear refresh token expire, so every Linear trigger failed silently until someone re-consented through the CLI's localhost callback. The vault refreshes the grant itself and ships a hosted consent page. - enableLinearIdentityVault now defaults to whether AgentCore is deployed (which proves the region has AgentCore); deployments without AgentCore keep Secrets Manager. true|false still overrides, and any other value fails synth. - Existing vault deployments keep their resources and logical IDs; a Secrets Manager workspace keeps working until `bgagent linear setup` moves it (the resolver picks per workspace via provider_name). - Census: all 112 supported profiles pass with the vault on; the all-backends inline-network profile was already an expected rejection. - CLI hints and the setup guide / ADR-016 describe the new default. (cherry picked from commit 60bacdbe80f303d5a78fd05c9a197c30b5133f53) --- cdk/src/stacks/agent.ts | 27 +++++++++++++---- cdk/test/stacks/agent.test.ts | 29 ++++++++++++++++--- cdk/test/stacks/compute-selection.test.ts | 6 +++- cli/src/commands/linear.ts | 16 +++++----- .../ADR-016-pluggable-identity-and-auth.md | 7 +++-- docs/guides/LINEAR_SETUP_GUIDE.md | 8 +++-- .../Adr-016-pluggable-identity-and-auth.md | 7 +++-- .../content/docs/using/Linear-setup-guide.md | 8 +++-- 8 files changed, 83 insertions(+), 25 deletions(-) diff --git a/cdk/src/stacks/agent.ts b/cdk/src/stacks/agent.ts index 276100253..5590b78e8 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -233,6 +233,17 @@ function linearAgentSessionsProps( }; } +/** + * Whether the Linear OAuth token vault is deployed. An explicit context value wins; + * otherwise the vault is on exactly when AgentCore is (see the call site). + */ +export function resolveLinearIdentityVault(context: unknown, agentCoreEnabled: boolean): boolean { + if (context === true || context === 'true') return true; + if (context === false || context === 'false') return false; + if (context !== undefined) throw new Error('enableLinearIdentityVault must be true or false'); + return agentCoreEnabled; +} + export class AgentStack extends Stack { /** The REST API and its Cognito user pool; the operator console stack signs users in against these. */ public readonly taskApi: TaskApi; @@ -427,11 +438,17 @@ export class AgentStack extends Stack { // unchanged and introduces no new CFN types into the bootstrap policy set. const toolGatewayEnabled = features.toolGateway; - // RFC #249 Phase 1 (Linear OAuth token vault). Additive + default-off: - // resolved here (early) so the agent runtime env map + the LinearIdentityVault - // construct + the token grants all key off one predicate and cannot drift. - const linearIdentityVaultEnabled = this.node.tryGetContext('enableLinearIdentityVault') === true - || this.node.tryGetContext('enableLinearIdentityVault') === 'true'; + // RFC #249 Linear OAuth token vault (AgentCore Identity). Default ON wherever + // Linear and AgentCore are both deployed: AgentCore already proves the region + // has it, and the vault refreshes the Linear grant itself, so an idle workspace + // cannot strand an expired refresh token in Secrets Manager. Deployments without + // AgentCore default to Secrets Manager, and without Linear there is no grant to + // vault. `--context enableLinearIdentityVault=true|false` overrides the default + // (an explicit true without Linear still fails below). Resolved early so the + // runtime env map, the LinearIdentityVault construct and the token grants share + // one predicate. + const linearIdentityVaultEnabled = resolveLinearIdentityVault( + this.node.tryGetContext('enableLinearIdentityVault'), agentCoreEnabled && features.linear); if (linearIdentityVaultEnabled && !features.linear) { throw new Error('enableLinearIdentityVault requires the linear feature; enable Linear or drop the vault switch'); } diff --git a/cdk/test/stacks/agent.test.ts b/cdk/test/stacks/agent.test.ts index 91f839696..70fa0e22d 100644 --- a/cdk/test/stacks/agent.test.ts +++ b/cdk/test/stacks/agent.test.ts @@ -1925,8 +1925,10 @@ describe('AgentStack solution attribution (#319): AWS_SDK_UA_APP_ID via stack-le // unnoticed; the exact count fails if a Lambda is dropped OR if a new one // is added without being attributed below. // 48 existing handlers (5 scheduled maintenance jobs nested) + 2 registry - // provisioning handlers + 4 registry API handlers in nested stacks. - expect(abcaLambdas.length).toBe(54); + // provisioning handlers + 4 registry API handlers in nested stacks, + 2 now + // that the Linear identity vault is on by default (its provider onEvent + // handler and the provider framework function). + expect(abcaLambdas.length).toBe(56); // Every ABCA-authored Lambda must carry the canonical `#` app-id. Collect // any offenders so a failure names the exact logical id(s) that are naked. const unattributed = abcaLambdas @@ -2058,8 +2060,21 @@ describe('AgentStack tool-gateway gate (ADR-019 P1)', () => { }); describe('AgentStack Linear identity vault gate (#809)', () => { - test('default synth omits the vault: no workload identity, no token grant, no agent env', () => { - const app = new App(); + test('default synth (AgentCore) provisions the vault and its hosted consent page', () => { + const rendered = JSON.stringify(Template.fromStack(new AgentStack(new App(), 'LinearVaultDefaultStack', { + env: { account: '123456789012', region: 'us-east-1' }, + })).toJSON()); + expect(rendered).toContain('Custom::LinearWorkloadIdentity'); + expect(rendered).toContain('GetResourceOauth2Token'); + expect(rendered).toContain('LINEAR_WORKLOAD_IDENTITY_NAME'); + expect(rendered).toContain('LinearVaultConsentUrl'); + }); + + test.each([ + ['explicit opt-out', { enableLinearIdentityVault: 'false' }], + ['a deployment without AgentCore', { compute_types: 'ecs' }], + ])('%s omits the vault: no workload identity, no token grant, no agent env', (_label, context) => { + const app = new App({ context }); const stack = new AgentStack(app, 'LinearVaultOffStack', { env: { account: '123456789012', region: 'us-east-1' }, }); @@ -2072,6 +2087,12 @@ describe('AgentStack Linear identity vault gate (#809)', () => { expect(rendered).not.toContain('LinearVaultConsentUrl'); }); + test('an unrecognised flag value fails synth instead of silently choosing a store', () => { + expect(() => new AgentStack(new App({ context: { enableLinearIdentityVault: 'yes' } }), 'LinearVaultBadStack', { + env: { account: '123456789012', region: 'us-east-1' }, + })).toThrow('enableLinearIdentityVault must be true or false'); + }); + test('flag on: agent runtime role gets the token data-plane grant + the agent env is set', () => { const app = new App({ context: { enableLinearIdentityVault: true } }); const stack = new AgentStack(app, 'LinearVaultOnStack', { diff --git a/cdk/test/stacks/compute-selection.test.ts b/cdk/test/stacks/compute-selection.test.ts index 5b9291da3..bf89befc3 100644 --- a/cdk/test/stacks/compute-selection.test.ts +++ b/cdk/test/stacks/compute-selection.test.ts @@ -150,7 +150,11 @@ describe.each([ { label: 'legacy ECS', selector: { compute_type: 'ecs' }, backends: ['agentcore', 'ecs'] }, { label: 'ECS default with AgentCore', selector: { compute_types: ['ecs', 'agentcore'] }, backends: ['ecs', 'agentcore'] }, { label: 'MicroVM default without AgentCore', selector: { compute_types: 'lambda-microvm,ecs' }, backends: ['lambda-microvm', 'ecs'] }, - { label: 'all backends', selector: { compute_types: 'agentcore,ecs,lambda-microvm' }, backends: ['agentcore', 'ecs', 'lambda-microvm'] }, + // All three backends with the inline network is an expected census rejection + // (`additive-agentcore+ecs+lambda-microvm-default-inline`, over the 490 budget); + // pin the default-on vault off so this backend-wiring test stays under + // CloudFormation's 500-resource limit. The vault itself is covered in agent.test. + { label: 'all backends', selector: { compute_types: 'agentcore,ecs,lambda-microvm', enableLinearIdentityVault: 'false' }, backends: ['agentcore', 'ecs', 'lambda-microvm'] }, ])('additive deployment from $label', ({ selector, backends }) => { let template: Template; let stack: Stack; diff --git a/cli/src/commands/linear.ts b/cli/src/commands/linear.ts index 861e064a6..95fe1784b 100644 --- a/cli/src/commands/linear.ts +++ b/cli/src/commands/linear.ts @@ -339,8 +339,9 @@ export function renderLinearAppTemplate(opts: LinearAppTemplateOptions = {}): st ] : [ ` ${callbackUrl}`, - ' (loopback — needs the browser on this machine; deploy with', - ' `--context enableLinearIdentityVault=true` for a hosted consent page)', + ' (loopback — needs the browser on this machine; the Identity vault provides a', + ' hosted consent page: on by default with AgentCore, or', + ' `--context enableLinearIdentityVault=true`)', ]), '', ' Public: OFF', @@ -1231,7 +1232,8 @@ export function makeLinearCommand(): Command { ? ' `--code` resumes the Secrets Manager authorization-code flow. A vault workspace ' + 'finishes its consent in one run — re-run without `--code`.' : ` The stack '${stackName}' publishes no LinearVaultConsentUrl, so its last deploy ` - + 'omitted `--context enableLinearIdentityVault=true`. Re-deploy with it, or move ' + + 'had no Identity vault (no AgentCore, or `--context enableLinearIdentityVault=false`). ' + + 'Re-deploy with `--context enableLinearIdentityVault=true`, or move ' + 'this workspace off the vault deliberately by deleting its registry row first.'), ); } @@ -1240,8 +1242,8 @@ export function makeLinearCommand(): Command { // availability, only this stack's outputs. Naming the real cause is what lets // an operator fix it, and the wrong cause sends them to the AWS region table. console.log( - ` Stack '${stackName}' has no Identity vault (deployed without ` - + '`--context enableLinearIdentityVault=true`) — using Secrets Manager.', + ` Stack '${stackName}' has no Identity vault (deployed without AgentCore, or with ` + + '`--context enableLinearIdentityVault=false`) — using Secrets Manager.', ); } @@ -1465,8 +1467,8 @@ export function makeLinearCommand(): Command { console.log(` Redirecting to: ${setupRedirectUri}`); console.log(' That exact URI must be one of the app\'s Redirect URIs, or consent'); console.log(' fails with "Invalid redirect_uri parameter for the application".'); - console.log(' No localhost on this machine? Deploy the consent page with'); - console.log(' `--context enableLinearIdentityVault=true`.\n'); + console.log(' No localhost on this machine? Re-deploy with'); + console.log(' `--context enableLinearIdentityVault=true` for the hosted consent page.\n'); } if (resumed || vaultAccessToken) { // nothing to open: consent already happened in the operator's browser. diff --git a/docs/decisions/ADR-016-pluggable-identity-and-auth.md b/docs/decisions/ADR-016-pluggable-identity-and-auth.md index 7deb17fe5..ff3b16ba2 100644 --- a/docs/decisions/ADR-016-pluggable-identity-and-auth.md +++ b/docs/decisions/ADR-016-pluggable-identity-and-auth.md @@ -9,8 +9,11 @@ > **2026-08-28 implementation note — Phase 1 (Linear `ChannelCredential`) is built and live-verified > on a dev stack** ([#809](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/809)). -> Additive and context-gated (`enableLinearIdentityVault`, default off), with Secrets Manager retained -> as the fallback, so a deployment that does not opt in is byte-for-byte unchanged. The decision below +> Additive and context-gated (`enableLinearIdentityVault`), with Secrets Manager retained +> as the fallback. **Update:** the gate now defaults ON wherever AgentCore is deployed (which proves +> the region has AgentCore) and OFF otherwise; `enableLinearIdentityVault=true|false` overrides. +> Motivation: a Secrets Manager workspace left unused let its refresh token expire, failing every +> Linear trigger silently until a browser re-consent through the CLI's localhost callback. The decision below > stands; two implementation details deviate from the P1 text and are recorded in *Phasing* → P1. ## Context diff --git a/docs/guides/LINEAR_SETUP_GUIDE.md b/docs/guides/LINEAR_SETUP_GUIDE.md index 17eb08418..98f28847b 100644 --- a/docs/guides/LINEAR_SETUP_GUIDE.md +++ b/docs/guides/LINEAR_SETUP_GUIDE.md @@ -21,8 +21,12 @@ One of two places, chosen automatically at setup time: | | When it's used | What's stored | |---|---|---| -| **AgentCore Identity vault** | The stack was deployed with `--context enableLinearIdentityVault=true` | Nothing long-lived. AgentCore holds the refresh token and mints short-lived access tokens on demand. | -| **Secrets Manager** | Otherwise — including regions where AgentCore Identity isn't available | An OAuth token bundle in `bgagent-linear-oauth-`, refreshed and rotated by ABCA. | +| **AgentCore Identity vault** | **Default** whenever the stack deploys AgentCore (the standard deployment). Force it on with `--context enableLinearIdentityVault=true` | Nothing long-lived. AgentCore holds the refresh token and mints short-lived access tokens on demand. | +| **Secrets Manager** | Deployments without AgentCore, or `--context enableLinearIdentityVault=false` | An OAuth token bundle in `bgagent-linear-oauth-`, refreshed and rotated by ABCA only when ABCA uses Linear. | + +Prefer the vault. With Secrets Manager, a workspace that ABCA does not use for long enough can be left with an expired refresh token, and re-authorizing needs a browser that can reach the CLI's `localhost` callback. The vault's hosted consent page works from any machine. + +Existing vault deployments keep their resources and logical IDs, so turning the default on changes nothing for them. A Secrets Manager workspace on a stack that now has the vault keeps working until you re-run `bgagent linear setup `, which moves it to the vault. The vault can be configured with any selected backend. Lambda MicroVMs remains experimental; its image must include the current shared configuration contract. diff --git a/docs/src/content/docs/decisions/Adr-016-pluggable-identity-and-auth.md b/docs/src/content/docs/decisions/Adr-016-pluggable-identity-and-auth.md index 690838cd2..33bbaf1bd 100644 --- a/docs/src/content/docs/decisions/Adr-016-pluggable-identity-and-auth.md +++ b/docs/src/content/docs/decisions/Adr-016-pluggable-identity-and-auth.md @@ -11,8 +11,11 @@ title: "ADR-016: Pluggable identity and authentication" > **2026-08-28 implementation note — Phase 1 (Linear `ChannelCredential`) is built and live-verified > on a dev stack** ([#809](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/809)). -> Additive and context-gated (`enableLinearIdentityVault`, default off), with Secrets Manager retained -> as the fallback, so a deployment that does not opt in is byte-for-byte unchanged. The decision below +> Additive and context-gated (`enableLinearIdentityVault`), with Secrets Manager retained +> as the fallback. **Update:** the gate now defaults ON wherever AgentCore is deployed (which proves +> the region has AgentCore) and OFF otherwise; `enableLinearIdentityVault=true|false` overrides. +> Motivation: a Secrets Manager workspace left unused let its refresh token expire, failing every +> Linear trigger silently until a browser re-consent through the CLI's localhost callback. The decision below > stands; two implementation details deviate from the P1 text and are recorded in *Phasing* → P1. ## Context diff --git a/docs/src/content/docs/using/Linear-setup-guide.md b/docs/src/content/docs/using/Linear-setup-guide.md index ce9d2847e..5a86cda7e 100644 --- a/docs/src/content/docs/using/Linear-setup-guide.md +++ b/docs/src/content/docs/using/Linear-setup-guide.md @@ -23,8 +23,12 @@ One of two places, chosen automatically at setup time: | | When it's used | What's stored | |---|---|---| -| **AgentCore Identity vault** | The stack was deployed with `--context enableLinearIdentityVault=true` | Nothing long-lived. AgentCore holds the refresh token and mints short-lived access tokens on demand. | -| **Secrets Manager** | Otherwise — including regions where AgentCore Identity isn't available | An OAuth token bundle in `bgagent-linear-oauth-`, refreshed and rotated by ABCA. | +| **AgentCore Identity vault** | **Default** whenever the stack deploys AgentCore (the standard deployment). Force it on with `--context enableLinearIdentityVault=true` | Nothing long-lived. AgentCore holds the refresh token and mints short-lived access tokens on demand. | +| **Secrets Manager** | Deployments without AgentCore, or `--context enableLinearIdentityVault=false` | An OAuth token bundle in `bgagent-linear-oauth-`, refreshed and rotated by ABCA only when ABCA uses Linear. | + +Prefer the vault. With Secrets Manager, a workspace that ABCA does not use for long enough can be left with an expired refresh token, and re-authorizing needs a browser that can reach the CLI's `localhost` callback. The vault's hosted consent page works from any machine. + +Existing vault deployments keep their resources and logical IDs, so turning the default on changes nothing for them. A Secrets Manager workspace on a stack that now has the vault keeps working until you re-run `bgagent linear setup `, which moves it to the vault. The vault can be configured with any selected backend. Lambda MicroVMs remains experimental; its image must include the current shared configuration contract. From 15287c13f38b64d520312309b287d088c3f07b36 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 5 Nov 2026 15:06:41 +0000 Subject: [PATCH 05/27] docs(linear): say when enableLinearIdentityVault=true still matters With the vault on by default wherever AgentCore is deployed, the explicit opt-in only matters for deployments without AgentCore. (cherry picked from commit b188f5c40ada1c2e6cdfcf8f7668f79d1c6be879) --- docs/guides/LINEAR_SETUP_GUIDE.md | 2 +- docs/src/content/docs/using/Linear-setup-guide.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/guides/LINEAR_SETUP_GUIDE.md b/docs/guides/LINEAR_SETUP_GUIDE.md index 98f28847b..09189f5a6 100644 --- a/docs/guides/LINEAR_SETUP_GUIDE.md +++ b/docs/guides/LINEAR_SETUP_GUIDE.md @@ -21,7 +21,7 @@ One of two places, chosen automatically at setup time: | | When it's used | What's stored | |---|---|---| -| **AgentCore Identity vault** | **Default** whenever the stack deploys AgentCore (the standard deployment). Force it on with `--context enableLinearIdentityVault=true` | Nothing long-lived. AgentCore holds the refresh token and mints short-lived access tokens on demand. | +| **AgentCore Identity vault** | **Default** whenever the stack deploys AgentCore (the standard deployment). A deployment without AgentCore (for example `compute_types=ecs`) can opt in with `--context enableLinearIdentityVault=true`, provided its region has AgentCore Identity | Nothing long-lived. AgentCore holds the refresh token and mints short-lived access tokens on demand. | | **Secrets Manager** | Deployments without AgentCore, or `--context enableLinearIdentityVault=false` | An OAuth token bundle in `bgagent-linear-oauth-`, refreshed and rotated by ABCA only when ABCA uses Linear. | Prefer the vault. With Secrets Manager, a workspace that ABCA does not use for long enough can be left with an expired refresh token, and re-authorizing needs a browser that can reach the CLI's `localhost` callback. The vault's hosted consent page works from any machine. diff --git a/docs/src/content/docs/using/Linear-setup-guide.md b/docs/src/content/docs/using/Linear-setup-guide.md index 5a86cda7e..e60ee28e0 100644 --- a/docs/src/content/docs/using/Linear-setup-guide.md +++ b/docs/src/content/docs/using/Linear-setup-guide.md @@ -23,7 +23,7 @@ One of two places, chosen automatically at setup time: | | When it's used | What's stored | |---|---|---| -| **AgentCore Identity vault** | **Default** whenever the stack deploys AgentCore (the standard deployment). Force it on with `--context enableLinearIdentityVault=true` | Nothing long-lived. AgentCore holds the refresh token and mints short-lived access tokens on demand. | +| **AgentCore Identity vault** | **Default** whenever the stack deploys AgentCore (the standard deployment). A deployment without AgentCore (for example `compute_types=ecs`) can opt in with `--context enableLinearIdentityVault=true`, provided its region has AgentCore Identity | Nothing long-lived. AgentCore holds the refresh token and mints short-lived access tokens on demand. | | **Secrets Manager** | Deployments without AgentCore, or `--context enableLinearIdentityVault=false` | An OAuth token bundle in `bgagent-linear-oauth-`, refreshed and rotated by ABCA only when ABCA uses Linear. | Prefer the vault. With Secrets Manager, a workspace that ABCA does not use for long enough can be left with an expired refresh token, and re-authorizing needs a browser that can reach the CLI's `localhost` callback. The vault's hosted consent page works from any machine. From e38fbce832eceb3fdfe80c248870cd96bf01f2dc Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Mon, 16 Nov 2026 01:37:37 +0000 Subject: [PATCH 06/27] refactor(cdk): resolveLinearIdentityVault is used only in its own file (knip) (cherry picked from commit 844b65c6dba811140c81145bddb2de95f95755d1) --- cdk/src/stacks/agent.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cdk/src/stacks/agent.ts b/cdk/src/stacks/agent.ts index 5590b78e8..fb219d65b 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -237,7 +237,7 @@ function linearAgentSessionsProps( * Whether the Linear OAuth token vault is deployed. An explicit context value wins; * otherwise the vault is on exactly when AgentCore is (see the call site). */ -export function resolveLinearIdentityVault(context: unknown, agentCoreEnabled: boolean): boolean { +function resolveLinearIdentityVault(context: unknown, agentCoreEnabled: boolean): boolean { if (context === true || context === 'true') return true; if (context === false || context === 'false') return false; if (context !== undefined) throw new Error('enableLinearIdentityVault must be true or false'); From a2206aa6d00338373ad05bc21e38c32d4057a1f4 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Mon, 16 Nov 2026 15:11:41 +0000 Subject: [PATCH 07/27] fix(cdk): default the Linear vault on only when Linear is deployed main now rejects enableLinearIdentityVault without the linear feature, so a default derived from AgentCore alone failed every stack synthesized without Linear. An explicit true without Linear still fails. (cherry picked from commit 524af347efa3183534a41d59daa14057e0347ffe) --- cdk/src/stacks/agent.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cdk/src/stacks/agent.ts b/cdk/src/stacks/agent.ts index fb219d65b..ae4b15389 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -235,13 +235,13 @@ function linearAgentSessionsProps( /** * Whether the Linear OAuth token vault is deployed. An explicit context value wins; - * otherwise the vault is on exactly when AgentCore is (see the call site). + * otherwise `byDefault` (on when Linear and AgentCore are both deployed: see the call site). */ -function resolveLinearIdentityVault(context: unknown, agentCoreEnabled: boolean): boolean { +function resolveLinearIdentityVault(context: unknown, byDefault: boolean): boolean { if (context === true || context === 'true') return true; if (context === false || context === 'false') return false; if (context !== undefined) throw new Error('enableLinearIdentityVault must be true or false'); - return agentCoreEnabled; + return byDefault; } export class AgentStack extends Stack { From c46d2a17ce6726575b941b9c61c4fc4af3340df9 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 5 Nov 2026 15:19:06 +0000 Subject: [PATCH 08/27] fix(linear): detect dead Linear grants even when no Linear events arrive (#1004) Revocation detection (#812) only runs when a Linear event needs a token, so an idle workspace or a dead webhook never re-detects a dead grant, and an unused refresh token simply expires: observed live, a workspace sat with an expired refresh token for months with one ERROR log line. - The concurrency reconciler (already every 15 min) async-invokes the Linear webhook processor with {grant_health_probe: true} on exactly one tick per 12 h (isProbeTick). Best-effort: a failed invoke never affects reconciliation. - In probe mode the processor resolves a token for every active registry workspace. That refreshes expiring tokens (keeping idle grants alive) and sends a rejected grant down the existing latch-and-announce path to OperationalAlerts. Its summary logs any workspace without a usable token. - Zero new CloudFormation resources (an invoke IAM statement and two env vars): the root stack is at its 490-resource budget in some census profiles, so a rule of its own did not fit. - LINEAR_SETUP_GUIDE troubleshooting documents the probe, the alert topic (which ships without subscribers) and the recovery command. (cherry picked from commit d78a4fa452a6fbe81cd38cc0c15d6c31a5db2944) --- cdk/src/constructs/concurrency-reconciler.ts | 19 ++- cdk/src/handlers/linear-webhook-processor.ts | 37 ++++- cdk/src/handlers/reconcile-concurrency.ts | 31 +++++ .../handlers/shared/linear-grant-health.ts | 128 ++++++++++++++++++ cdk/src/stacks/agent.ts | 5 +- .../constructs/concurrency-reconciler.test.ts | 39 ++++++ .../handlers/linear-webhook-processor.test.ts | 29 ++++ .../reconcile-concurrency-grant-probe.test.ts | 61 +++++++++ .../shared/linear-grant-health.test.ts | 98 ++++++++++++++ docs/guides/LINEAR_SETUP_GUIDE.md | 12 ++ .../content/docs/using/Linear-setup-guide.md | 12 ++ 11 files changed, 468 insertions(+), 3 deletions(-) create mode 100644 cdk/src/handlers/shared/linear-grant-health.ts create mode 100644 cdk/test/handlers/reconcile-concurrency-grant-probe.test.ts create mode 100644 cdk/test/handlers/shared/linear-grant-health.test.ts diff --git a/cdk/src/constructs/concurrency-reconciler.ts b/cdk/src/constructs/concurrency-reconciler.ts index c0fed93dd..4e66bba6d 100644 --- a/cdk/src/constructs/concurrency-reconciler.ts +++ b/cdk/src/constructs/concurrency-reconciler.ts @@ -22,7 +22,7 @@ import { Duration } from 'aws-cdk-lib'; import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; import * as events from 'aws-cdk-lib/aws-events'; import * as targets from 'aws-cdk-lib/aws-events-targets'; -import { Runtime, Architecture } from 'aws-cdk-lib/aws-lambda'; +import { Runtime, Architecture, type IFunction } from 'aws-cdk-lib/aws-lambda'; import * as lambda from 'aws-cdk-lib/aws-lambda-nodejs'; import { NagSuppressions } from 'cdk-nag'; import { Construct } from 'constructs'; @@ -92,6 +92,7 @@ export class ConcurrencyReconciler extends Construct { props.userConcurrencyTable.grantReadWriteData(this.fn); const schedule = props.schedule ?? Duration.minutes(DEFAULT_SCHEDULE_MINUTES); + this.fn.addEnvironment('RECONCILER_TICK_MINUTES', String(schedule.toMinutes())); const rule = new events.Rule(this, 'ReconcilerSchedule', { schedule: events.Schedule.rate(schedule), }); @@ -108,4 +109,20 @@ export class ConcurrencyReconciler extends Construct { }, ], true); } + + /** + * Have this reconciler invoke the Linear webhook processor's grant health probe + * (#1004) on one tick every 12 h. + * + * Revocation detection (#812) only runs when a Linear event needs a token, so an + * idle workspace or a dead webhook never re-detects a dead grant, and an unused + * refresh token simply expires. The probe refreshes expiring tokens and sends a + * rejected grant down the existing latch-and-announce path. It rides this + * schedule by async invoke because the root stack has no resource budget for a + * rule of its own: this adds only an IAM statement and two env vars. + */ + public triggerLinearGrantProbe(processor: IFunction): void { + this.fn.addEnvironment('LINEAR_GRANT_PROBE_FUNCTION_ARN', processor.functionArn); + processor.grantInvoke(this.fn); + } } diff --git a/cdk/src/handlers/linear-webhook-processor.ts b/cdk/src/handlers/linear-webhook-processor.ts index 6c69ea6ee..f736b4fed 100644 --- a/cdk/src/handlers/linear-webhook-processor.ts +++ b/cdk/src/handlers/linear-webhook-processor.ts @@ -42,6 +42,7 @@ import { fetchRecentComments, type RenderedComment, } from './shared/linear-feedback'; +import { type GRANT_HEALTH_PROBE_EVENT, isGrantHealthProbe, probeLinearGrants } from './shared/linear-grant-health'; import { probeLinearIssueContext, renderIssueContextHint, @@ -730,8 +731,42 @@ type BuilderResolvedToken = { vaultUserId?: string; }; +/** + * Grant health probe (#1004), invoked twice a day by the concurrency reconciler. Runs + * in this Lambda because it already holds + * the token-refresh grants, the registry write for the revocation latch and the + * OperationalAlerts publish, so a dead grant reuses the #812 announce path. + */ +async function runGrantHealthProbe(): Promise { + if (!WORKSPACE_REGISTRY_TABLE) { + logger.error('Linear grant health probe skipped: LINEAR_WORKSPACE_REGISTRY_TABLE_NAME not set'); + return; + } + const table = WORKSPACE_REGISTRY_TABLE; + const report = await probeLinearGrants(ddb, table, id => resolveLinearOauthToken(id, table)); + const fields = { + checked: report.checked, + healthy: report.healthy, + unhealthy: report.unhealthy, + revoked: report.revoked, + }; + if (report.unhealthy.length > 0) { + logger.warn('Linear grant health probe: some workspaces have no usable token — run `bgagent linear setup `', fields); + } else { + logger.info('Linear grant health probe', fields); + } +} + +export async function handler(event: ProcessorEvent | typeof GRANT_HEALTH_PROBE_EVENT): Promise { + if (isGrantHealthProbe(event)) { + await runGrantHealthProbe(); + return; + } + await processWebhookEvent(event); +} + // eslint-disable-next-line complexity -- predates the ceiling (118, down from 120 when it landed); must not grow -export async function handler(event: ProcessorEvent): Promise { +async function processWebhookEvent(event: ProcessorEvent): Promise { if (!event.raw_body) { logger.error('Linear webhook processor invoked without raw_body'); return; diff --git a/cdk/src/handlers/reconcile-concurrency.ts b/cdk/src/handlers/reconcile-concurrency.ts index 008f0e8a2..55307f2d2 100644 --- a/cdk/src/handlers/reconcile-concurrency.ts +++ b/cdk/src/handlers/reconcile-concurrency.ts @@ -18,6 +18,8 @@ */ import { DynamoDBClient, ScanCommand, QueryCommand, UpdateItemCommand } from '@aws-sdk/client-dynamodb'; +import { InvocationType, InvokeCommand, LambdaClient } from '@aws-sdk/client-lambda'; +import { GRANT_HEALTH_PROBE_EVENT, isProbeTick } from './shared/linear-grant-health'; import { logger } from './shared/logger'; import { makeClient } from './shared/ua'; @@ -60,8 +62,37 @@ async function countActiveTasks(userId: string): Promise { * Scheduled handler: scan the concurrency table and reconcile each user's * active_count against actual active tasks in the task table. */ +const LINEAR_GRANT_PROBE_FUNCTION_ARN = process.env.LINEAR_GRANT_PROBE_FUNCTION_ARN; +const RECONCILER_TICK_MINUTES = Number(process.env.RECONCILER_TICK_MINUTES); +const lambdaClient = LINEAR_GRANT_PROBE_FUNCTION_ARN ? makeClient(LambdaClient) : undefined; + +/** + * Kick the Linear grant health probe (#1004) on one tick per 12 h. Fire-and-forget + * (async invoke) and best-effort: a probe problem must never affect reconciliation. + */ +export async function triggerLinearGrantProbe(nowMs: number = Date.now()): Promise { + if (!lambdaClient || !LINEAR_GRANT_PROBE_FUNCTION_ARN || !isProbeTick(nowMs, RECONCILER_TICK_MINUTES)) { + return false; + } + try { + await lambdaClient.send(new InvokeCommand({ + FunctionName: LINEAR_GRANT_PROBE_FUNCTION_ARN, + InvocationType: InvocationType.Event, + Payload: Buffer.from(JSON.stringify(GRANT_HEALTH_PROBE_EVENT)), + })); + logger.info('Triggered the Linear grant health probe'); + return true; + } catch (err) { + logger.warn('Could not trigger the Linear grant health probe', { + error: err instanceof Error ? err.message : String(err), + }); + return false; + } +} + export async function handler(): Promise { logger.info('Concurrency reconciler started'); + await triggerLinearGrantProbe(); let corrected = 0; let scanned = 0; let errors = 0; diff --git a/cdk/src/handlers/shared/linear-grant-health.ts b/cdk/src/handlers/shared/linear-grant-health.ts new file mode 100644 index 000000000..3b5d31dd6 --- /dev/null +++ b/cdk/src/handlers/shared/linear-grant-health.ts @@ -0,0 +1,128 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Scheduled Linear grant health probe (#1004). + * + * Revocation detection (#812) runs only when something needs a Linear token, which + * means when a Linear event arrives. A workspace whose webhook stopped delivering, or + * that nobody used for a while, therefore never re-detects a dead grant: observed + * live, a workspace sat with an expired refresh token for months with one ERROR log + * line. Linear refresh tokens also expire when unused, so the outage was preventable. + * + * The probe resolves a token for every active workspace on a schedule. That does two + * jobs with the existing code path: + * - it refreshes expiring access tokens, which keeps an idle refresh token alive; + * - a grant Linear rejects goes through the resolver's revocation recorder, which + * latches the workspace and announces it on OperationalAlerts (once). + */ + +import { ScanCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; + +/** How often each workspace is probed. Linear access tokens last about a day. */ +export const GRANT_HEALTH_PROBE_INTERVAL_HOURS = 12; + +const MS_PER_MINUTE = 60_000; +const MS_PER_HOUR = 3_600_000; + +/** Async invocation payload that selects probe mode in the webhook processor. */ +export const GRANT_HEALTH_PROBE_EVENT = { grant_health_probe: true } as const; + +export function isGrantHealthProbe(event: unknown): event is typeof GRANT_HEALTH_PROBE_EVENT { + return typeof event === 'object' && event !== null + && (event as Record).grant_health_probe === true; +} + +/** + * True on exactly one tick per interval for a job that runs every `tickMinutes`: + * the tick falling in the half-open window `[k * interval, k * interval + tick)`. + * Ticks are `tick` apart, so each window holds exactly one. A nonsensical cadence + * probes every tick rather than never, so a misconfiguration cannot silently + * disable detection. + */ +export function isProbeTick( + nowMs: number, + tickMinutes: number, + intervalHours: number = GRANT_HEALTH_PROBE_INTERVAL_HOURS, +): boolean { + const tickMs = tickMinutes * MS_PER_MINUTE; + const intervalMs = intervalHours * MS_PER_HOUR; + if (!(tickMs > 0) || !(intervalMs > 0) || tickMs >= intervalMs) return true; + return nowMs % intervalMs < tickMs; +} + +export interface GrantHealthReport { + readonly checked: number; + readonly healthy: number; + /** Slugs (or ids when a row has no slug) whose token could not be resolved. */ + readonly unhealthy: readonly string[]; + /** Rows already latched `revoked`; not re-probed, they were already announced. */ + readonly revoked: readonly string[]; +} + +interface RegistryRow { + readonly linear_workspace_id?: string; + readonly workspace_slug?: string; + readonly status?: string; +} + +/** + * Resolve a token for every active registry row, sequentially (a handful of + * workspaces; sequential keeps the probe gentle on Linear's token endpoint). + */ +export async function probeLinearGrants( + ddb: DynamoDBDocumentClient, + registryTableName: string, + resolve: (linearWorkspaceId: string) => Promise, +): Promise { + const rows: RegistryRow[] = []; + let startKey: Record | undefined; + do { + const page = await ddb.send(new ScanCommand({ + TableName: registryTableName, + ProjectionExpression: 'linear_workspace_id, workspace_slug, #status', + ExpressionAttributeNames: { '#status': 'status' }, + ExclusiveStartKey: startKey, + })); + rows.push(...(page.Items ?? []) as RegistryRow[]); + startKey = page.LastEvaluatedKey; + } while (startKey); + + let healthy = 0; + const unhealthy: string[] = []; + const revoked: string[] = []; + let checked = 0; + for (const row of rows) { + if (!row.linear_workspace_id) continue; + const label = row.workspace_slug ?? row.linear_workspace_id; + if (row.status !== 'active') { + revoked.push(label); + continue; + } + checked++; + try { + if (await resolve(row.linear_workspace_id)) healthy++; + else unhealthy.push(label); + } catch { + // One workspace's failure must not hide the others. + unhealthy.push(label); + } + } + return { checked, healthy, unhealthy, revoked }; +} diff --git a/cdk/src/stacks/agent.ts b/cdk/src/stacks/agent.ts index ae4b15389..fd1815534 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -1535,7 +1535,7 @@ export class AgentStack extends Stack { const concurrencyMaintenance = new NestedStack(this, 'ConcurrencyMaintenance'); // --- Concurrency counter reconciler (drift correction) --- - new ConcurrencyReconciler(concurrencyMaintenance, 'ConcurrencyReconciler', { + const concurrencyReconciler = new ConcurrencyReconciler(concurrencyMaintenance, 'ConcurrencyReconciler', { taskTable: taskTable.table, userConcurrencyTable: userConcurrencyTable.table, }); @@ -2222,6 +2222,9 @@ export class AgentStack extends Stack { // not exist yet at this point in the constructor. if (linearIntegration) { operationalAlerts.grantPublish(linearIntegration.webhookProcessorFn); + // #1004: the reconciler kicks the processor's grant health probe twice a day, so a + // grant that dies while nobody uses Linear is still detected and announced here. + concurrencyReconciler.triggerLinearGrantProbe(linearIntegration.webhookProcessorFn); linearIntegration.webhookProcessorFn.addEnvironment( 'OPERATIONAL_ALERT_TOPIC_ARN', operationalAlerts.topic.topicArn, diff --git a/cdk/test/constructs/concurrency-reconciler.test.ts b/cdk/test/constructs/concurrency-reconciler.test.ts index 34e1e88e4..e3d9f82ef 100644 --- a/cdk/test/constructs/concurrency-reconciler.test.ts +++ b/cdk/test/constructs/concurrency-reconciler.test.ts @@ -20,6 +20,7 @@ import { App, Stack } from 'aws-cdk-lib'; import { Template, Match } from 'aws-cdk-lib/assertions'; import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; +import * as lambda from 'aws-cdk-lib/aws-lambda'; import { ConcurrencyReconciler } from '../../src/constructs/concurrency-reconciler'; function createStack(): Template { @@ -70,3 +71,41 @@ describe('ConcurrencyReconciler construct', () => { }); }); }); + +describe('ConcurrencyReconciler Linear grant probe trigger (#1004)', () => { + function build(withProbe: boolean): Template { + const stack = new Stack(new App(), 'ProbeStack'); + const table = (id: string, pk: string) => new dynamodb.Table(stack, id, { + partitionKey: { name: pk, type: dynamodb.AttributeType.STRING }, + }); + const reconciler = new ConcurrencyReconciler(stack, 'ConcurrencyReconciler', { + taskTable: table('Tasks', 'task_id'), + userConcurrencyTable: table('Users', 'user_id'), + }); + const processor = new lambda.Function(stack, 'Processor', { + runtime: lambda.Runtime.NODEJS_22_X, handler: 'index.handler', code: lambda.Code.fromInline('exports.handler=async()=>{}'), + }); + if (withProbe) reconciler.triggerLinearGrantProbe(processor); + return Template.fromStack(stack); + } + + test('grants invoke and passes the target without adding any resource', () => { + const without = build(false); + const template = build(true); + const types = (t: Template) => Object.entries(t.toJSON().Resources as Record) + .map(([id, r]) => `${r.Type} ${id}`).sort(); + + expect(types(template)).toEqual(types(without)); + template.hasResourceProperties('AWS::Lambda::Function', { + Environment: { + Variables: Match.objectLike({ + RECONCILER_TICK_MINUTES: '15', + LINEAR_GRANT_PROBE_FUNCTION_ARN: { 'Fn::GetAtt': [Match.stringLikeRegexp('Processor'), 'Arn'] }, + }), + }, + }); + template.hasResourceProperties('AWS::IAM::Policy', { + PolicyDocument: { Statement: Match.arrayWith([Match.objectLike({ Action: 'lambda:InvokeFunction' })]) }, + }); + }); +}); diff --git a/cdk/test/handlers/linear-webhook-processor.test.ts b/cdk/test/handlers/linear-webhook-processor.test.ts index 79f53882f..ec51f8434 100644 --- a/cdk/test/handlers/linear-webhook-processor.test.ts +++ b/cdk/test/handlers/linear-webhook-processor.test.ts @@ -25,6 +25,7 @@ jest.mock('@aws-sdk/client-dynamodb', () => ({ DynamoDBClient: jest.fn(() => ({} jest.mock('@aws-sdk/lib-dynamodb', () => ({ DynamoDBDocumentClient: { from: jest.fn(() => ({ send: ddbSend })) }, GetCommand: jest.fn((input: unknown) => ({ _type: 'Get', input })), + ScanCommand: jest.fn((input: unknown) => ({ _type: 'Scan', input })), })); const createTaskCoreMock = jest.fn(); @@ -132,6 +133,34 @@ function issue(overrides: Record = {}): Record }; } +describe('linear-webhook-processor scheduled grant health probe (#1004)', () => { + beforeEach(() => { + ddbSend.mockReset(); + createTaskCoreMock.mockReset(); + resolveLinearOauthTokenMock.mockReset(); + }); + + test('the probe event resolves every active workspace and never takes the webhook path', async () => { + ddbSend.mockResolvedValueOnce({ + Items: [ + { linear_workspace_id: 'ws-live', workspace_slug: 'live', status: 'active' }, + { linear_workspace_id: 'ws-dead', workspace_slug: 'dead', status: 'active' }, + { linear_workspace_id: 'ws-latched', workspace_slug: 'latched', status: 'revoked' }, + ], + }); + resolveLinearOauthTokenMock.mockImplementation(async (id: string) => (id === 'ws-live' ? { access_token: 't' } : null)); + + await handler({ grant_health_probe: true }); + + expect(ddbSend.mock.calls[0][0]).toMatchObject({ _type: 'Scan', input: { TableName: 'LinearWorkspaceRegistry' } }); + expect(resolveLinearOauthTokenMock.mock.calls).toEqual([ + ['ws-live', 'LinearWorkspaceRegistry'], + ['ws-dead', 'LinearWorkspaceRegistry'], + ]); + expect(createTaskCoreMock).not.toHaveBeenCalled(); + }); +}); + describe('linear-webhook-processor handler', () => { beforeEach(() => { ddbSend.mockReset(); diff --git a/cdk/test/handlers/reconcile-concurrency-grant-probe.test.ts b/cdk/test/handlers/reconcile-concurrency-grant-probe.test.ts new file mode 100644 index 000000000..4ecf30b57 --- /dev/null +++ b/cdk/test/handlers/reconcile-concurrency-grant-probe.test.ts @@ -0,0 +1,61 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +// The reconciler kicks the Linear grant health probe (#1004). +const mockLambdaSend = jest.fn(); +jest.mock('@aws-sdk/client-lambda', () => ({ + LambdaClient: jest.fn(() => ({ send: mockLambdaSend })), + InvokeCommand: jest.fn((input: unknown) => ({ _type: 'Invoke', input })), + InvocationType: { Event: 'Event' }, +})); +jest.mock('@aws-sdk/client-dynamodb', () => ({ + DynamoDBClient: jest.fn(() => ({ send: jest.fn() })), + ScanCommand: jest.fn(), + QueryCommand: jest.fn(), + UpdateItemCommand: jest.fn(), +})); + +process.env.TASK_TABLE_NAME = 'Tasks'; +process.env.USER_CONCURRENCY_TABLE_NAME = 'UserConcurrency'; +process.env.LINEAR_GRANT_PROBE_FUNCTION_ARN = 'arn:aws:lambda:us-east-1:123456789012:function:processor'; +process.env.RECONCILER_TICK_MINUTES = '15'; + +import { triggerLinearGrantProbe } from '../../src/handlers/reconcile-concurrency'; + +const WINDOW = 12 * 3_600_000; + +beforeEach(() => mockLambdaSend.mockReset()); + +test('async-invokes the processor with the probe event on the window tick only', async () => { + mockLambdaSend.mockResolvedValue({}); + expect(await triggerLinearGrantProbe(WINDOW * 100 + 60_000)).toBe(true); + expect(mockLambdaSend).toHaveBeenCalledTimes(1); + const { input } = mockLambdaSend.mock.calls[0][0]; + expect(input.FunctionName).toBe(process.env.LINEAR_GRANT_PROBE_FUNCTION_ARN); + expect(input.InvocationType).toBe('Event'); + expect(JSON.parse(Buffer.from(input.Payload).toString())).toEqual({ grant_health_probe: true }); + + expect(await triggerLinearGrantProbe(WINDOW * 100 + 20 * 60_000)).toBe(false); + expect(mockLambdaSend).toHaveBeenCalledTimes(1); +}); + +test('an invoke failure never breaks the reconciler', async () => { + mockLambdaSend.mockRejectedValue(new Error('throttled')); + await expect(triggerLinearGrantProbe(WINDOW * 7)).resolves.toBe(false); +}); diff --git a/cdk/test/handlers/shared/linear-grant-health.test.ts b/cdk/test/handlers/shared/linear-grant-health.test.ts new file mode 100644 index 000000000..d4f8eb193 --- /dev/null +++ b/cdk/test/handlers/shared/linear-grant-health.test.ts @@ -0,0 +1,98 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { + GRANT_HEALTH_PROBE_EVENT, + isGrantHealthProbe, + isProbeTick, + probeLinearGrants, +} from '../../../src/handlers/shared/linear-grant-health'; + +function fakeDdb(pages: Array<{ Items: unknown[]; LastEvaluatedKey?: Record }>) { + const send = jest.fn(); + for (const page of pages) send.mockResolvedValueOnce(page); + return { client: { send } as unknown as DynamoDBDocumentClient, send }; +} + +describe('isGrantHealthProbe', () => { + test('recognises only the scheduled probe input', () => { + expect(isGrantHealthProbe(GRANT_HEALTH_PROBE_EVENT)).toBe(true); + expect(isGrantHealthProbe({ raw_body: '{}' })).toBe(false); + expect(isGrantHealthProbe({ grant_health_probe: 'true' })).toBe(false); + expect(isGrantHealthProbe(null)).toBe(false); + }); +}); + +describe('isProbeTick', () => { + const HOUR = 3_600_000; + test('fires on exactly one 15-minute tick per 12-hour window, wherever the ticks start', () => { + for (const offsetMs of [0, 7 * 60_000, 14 * 60_000 + 59_999]) { + const fired: number[] = []; + for (let t = offsetMs; t < 48 * HOUR; t += 15 * 60_000) if (isProbeTick(t, 15)) fired.push(t); + expect(fired).toHaveLength(4); + expect(fired.map(t => Math.floor(t / (12 * HOUR)))).toEqual([0, 1, 2, 3]); + } + }); + + test('a nonsensical cadence probes every tick instead of never', () => { + expect(isProbeTick(5 * HOUR, Number.NaN)).toBe(true); + expect(isProbeTick(5 * HOUR, 0)).toBe(true); + expect(isProbeTick(5 * HOUR, 15, Number.NaN)).toBe(true); + }); +}); + +describe('probeLinearGrants', () => { + test('pages the registry and resolves every active workspace, skipping latched ones', async () => { + const { client, send } = fakeDdb([ + { + Items: [ + { linear_workspace_id: 'ws-1', workspace_slug: 'alpha', status: 'active' }, + { linear_workspace_id: 'ws-2', workspace_slug: 'beta', status: 'revoked' }, + ], + LastEvaluatedKey: { linear_workspace_id: 'ws-2' }, + }, + { Items: [{ linear_workspace_id: 'ws-3', workspace_slug: 'gamma', status: 'active' }] }, + ]); + const resolve = jest.fn(async (id: string) => (id === 'ws-1' ? { access_token: 't' } : null)); + + const report = await probeLinearGrants(client, 'Registry', resolve); + + expect(resolve.mock.calls.map(([id]) => id)).toEqual(['ws-1', 'ws-3']); + expect(report).toEqual({ checked: 2, healthy: 1, unhealthy: ['gamma'], revoked: ['beta'] }); + expect(send).toHaveBeenCalledTimes(2); + expect(send.mock.calls[1][0].input.ExclusiveStartKey).toEqual({ linear_workspace_id: 'ws-2' }); + }); + + test('one workspace throwing does not hide the others', async () => { + const { client } = fakeDdb([{ + Items: [ + { linear_workspace_id: 'ws-1', workspace_slug: 'alpha', status: 'active' }, + { linear_workspace_id: 'ws-2', status: 'active' }, + ], + }]); + const resolve = jest.fn() + .mockRejectedValueOnce(new Error('throttled')) + .mockResolvedValueOnce({ access_token: 't' }); + + expect(await probeLinearGrants(client, 'Registry', resolve)).toEqual({ + checked: 2, healthy: 1, unhealthy: ['alpha'], revoked: [], + }); + }); +}); diff --git a/docs/guides/LINEAR_SETUP_GUIDE.md b/docs/guides/LINEAR_SETUP_GUIDE.md index 09189f5a6..4d8b84478 100644 --- a/docs/guides/LINEAR_SETUP_GUIDE.md +++ b/docs/guides/LINEAR_SETUP_GUIDE.md @@ -337,6 +337,18 @@ If the app has been edited repeatedly through failed saves, creating a fresh app - Is the label spelled as configured? Matching is case-insensitive but must be the same word. - Check CloudWatch for `WebhookFn` and `WebhookProcessorFn`. Common: `Invalid Linear webhook signature`, `Linear workspace is not onboarded`, `Linear project is not onboarded`, `Linear actor has no linked platform user`. +### Linear stops responding and an "authorization revoked" alert arrives + +ABCA probes every registered workspace's grant every 12 hours, as well as whenever an event needs a token. The probe refreshes tokens that are about to expire, which keeps a grant alive even when nobody uses Linear for a while. If Linear rejects a grant, the workspace is marked `revoked` and one alert goes to the **OperationalAlerts** SNS topic (stack output `OperationalAlertsTopicArn`). Subscribe an email or chat endpoint to it, or deploy with `-c alertEmail=…`, because it ships with no subscribers. + +To recover, re-authorize the workspace: + +```bash +bgagent linear setup +``` + +The probe's summary is in the `WebhookProcessorFn` logs ("Linear grant health probe"), listing any workspace without a usable token. + ### Webhook signature verification fails repeatedly The stored signing secret doesn't match the subscription Linear is sending from — usually because the webhook was configured in Linear without telling ABCA, or the secret was rotated: diff --git a/docs/src/content/docs/using/Linear-setup-guide.md b/docs/src/content/docs/using/Linear-setup-guide.md index e60ee28e0..e83f0b304 100644 --- a/docs/src/content/docs/using/Linear-setup-guide.md +++ b/docs/src/content/docs/using/Linear-setup-guide.md @@ -339,6 +339,18 @@ If the app has been edited repeatedly through failed saves, creating a fresh app - Is the label spelled as configured? Matching is case-insensitive but must be the same word. - Check CloudWatch for `WebhookFn` and `WebhookProcessorFn`. Common: `Invalid Linear webhook signature`, `Linear workspace is not onboarded`, `Linear project is not onboarded`, `Linear actor has no linked platform user`. +### Linear stops responding and an "authorization revoked" alert arrives + +ABCA probes every registered workspace's grant every 12 hours, as well as whenever an event needs a token. The probe refreshes tokens that are about to expire, which keeps a grant alive even when nobody uses Linear for a while. If Linear rejects a grant, the workspace is marked `revoked` and one alert goes to the **OperationalAlerts** SNS topic (stack output `OperationalAlertsTopicArn`). Subscribe an email or chat endpoint to it, or deploy with `-c alertEmail=…`, because it ships with no subscribers. + +To recover, re-authorize the workspace: + +```bash +bgagent linear setup +``` + +The probe's summary is in the `WebhookProcessorFn` logs ("Linear grant health probe"), listing any workspace without a usable token. + ### Webhook signature verification fails repeatedly The stored signing secret doesn't match the subscription Linear is sending from — usually because the webhook was configured in Linear without telling ABCA, or the secret was rotated: From 9586e84302777d128b8704e8e828ecd36dcc8feb Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Mon, 16 Nov 2026 01:38:14 +0000 Subject: [PATCH 09/27] refactor(linear): GRANT_HEALTH_PROBE_INTERVAL_HOURS is used only in its own file (knip) (cherry picked from commit 702cdbe8335d7fcc90940d50c9d65f67e14e2b4d) --- cdk/src/handlers/shared/linear-grant-health.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cdk/src/handlers/shared/linear-grant-health.ts b/cdk/src/handlers/shared/linear-grant-health.ts index 3b5d31dd6..1d0c2da94 100644 --- a/cdk/src/handlers/shared/linear-grant-health.ts +++ b/cdk/src/handlers/shared/linear-grant-health.ts @@ -36,7 +36,7 @@ import { ScanCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; /** How often each workspace is probed. Linear access tokens last about a day. */ -export const GRANT_HEALTH_PROBE_INTERVAL_HOURS = 12; +const GRANT_HEALTH_PROBE_INTERVAL_HOURS = 12; const MS_PER_MINUTE = 60_000; const MS_PER_HOUR = 3_600_000; From b2d083ab1f318f88b72f1bd7cf7da43032f8c9e2 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 5 Nov 2026 15:49:42 +0000 Subject: [PATCH 10/27] fix(linear): approval notices and approve/deny replies on Linear issues (#1001) Post an approval-request notice on the task's Linear issue when a Cedar gate opens, and one outcome comment when it resolves (approved, denied, timed out, stranded). Notices go through the existing fan-out Linear dispatcher and workspace token resolver, are rendered from the saved approval row, and are idempotent per request via delivery markers and deterministic comment IDs. The linked task owner can reply `approve` or `deny [reason]` to the notice. The processor re-reads the comment from Linear (bot actors, the app's own identity, and issue/parent/body mismatches are ignored), checks the replier maps to the task owner, and records the decision through the same approve/deny code path as the API, tagged with a Linear decision_source. Non-owner, stale and duplicate replies get a same-thread explanation. API and CLI behaviour is unchanged; webhook signature verification is untouched. No new CloudFormation resources. (cherry picked from commit 4567ba69b0c896a6183d9f9981d63e505bdcf40f) --- cdk/package.json | 3 + cdk/src/constructs/fanout-consumer.ts | 11 + cdk/src/constructs/linear-integration.ts | 12 + cdk/src/handlers/approve-task.ts | 39 ++- cdk/src/handlers/deny-task.ts | 39 ++- cdk/src/handlers/fanout-task-events.ts | 71 +++++- cdk/src/handlers/linear-webhook-processor.ts | 12 + cdk/src/handlers/shared/approval-decision.ts | 2 +- .../handlers/shared/approval-notifications.ts | 233 ++++++++++++++++++ .../handlers/shared/linear-approval-reply.ts | 140 +++++++++++ .../handlers/shared/linear-approval-thread.ts | 112 +++++++++ .../shared/linear-channel-metadata.ts | 2 + cdk/src/handlers/shared/linear-feedback.ts | 69 ++++++ cdk/src/stacks/agent.ts | 2 + cdk/test/constructs/fanout-consumer.test.ts | 42 ++++ .../constructs/linear-integration.test.ts | 65 +++++ cdk/test/handlers/approve-task.test.ts | 38 ++- cdk/test/handlers/deny-task.test.ts | 38 ++- cdk/test/handlers/fanout-task-events.test.ts | 98 ++++++++ ...r-webhook-processor-approval-reply.test.ts | 114 +++++++++ .../shared/approval-notifications.test.ts | 203 +++++++++++++++ .../shared/linear-approval-reply.test.ts | 226 +++++++++++++++++ .../shared/linear-approval-thread.test.ts | 86 +++++++ docs/guides/LINEAR_SETUP_GUIDE.md | 11 + .../content/docs/using/Linear-setup-guide.md | 11 + 25 files changed, 1663 insertions(+), 16 deletions(-) create mode 100644 cdk/src/handlers/shared/approval-notifications.ts create mode 100644 cdk/src/handlers/shared/linear-approval-reply.ts create mode 100644 cdk/src/handlers/shared/linear-approval-thread.ts create mode 100644 cdk/test/handlers/linear-webhook-processor-approval-reply.test.ts create mode 100644 cdk/test/handlers/shared/approval-notifications.test.ts create mode 100644 cdk/test/handlers/shared/linear-approval-reply.test.ts create mode 100644 cdk/test/handlers/shared/linear-approval-thread.test.ts diff --git a/cdk/package.json b/cdk/package.json index 97fe923d8..c444402fc 100644 --- a/cdk/package.json +++ b/cdk/package.json @@ -144,6 +144,9 @@ "tsconfig": "tsconfig.jest.json" } ] + }, + "moduleNameMapper": { + "^(\\.{1,2}/.*)\\.js$": "$1" } } } diff --git a/cdk/src/constructs/fanout-consumer.ts b/cdk/src/constructs/fanout-consumer.ts index 9c9f821d7..d2909e895 100644 --- a/cdk/src/constructs/fanout-consumer.ts +++ b/cdk/src/constructs/fanout-consumer.ts @@ -63,6 +63,13 @@ export interface FanOutConsumerProps { */ readonly taskTable?: dynamodb.ITable; + /** + * Approval state for channel approval notices (#1001): the dispatcher renders + * from the saved row, records per-request delivery receipts and the Linear + * reply-thread mapping. + */ + readonly taskApprovalsTable?: dynamodb.ITable; + /** * RepoTable — GitHub dispatcher reads per-repo * `github_token_secret_arn` overrides. Optional: if omitted, falls @@ -224,6 +231,10 @@ export class FanOutConsumer extends Construct { props.taskTable.grantReadWriteData(this.fn); this.fn.addEnvironment('TASK_TABLE_NAME', props.taskTable.tableName); } + if (props.taskApprovalsTable) { + props.taskApprovalsTable.grant(this.fn, 'dynamodb:GetItem', 'dynamodb:UpdateItem'); + this.fn.addEnvironment('TASK_APPROVALS_TABLE_NAME', props.taskApprovalsTable.tableName); + } if (props.repoTable) { props.repoTable.grantReadData(this.fn); this.fn.addEnvironment('REPO_TABLE_NAME', props.repoTable.tableName); diff --git a/cdk/src/constructs/linear-integration.ts b/cdk/src/constructs/linear-integration.ts index dac4a36d3..80441f0b1 100644 --- a/cdk/src/constructs/linear-integration.ts +++ b/cdk/src/constructs/linear-integration.ts @@ -78,6 +78,13 @@ export interface LinearIntegrationProps { /** The DynamoDB task events table. */ readonly taskEventsTable: dynamodb.ITable; + /** + * Enables task-owner approve/deny decisions from replies to Linear approval + * notices (#1001). The processor reads the reply thread mapping and records + * the decision through the same handler path as the API. + */ + readonly taskApprovalsTable?: dynamodb.ITable; + /** Monthly user/team budget configuration and spend table. */ readonly budgetTable?: dynamodb.ITable; @@ -301,6 +308,9 @@ export class LinearIntegration extends Construct { TASK_EVENTS_TABLE_NAME: props.taskEventsTable.tableName, TASK_RETENTION_DAYS: String(props.taskRetentionDays ?? DEFAULT_TASK_RETENTION_DAYS), }; + if (props.taskApprovalsTable) { + createTaskEnv.TASK_APPROVALS_TABLE_NAME = props.taskApprovalsTable.tableName; + } if (props.repoTable) { createTaskEnv.REPO_TABLE_NAME = props.repoTable.tableName; } @@ -455,6 +465,8 @@ export class LinearIntegration extends Construct { } props.taskTable.grantReadWriteData(webhookProcessorFn); props.taskEventsTable.grantReadWriteData(webhookProcessorFn); + // Approval replies: thread mapping, rate-limit counter and the decision. + props.taskApprovalsTable?.grantReadWriteData(webhookProcessorFn); if (props.repoTable) { props.repoTable.grantReadData(webhookProcessorFn); } diff --git a/cdk/src/handlers/approve-task.ts b/cdk/src/handlers/approve-task.ts index 5cb0c3938..9349a75fc 100644 --- a/cdk/src/handlers/approve-task.ts +++ b/cdk/src/handlers/approve-task.ts @@ -68,25 +68,50 @@ const AUDIT_EVENT_RETENTION_DAYS = Number(process.env.TASK_RETENTION_DAYS ?? '90 export async function handler( event: APIGatewayProxyEvent, context?: Pick, ): Promise { - const invocationStartedMs = Date.now(); + return recordApprovalForUser({ + userId: extractUserId(event), + taskId: event.pathParameters?.task_id, + body: event.body, + invocationStartedMs: Date.now(), + context, + }); +} + +/** + * Shared decision path for the API and Linear approval replies. Callers must + * authenticate and map the platform user first; this applies the same + * validation, rate limit, owner and state checks as the API. + * ``decisionSource`` records where a non-API decision came from. + */ +export async function recordApprovalForUser(input: { + userId: string | null; + taskId?: string; + body?: string | null; + decisionSource?: string; + /** API invocation start and Lambda context bound the post-commit MicroVM wake. */ + invocationStartedMs?: number; + context?: Pick; +}): Promise { + const invocationStartedMs = input.invocationStartedMs ?? Date.now(); + const context = input.context; const requestId = ulid(); try { // 1. Auth - const callerUserId = extractUserId(event); + const callerUserId = input.userId; if (!callerUserId) { return errorResponse(401, ErrorCode.UNAUTHORIZED, 'Missing or invalid authentication.', requestId); } // 2. Path + body - const taskId = event.pathParameters?.task_id; + const taskId = input.taskId; if (!taskId) { return errorResponse(400, ErrorCode.VALIDATION_ERROR, 'Missing task_id path parameter.', requestId); } let parsed: ApprovalRequest | null = null; try { - parsed = event.body ? JSON.parse(event.body) as ApprovalRequest : null; + parsed = input.body ? JSON.parse(input.body) as ApprovalRequest : null; } catch { return errorResponse(400, ErrorCode.VALIDATION_ERROR, 'Request body must be valid JSON.', requestId); } @@ -172,7 +197,8 @@ export async function handler( TableName: TASK_APPROVALS_TABLE_NAME, Key: { task_id: taskId, request_id }, UpdateExpression: - 'SET #status = :approved, decided_at = :now, #scope = :scope', + 'SET #status = :approved, decided_at = :now, #scope = :scope' + + (input.decisionSource ? ', decision_source = :source' : ''), ConditionExpression: 'attribute_exists(request_id) AND #status = :pending AND user_id = :caller ' + 'AND (attribute_not_exists(deadline_epoch) OR deadline_epoch > :epoch)', @@ -187,6 +213,7 @@ export async function handler( ':scope': scope, ':caller': callerUserId, ':epoch': nowEpoch, + ...(input.decisionSource ? { ':source': input.decisionSource } : {}), }, }, }, @@ -224,7 +251,7 @@ export async function handler( callerUserId, requestId: request_id, decision: 'APPROVED', - auditMetadata: { scope: scope }, + auditMetadata: { ...(input.decisionSource ? { decision_source: input.decisionSource } : {}), scope: scope }, decidedAt: nowIso, nowEpoch, retentionDays: AUDIT_EVENT_RETENTION_DAYS, diff --git a/cdk/src/handlers/deny-task.ts b/cdk/src/handlers/deny-task.ts index 0c8f048ec..9e8b831b3 100644 --- a/cdk/src/handlers/deny-task.ts +++ b/cdk/src/handlers/deny-task.ts @@ -66,25 +66,50 @@ const AUDIT_EVENT_RETENTION_DAYS = Number(process.env.TASK_RETENTION_DAYS ?? '90 export async function handler( event: APIGatewayProxyEvent, context?: Pick, ): Promise { - const invocationStartedMs = Date.now(); + return recordDenialForUser({ + userId: extractUserId(event), + taskId: event.pathParameters?.task_id, + body: event.body, + invocationStartedMs: Date.now(), + context, + }); +} + +/** + * Shared decision path for the API and Linear approval replies. Callers must + * authenticate and map the platform user first; this applies the same + * validation, rate limit, owner and state checks as the API. + * ``decisionSource`` records where a non-API decision came from. + */ +export async function recordDenialForUser(input: { + userId: string | null; + taskId?: string; + body?: string | null; + decisionSource?: string; + /** API invocation start and Lambda context bound the post-commit MicroVM wake. */ + invocationStartedMs?: number; + context?: Pick; +}): Promise { + const invocationStartedMs = input.invocationStartedMs ?? Date.now(); + const context = input.context; const requestId = ulid(); try { // 1. Auth - const callerUserId = extractUserId(event); + const callerUserId = input.userId; if (!callerUserId) { return errorResponse(401, ErrorCode.UNAUTHORIZED, 'Missing or invalid authentication.', requestId); } // 2. Path + body - const taskId = event.pathParameters?.task_id; + const taskId = input.taskId; if (!taskId) { return errorResponse(400, ErrorCode.VALIDATION_ERROR, 'Missing task_id path parameter.', requestId); } let parsed: DenyRequest | null = null; try { - parsed = event.body ? JSON.parse(event.body) as DenyRequest : null; + parsed = input.body ? JSON.parse(input.body) as DenyRequest : null; } catch { return errorResponse(400, ErrorCode.VALIDATION_ERROR, 'Request body must be valid JSON.', requestId); } @@ -163,7 +188,8 @@ export async function handler( TableName: TASK_APPROVALS_TABLE_NAME, Key: { task_id: taskId, request_id }, UpdateExpression: - 'SET #status = :denied, decided_at = :now, deny_reason = :reason', + 'SET #status = :denied, decided_at = :now, deny_reason = :reason' + + (input.decisionSource ? ', decision_source = :source' : ''), ConditionExpression: 'attribute_exists(request_id) AND #status = :pending AND user_id = :caller ' + 'AND (attribute_not_exists(deadline_epoch) OR deadline_epoch > :epoch)', @@ -175,6 +201,7 @@ export async function handler( ':reason': sanitizedReason, ':caller': callerUserId, ':epoch': nowEpoch, + ...(input.decisionSource ? { ':source': input.decisionSource } : {}), }, }, }, @@ -211,7 +238,7 @@ export async function handler( callerUserId, requestId: request_id, decision: 'DENIED', - auditMetadata: { reason: sanitizedReason }, + auditMetadata: { ...(input.decisionSource ? { decision_source: input.decisionSource } : {}), reason: sanitizedReason }, decidedAt: nowIso, nowEpoch, retentionDays: AUDIT_EVENT_RETENTION_DAYS, diff --git a/cdk/src/handlers/fanout-task-events.ts b/cdk/src/handlers/fanout-task-events.ts index f3419c4c6..7fe993fc1 100644 --- a/cdk/src/handlers/fanout-task-events.ts +++ b/cdk/src/handlers/fanout-task-events.ts @@ -46,6 +46,10 @@ import type { DynamoDBStreamEvent, } from 'aws-lambda'; import { TaskStatus, TERMINAL_STATUSES } from '../constructs/task-status'; +import { + approvalNotificationMarkdown, isApprovalNotification, loadApprovalNotification, markApprovalNotificationDelivered, + APPROVAL_NOTIFICATION_EVENTS as LINEAR_APPROVAL_EVENTS, +} from './shared/approval-notifications'; import { clearTokenCache, resolveGitHubToken } from './shared/context-hydration'; import { classifyError } from './shared/error-classifier'; import { renderFailureReply } from './shared/failure-reply'; @@ -68,10 +72,12 @@ import { } from './shared/jira-status-comment'; import { addAgentSessionExternalUrl, emitAgentActivity, setAgentSessionPlan, type AgentActivityContent } from './shared/linear-agent-session'; import { isLinearAgentSessionsEnabled, SESSION_STOP_CANCELLED_VIA } from './shared/linear-agent-session-event'; +import { closeLinearApprovalThread, type LinearApprovalThread, saveLinearApprovalThread } from './shared/linear-approval-thread'; import { EMOJI_FAILURE, EMOJI_NEEDS_INPUT, EMOJI_SUCCESS, + postIdentifiedComment, postIssueComment, resolveToken, swapCommentReaction, @@ -228,6 +234,9 @@ export const CHANNEL_DEFAULTS: Record> // even earlier, at task-admission in the webhook processor (ADR-016 P4.5). linear: new Set([ ...TERMINAL_EVENT_TYPES, + // Approval request and outcome notices, rendered from the saved approval + // row with per-request delivery receipts (#1001). + ...LINEAR_APPROVAL_EVENTS, 'pr_created', // Include task_timed_out so a Linear standalone iteration // that TIMES OUT still settles (its 👀→✅/❌ + terminal reply come through the @@ -397,7 +406,11 @@ export function parseStreamRecord(record: DynamoDBRecord): FanOutEvent | null { * ``trajectory_uploaded``, ``trace_truncated``. Only ``pr_created`` * is currently in any channel's default filter (§6.2 Slack + GitHub). */ -const ROUTABLE_MILESTONES: ReadonlySet = new Set(['pr_created', ...LINEAR_SESSION_PROGRESS_MILESTONES]); +// Approval milestones route by name so channels see them as their own event +// type. Slack's dispatcher still drops them at its NOTIFIABLE_EVENTS gate. +const ROUTABLE_MILESTONES: ReadonlySet = new Set([ + 'pr_created', ...LINEAR_APPROVAL_EVENTS, ...LINEAR_SESSION_PROGRESS_MILESTONES, +]); /** * Unwrap ``agent_milestone`` events to their milestone name for @@ -1295,6 +1308,62 @@ async function dispatchToLinear(event: FanOutEvent): Promise { // otherwise read any `agent_milestone` as the PR milestone.) if (progressOnly) return; + const approvalsTable = process.env.TASK_APPROVALS_TABLE_NAME; + const effectiveType = effectiveEventType(event); + if (isApprovalNotification(effectiveType)) { + if (!approvalsTable) { + logger.warn('[fanout/linear] approval notice skipped: TASK_APPROVALS_TABLE_NAME unset', { + event: 'fanout.linear.approval_unconfigured', task_id: event.task_id, + }); + return; + } + // The notice compares the task's live gate with the saved row, so read the + // task consistently: a stale read would silently drop a real request. + const liveTask = (await ddb.send(new GetCommand({ + TableName: process.env.TASK_TABLE_NAME, Key: { task_id: task.task_id }, ConsistentRead: true, + }))).Item as TaskRecord | undefined; + if (!liveTask) return; + const notification = await loadApprovalNotification(ddb, liveTask, effectiveType, event.metadata ?? {}, 'linear'); + if (!notification) return; + const thread: LinearApprovalThread = { + workspaceId, issueId, taskId: task.task_id, requestId: notification.requestId, userId: notification.userId, + }; + const ctx = { linearWorkspaceId: workspaceId, registryTableName }; + const body = approvalNotificationMarkdown(notification); + // Retention follows the saved closure even if Linear cannot take the notice. + if (effectiveType !== 'approval_requested') await closeLinearApprovalThread(ddb, approvalsTable, thread); + const result = effectiveType === 'approval_requested' + ? await postIdentifiedComment(ctx, { id: await saveLinearApprovalThread(ddb, approvalsTable, thread), issueId, body }) + : await postIssueComment(ctx, issueId, body); + if (!result.ok) { + logger.warn('Linear approval notification failed', { + event: 'fanout.linear.approval_post_failed', + task_id: task.task_id, + request_id: notification.requestId, + retryable: result.retryable, + }); + if (result.retryable) throw new Error('Retryable Linear approval notification failure'); + return; + } + await markApprovalNotificationDelivered(ddb, notification); + logger.info('Linear approval notification delivered', { + event: 'fanout.linear.approval_dispatched', task_id: task.task_id, request_id: notification.requestId, + }); + return; // An approval notice never settles the task's final status. + } + // A task that ends while waiting (e.g. cancelled) leaves its reply thread + // open; start its retention so late replies find nothing to decide. + if (approvalsTable && task.awaiting_approval_request_id + && (TERMINAL_EVENT_TYPES as readonly string[]).includes(event.event_type)) { + await closeLinearApprovalThread(ddb, approvalsTable, { + workspaceId, + issueId, + taskId: task.task_id, + requestId: task.awaiting_approval_request_id, + userId: task.user_id, + }); + } + // Iteration-UX: this task is a comment-iteration when it carries a maturing // reply id (set at trigger time). For those, the progress + terminal status // lives in that ONE edited reply, NOT in fresh top-level comments. diff --git a/cdk/src/handlers/linear-webhook-processor.ts b/cdk/src/handlers/linear-webhook-processor.ts index f736b4fed..bff8fb35a 100644 --- a/cdk/src/handlers/linear-webhook-processor.ts +++ b/cdk/src/handlers/linear-webhook-processor.ts @@ -29,6 +29,7 @@ import { createTaskCore } from './shared/create-task-core'; import { renderMaturingReply } from './shared/iteration-reply'; import { AGENT_SESSION_EVENT_TYPE, isLinearAgentSessionsEnabled, type LinearAgentSessionEvent } from './shared/linear-agent-session-event'; import { handleAgentSessionEvent } from './shared/linear-agent-session-handler'; +import { handleLinearApprovalReply } from './shared/linear-approval-reply'; import { cleanupPreScreenedAttachments, downloadScreenAndStoreLinearAttachments, LinearAttachmentError } from './shared/linear-attachments'; import { lookupLinearPlatformUser, @@ -2046,6 +2047,17 @@ function commentTargetBelongsToWorkspace( } async function handleCommentTrigger(payload: LinearCommentEvent): Promise { + // A reply to an approval notice is a decision, not a task request. It is + // handled only for the exact thread ABCA created, and only for the owner. + if (process.env.TASK_APPROVALS_TABLE_NAME && WORKSPACE_REGISTRY_TABLE + && await handleLinearApprovalReply(payload, { + ddb, + approvalsTable: process.env.TASK_APPROVALS_TABLE_NAME, + taskTable: process.env.TASK_TABLE_NAME!, + registryTable: WORKSPACE_REGISTRY_TABLE, + lookupUser: lookupPlatformUser, + })) return; + // Orchestration must be enabled + a workspace token resolvable. if (!ORCHESTRATION_TABLE || !WORKSPACE_REGISTRY_TABLE) { return; diff --git a/cdk/src/handlers/shared/approval-decision.ts b/cdk/src/handlers/shared/approval-decision.ts index 0f5487272..21996e22e 100644 --- a/cdk/src/handlers/shared/approval-decision.ts +++ b/cdk/src/handlers/shared/approval-decision.ts @@ -35,7 +35,7 @@ export interface DecisionPostCommitInput { readonly requestId: string; readonly decision: 'APPROVED' | 'DENIED'; /** Decision-specific audit fields (approve: `scope`; deny: `reason`). */ - readonly auditMetadata: Pick; + readonly auditMetadata: Pick & { readonly decision_source?: string }; readonly decidedAt: string; readonly nowEpoch: number; readonly retentionDays: number; diff --git a/cdk/src/handlers/shared/approval-notifications.ts b/cdk/src/handlers/shared/approval-notifications.ts new file mode 100644 index 000000000..8f5c33546 --- /dev/null +++ b/cdk/src/handlers/shared/approval-notifications.ts @@ -0,0 +1,233 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { GetCommand, UpdateCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { scanDenyReason } from './deny-reason-scanner'; +import { logger } from './logger'; +import type { TaskRecord } from './types'; +import { TaskStatus, TERMINAL_STATUSES } from '../../constructs/task-status'; + +const REQUEST_ID_MAX_LENGTH = 128; +const SEVERITY_MAX_LENGTH = 20; +const SCOPE_MAX_LENGTH = 150; + +/** + * Approval messages for a task's channel. Requests are rendered from the saved + * approval row; outcomes are acknowledged when the decision commits. A task + * cancelled while waiting is reported by the channel's terminal message. + */ +export const APPROVAL_NOTIFICATION_EVENTS = [ + 'approval_requested', 'approval_decision_recorded', 'approval_timed_out', 'approval_stranded', +] as const; + +export function isApprovalNotification(eventType: string): boolean { + return (APPROVAL_NOTIFICATION_EVENTS as readonly string[]).includes(eventType); +} + +export interface ApprovalNotification { + readonly title: string; + readonly text: string; + readonly taskId: string; + readonly requestId: string; + readonly userId: string; + readonly marker: string; +} + +function text(value: unknown, max = 500): string { + if (typeof value !== 'string') return ''; + // Redact before truncation so cutting a token cannot hide its recognizable shape. + const clean = scanDenyReason(value) + .replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '') + .replace(/[\u0000-\u0008\u000b-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, ''); + return clean.length > max ? `${clean.slice(0, max)}… [shortened]` : clean; +} + +/** Describe only recorded arguments; tool names cannot establish intent or safety. */ +function describeAction(row: Record, task: TaskRecord): string[] { + const tool = text(row.tool_name, 100); + const preview = typeof row.tool_input_preview === 'string' ? row.tool_input_preview : ''; + let input: Record | undefined; + try { + const parsed: unknown = JSON.parse(preview); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) input = parsed as Record; + } catch { + // The guest stores a bounded preview, which may end partway through JSON. + } + const quote = (value: unknown) => JSON.stringify(text(value)); + const path = typeof input?.file_path === 'string' ? input.file_path : ''; + const workspace = `/workspace/${task.task_id}/`; + const target = quote(path.startsWith(workspace) ? path.slice(workspace.length) : path); + let action: string; + if (tool === 'Read' && path) { + action = `The agent wants to read the file ${target}.`; + } else if (tool === 'Write' && path) { + action = `The agent wants to write to ${target}, creating the file or replacing its contents.`; + } else if (tool === 'Edit' && path) { + action = `The agent wants to change text in ${target}.`; + } else if (tool === 'Bash') { + action = 'The agent wants to run a shell command.'; + } else if (tool === 'WebFetch' && typeof input?.url === 'string') { + action = `The agent wants to fetch content from ${quote(input.url)}.`; + } else if (tool === 'Glob' || tool === 'Grep') { + action = `The agent wants to search ${tool === 'Glob' ? 'file names' : 'file contents'}.`; + } else { + action = `The agent wants to call the tool ${quote(tool)}.`; + } + const lines = [action]; + if (task.repo) lines.push(`Repository: ${text(task.repo)}`); + if (typeof input?.description === 'string' && input.description.trim()) { + lines.push(`Agent's explanation: ${text(input.description)}`); + } + if (tool === 'Bash' && typeof input?.command === 'string') { + lines.push(`Command: ${quote(input.command)}`); + } + // Always retain the preview: summaries must not hide flags, ranges or edits. + lines.push(`Saved arguments: ${text(preview) || '(not available)'}`); + if (!input || preview.endsWith('...') || preview.length > 500) { + lines.push('The saved arguments are incomplete or could not be interpreted. They may not show the full action.'); + } + return lines; +} + +/** Read saved state instead of showing an old, delayed "please approve" event. */ +export async function loadApprovalNotification( + ddb: DynamoDBDocumentClient, + task: TaskRecord, + eventType: string, + metadata: Record, + channel: 'slack' | 'linear', +): Promise { + if (!isApprovalNotification(eventType)) return null; + const tableName = process.env.TASK_APPROVALS_TABLE_NAME; + if (!tableName) throw new Error('Approval notifications require TASK_APPROVALS_TABLE_NAME'); + // The deployed stranded-task reconciler closes the task, leaves its approval + // row PENDING, and emits a milestone without request_id. Recover that identity + // only from the consistently read, failed owning task and its saved cause. + const legacyStranded = eventType === 'approval_stranded' + && task.status === TaskStatus.FAILED + && metadata.reason === 'STRANDED_NO_HEARTBEAT' + && task.error_message?.startsWith('Approval stranded:'); + const requestId = metadata.request_id ?? (legacyStranded ? task.awaiting_approval_request_id : undefined); + if (!requestId && eventType === 'approval_stranded') { + logger.warn('Stranded approval notification has no saved request identity', { + event: 'approval_notification_request_missing', task_id: task.task_id, + }); + return null; + } + if (typeof requestId !== 'string' || !requestId || requestId.length > REQUEST_ID_MAX_LENGTH) { + throw new Error('Approval notification is missing a valid request_id'); + } + const response = await ddb.send(new GetCommand({ + TableName: tableName, Key: { task_id: task.task_id, request_id: requestId }, ConsistentRead: true, + })); + const row = response.Item; + const marker = `notified_${channel}_${eventType}`; + if (!row || row.user_id !== task.user_id || row[marker]) return null; + const status = legacyStranded && row.status === 'PENDING' + && task.awaiting_approval_request_id === requestId ? 'STRANDED' : row.status; + const expected = eventType === 'approval_requested' ? ['PENDING'] + : eventType === 'approval_decision_recorded' ? ['APPROVED', 'DENIED'] + : eventType === 'approval_timed_out' ? ['TIMED_OUT'] : ['STRANDED']; + if (!expected.includes(status)) return null; + if (status === 'PENDING' + && (task.status !== 'AWAITING_APPROVAL' || task.awaiting_approval_request_id !== requestId)) return null; + + const title = status === 'PENDING' ? 'Approval needed' + : status === 'APPROVED' ? 'Approval recorded' + : status === 'DENIED' ? 'Denial recorded' + : status === 'TIMED_OUT' ? 'Approval request timed out' : 'Approval wait could not continue'; + const lines = [title]; + if (status === 'PENDING') { + lines.push('', ...describeAction(row, task), ''); + const reason = text(row.reason); + lines.push(reason.startsWith('Soft-deny:') + ? 'Why approval is required: your configured policy requires a human decision for this action.' + : `Why approval is required: ${reason || 'No explanation was saved with this request.'}`); + lines.push('Approve: allow this action once.', + 'Deny: block this action and return the decision to the agent.'); + const deadline = Date.parse(row.created_at) + Number(row.timeout_s) * 1000; + if (Number.isFinite(deadline) && Number(row.timeout_s) > 0) { + lines.push(`Decision deadline: ${new Date(deadline).toISOString()}`); + } + if (channel === 'linear') { + lines.push('', 'Reply approve, or deny with an optional reason (for example "deny use the staging config"),', + 'to this comment while signed in as the task owner.'); + } + lines.push('', 'Technical details / CLI alternative', + `Task: ${task.task_id}`, `Request: ${requestId}`, + `Tool: ${text(row.tool_name, 100)}`, `Policy severity: ${text(row.severity, SEVERITY_MAX_LENGTH)}`, + `Policy detail: ${reason}`); + // Never interpolate untrusted text into suggested shell commands. + if ([task.task_id, requestId].every(id => /^[A-Za-z0-9_-]{1,128}$/.test(id))) { + lines.push('Respond using the CLI while signed in as the task owner:', + `bgagent approve ${task.task_id} ${requestId} --scope this_call`, + `bgagent deny ${task.task_id} ${requestId}`); + } + lines.push('Run bgagent pending to see currently open requests.'); + } else if (status === 'APPROVED') { + lines.push(`Task: ${task.task_id}`, `Request: ${requestId}`); + lines.push(`Scope: ${text(row.scope, SCOPE_MAX_LENGTH)}`); + lines.push(TERMINAL_STATUSES.includes(task.status) + ? `The decision is saved. Task status: ${task.status}. The task has already ended.` + : 'The decision is saved. The agent continues with this action.'); + } else if (status === 'DENIED') { + lines.push(`Task: ${task.task_id}`, `Request: ${requestId}`); + lines.push(`Reason: ${text(row.deny_reason) || 'No reason supplied.'}`); + lines.push(TERMINAL_STATUSES.includes(task.status) + ? `The decision is saved. Task status: ${task.status}. The task has already ended.` + : 'The decision is saved. The agent receives the denial and continues without this action.'); + } else { + lines.push(`Task: ${task.task_id}`, `Request: ${requestId}`); + // reason is the original policy explanation, not the cause of closure. + // The agent stores a polling failure in deny_reason on its timeout path. + const reason = status === 'TIMED_OUT' + ? text(row.deny_reason) || 'The configured decision deadline was reached.' + : text(task.error_message) || 'The agent could not continue this approval wait.'; + lines.push(`Reason: ${reason}`); + } + return { title, text: lines.join('\n'), taskId: task.task_id, requestId, userId: task.user_id, marker }; +} + +/** Persist only after the external service accepted the message, so failures retry. */ +export async function markApprovalNotificationDelivered( + ddb: DynamoDBDocumentClient, + notification: ApprovalNotification, +): Promise { + try { + await ddb.send(new UpdateCommand({ + TableName: process.env.TASK_APPROVALS_TABLE_NAME!, + Key: { task_id: notification.taskId, request_id: notification.requestId }, + UpdateExpression: 'SET #marker = :now', + ConditionExpression: 'attribute_exists(task_id) AND user_id = :user', + ExpressionAttributeNames: { '#marker': notification.marker }, + ExpressionAttributeValues: { ':now': new Date().toISOString(), ':user': notification.userId }, + })); + } catch (error) { + if ((error as { name?: string }).name !== 'ConditionalCheckFailedException') throw error; + // TTL removal after a successful post must not recreate the approval row. + logger.info('Approval disappeared before its notification receipt was saved', { + event: 'approval_notification_receipt_missing', task_id: notification.taskId, request_id: notification.requestId, + }); + } +} + +/** Escape preview Markdown, including backticks, so repository text cannot break out of its code fence. */ +export function approvalNotificationMarkdown(notification: ApprovalNotification): string { + return `\`\`\`text\n${notification.text.replace(/`/g, 'ˋ')}\n\`\`\``; +} diff --git a/cdk/src/handlers/shared/linear-approval-reply.ts b/cdk/src/handlers/shared/linear-approval-reply.ts new file mode 100644 index 000000000..77c5c9c2a --- /dev/null +++ b/cdk/src/handlers/shared/linear-approval-reply.ts @@ -0,0 +1,140 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { GetCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { + closeLinearApprovalThread, linearApprovalCommentId, parseLinearApprovalReply, readLinearApprovalThread, + type LinearApprovalReply, +} from './linear-approval-thread'; +import { postIdentifiedComment, readLinearApprovalComment } from './linear-feedback'; +import { logger } from './logger'; + +interface ApprovalReplyEvent { + action: string; + organizationId?: string; + actor?: { id?: string }; + data: { id: string; body?: string; parentId?: string; issueId?: string; issue?: { id?: string } }; +} + +interface ApprovalReplyDependencies { + ddb: DynamoDBDocumentClient; + approvalsTable: string; + taskTable: string; + registryTable: string; + lookupUser: (workspaceId: string, actorId: string) => Promise; +} + +function sameReply(a: LinearApprovalReply | null, b: LinearApprovalReply): boolean { + return a?.decision === b.decision && (a.reason ?? '') === (b.reason ?? ''); +} + +/** A verified webhook may decide only the exact gate bound to its thread. */ +export async function handleLinearApprovalReply( + event: ApprovalReplyEvent, deps: ApprovalReplyDependencies, +): Promise { + const reply = parseLinearApprovalReply(event.data.body); + const workspaceId = event.organizationId; + const parentId = event.data.parentId; + if (event.action !== 'create' || !reply || !workspaceId || !parentId || !event.data.id) return false; + const { decision } = reply; + const thread = await readLinearApprovalThread(deps.ddb, deps.approvalsTable, workspaceId, parentId); + if (!thread) return false; + const issueId = event.data.issueId ?? event.data.issue?.id; + if (issueId !== thread.issueId) return true; + const ctx = { linearWorkspaceId: workspaceId, registryTableName: deps.registryTable }; + const comment = await readLinearApprovalComment(ctx, event.data.id); + if (!comment || comment.id !== event.data.id || comment.botActor || !comment.user?.id + || comment.issue?.id !== issueId || comment.parent?.id !== parentId + || !sameReply(parseLinearApprovalReply(comment.body), reply)) { + logger.warn('Linear approval webhook does not match a human comment', { + task_id: thread.taskId, request_id: thread.requestId, comment_id: event.data.id, + }); + return true; + } + const respond = async (body: string): Promise => { + const posted = await postIdentifiedComment(ctx, { + id: linearApprovalCommentId({ ...thread, requestId: `${thread.requestId}#reply#${event.data.id}` }), + issueId, + parentId, + body, + }); + if (!posted.ok) { + logger.warn('Linear approval acknowledgement failed', { + task_id: thread.taskId, request_id: thread.requestId, comment_id: event.data.id, retryable: posted.retryable, + }); + if (posted.retryable) throw new Error('Retryable Linear approval acknowledgement failure'); + } + }; + const userId = await deps.lookupUser(workspaceId, comment.user.id); + if (!userId || userId !== thread.userId) { + await respond('Only the task owner can decide this request. Link your Linear account to ABCA, then reply again.'); + return true; + } + const task = (await deps.ddb.send(new GetCommand({ + TableName: deps.taskTable, Key: { task_id: thread.taskId }, ConsistentRead: true, + }))).Item; + if (!task || task.user_id !== userId || task.channel_source !== 'linear' + || task.channel_metadata?.linear_workspace_id !== workspaceId + || task.channel_metadata?.linear_issue_id !== issueId) { + await respond('This approval is no longer available for this task. No decision was recorded.'); + return true; + } + const source = JSON.stringify(['linear', workspaceId, event.data.id]); + const expectedStatus = decision === 'approve' ? 'APPROVED' : 'DENIED'; + const readApproval = async () => (await deps.ddb.send(new GetCommand({ + TableName: deps.approvalsTable, Key: { task_id: thread.taskId, request_id: thread.requestId }, ConsistentRead: true, + }))).Item; + const alreadyRecorded = (row: Awaited>) => + row?.user_id === userId && row.status === expectedStatus && row.decision_source === source; + let recorded = alreadyRecorded(await readApproval()); + if (!recorded) { + // Loaded only for configured approval integrations; ordinary comment paths + // do not require the decision handlers' environment variables. + const record = decision === 'approve' + ? (await import('../approve-task.js')).recordApprovalForUser + : (await import('../deny-task.js')).recordDenialForUser; + const result = await record({ + userId, + taskId: thread.taskId, + decisionSource: source, + // The verified comment body (read back from Linear), not the webhook copy. + body: JSON.stringify({ + request_id: thread.requestId, + decision, + ...(decision === 'deny' && reply.reason ? { reason: reply.reason } : {}), + }), + }); + recorded = result.statusCode === 202 || alreadyRecorded(await readApproval()); + if (!recorded) { + if (result.statusCode >= 500) throw new Error(`Linear approval decision failed: HTTP ${result.statusCode}`); + await respond(result.statusCode === 429 + ? 'Too many approval decisions. Wait a minute, then send a new reply.' + : 'This request is already closed, expired, or no longer waiting. No new decision was recorded.'); + return true; + } + } + await closeLinearApprovalThread(deps.ddb, deps.approvalsTable, thread); + await respond(decision === 'approve' + ? 'Approved for this action once. The decision is saved and the agent continues.' + : 'Denied. The decision is saved and the agent receives your denial.'); + logger.info('Linear approval reply recorded', { + task_id: thread.taskId, request_id: thread.requestId, comment_id: event.data.id, decision, + }); + return true; +} diff --git a/cdk/src/handlers/shared/linear-approval-thread.ts b/cdk/src/handlers/shared/linear-approval-thread.ts new file mode 100644 index 000000000..ded628758 --- /dev/null +++ b/cdk/src/handlers/shared/linear-approval-thread.ts @@ -0,0 +1,112 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { createHash } from 'node:crypto'; +import { GetCommand, UpdateCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { computeTtlEpoch } from './validation'; + +export interface LinearApprovalThread { + readonly workspaceId: string; + readonly issueId: string; + readonly taskId: string; + readonly requestId: string; + readonly userId: string; +} + +/** Linear requires UUIDv4; stable hash-derived bits make comment retries address the same ID. */ +export function linearApprovalCommentId(thread: LinearApprovalThread): string { + const hash = createHash('sha256').update(JSON.stringify([ + 'abca-linear-approval-v1', thread.workspaceId, thread.issueId, thread.taskId, thread.requestId, + ])).digest('hex'); + const groups = hash.match(/^(.{8})(.{4}).(.{3}).(.{3})(.{12})/)!; + return `${groups[1]}-${groups[2]}-4${groups[3]}-a${groups[4]}-${groups[5]}`; +} + +function threadKey(workspaceId: string, commentId: string): { task_id: string; request_id: string } { + return { task_id: `LINEAR_COMMENT#${workspaceId}#${commentId}`, request_id: 'APPROVAL' }; +} + +/** Mapping is coordinator-owned: task-scoped worker credentials cannot write this key. */ +export async function saveLinearApprovalThread( + ddb: DynamoDBDocumentClient, tableName: string, thread: LinearApprovalThread, +): Promise { + const commentId = linearApprovalCommentId(thread); + await ddb.send(new UpdateCommand({ + TableName: tableName, + Key: threadKey(thread.workspaceId, commentId), + UpdateExpression: 'SET #kind = :kind, #thread = :thread', + ConditionExpression: 'attribute_not_exists(task_id) OR (#kind = :kind AND #thread = :thread)', + ExpressionAttributeNames: { '#kind': 'kind', '#thread': 'thread' }, + ExpressionAttributeValues: { ':kind': 'linear_approval_thread', ':thread': thread }, + })); + return commentId; +} + +export async function readLinearApprovalThread( + ddb: DynamoDBDocumentClient, tableName: string, workspaceId: string, commentId: string, +): Promise { + const result = await ddb.send(new GetCommand({ + TableName: tableName, Key: threadKey(workspaceId, commentId), ConsistentRead: true, + })); + const thread = result.Item?.thread as LinearApprovalThread | undefined; + if (result.Item?.kind !== 'linear_approval_thread' || !thread + || ![thread.workspaceId, thread.issueId, thread.taskId, thread.requestId, thread.userId] + .every(value => typeof value === 'string' && value.length > 0) + || thread.workspaceId !== workspaceId || linearApprovalCommentId(thread) !== commentId) return null; + return thread; +} + +/** Pending mappings have no TTL, like pending approvals; closure starts retention. */ +export async function closeLinearApprovalThread( + ddb: DynamoDBDocumentClient, tableName: string, thread: LinearApprovalThread, +): Promise { + try { + await ddb.send(new UpdateCommand({ + TableName: tableName, + Key: threadKey(thread.workspaceId, linearApprovalCommentId(thread)), + UpdateExpression: 'SET #ttl = if_not_exists(#ttl, :ttl)', + ConditionExpression: 'attribute_exists(task_id)', + ExpressionAttributeNames: { '#ttl': 'ttl' }, + ExpressionAttributeValues: { ':ttl': computeTtlEpoch(Number(process.env.TASK_RETENTION_DAYS ?? '90')) }, + })); + } catch (error) { + if ((error as { name?: string }).name !== 'ConditionalCheckFailedException') throw error; + } +} + +export interface LinearApprovalReply { + readonly decision: 'approve' | 'deny'; + /** Optional free text after ``deny``; never accepted after ``approve``. */ + readonly reason?: string; +} + +/** + * Only an explicit answer in an approval thread is a decision, never prose or an + * edit: ``approve`` alone, or ``deny`` optionally followed by a reason + * (``deny use staging``, ``deny: use staging``). Anything else is not a decision. + */ +export function parseLinearApprovalReply(body: unknown): LinearApprovalReply | null { + if (typeof body !== 'string') return null; + const trimmed = body.trim(); + if (/^approve[.!]?$/i.test(trimmed)) return { decision: 'approve' }; + const deny = /^deny(?:[.!]?$|[\s:-]+([\s\S]+))/i.exec(trimmed); + if (!deny) return null; + const reason = deny[1]?.trim(); + return reason ? { decision: 'deny', reason } : { decision: 'deny' }; +} diff --git a/cdk/src/handlers/shared/linear-channel-metadata.ts b/cdk/src/handlers/shared/linear-channel-metadata.ts index 592ccb660..e8744a69f 100644 --- a/cdk/src/handlers/shared/linear-channel-metadata.ts +++ b/cdk/src/handlers/shared/linear-channel-metadata.ts @@ -55,6 +55,8 @@ export async function lookupLinearPlatformUser( const result = await ddb.send(new GetCommand({ TableName: userMappingTableName, Key: { linear_identity: `${workspaceId}#${userId}` }, + // Decisions (approval replies, a session stop) are authorized from this mapping. + ConsistentRead: true, })); if (!result.Item || result.Item.status === 'pending') return null; return (result.Item.platform_user_id as string) ?? null; diff --git a/cdk/src/handlers/shared/linear-feedback.ts b/cdk/src/handlers/shared/linear-feedback.ts index 91e998501..4454e1b16 100644 --- a/cdk/src/handlers/shared/linear-feedback.ts +++ b/cdk/src/handlers/shared/linear-feedback.ts @@ -389,6 +389,75 @@ export async function postIssueComment( return graphqlRequest(token, COMMENT_CREATE_MUTATION, { issueId, body }); } +/** + * Read consent from Linear itself. Webhook authentication alone is insufficient: + * legacy worker credentials can read the OAuth bundle containing the HMAC key. + * Lookup failures must retry, never become permission to use webhook fields. + */ +export async function readLinearApprovalComment( + ctx: LinearFeedbackContext, + id: string, +): Promise<{ + id: string; + body: string; + user?: { id: string } | null; + botActor?: { id: string } | null; + issue: { id: string }; + parent?: { id: string } | null; +} | null> { + const token = await resolveToken(ctx); + if (!token) throw new Error('Linear approval verification token unavailable'); + const result = await graphqlData(token, ` + query VerifyApprovalComment($id: String!) { + organization { id } + viewer { id } + comment(id: $id) { id body user { id } botActor { id } issue { id } parent { id } } + }`, { id }); + if (!result.ok) throw new Error('Linear approval comment verification unavailable'); + if ((result.value.organization as { id?: string } | undefined)?.id !== ctx.linearWorkspaceId) { + throw new Error('Linear approval verification workspace mismatch'); + } + const viewerId = (result.value.viewer as { id?: string } | undefined)?.id; + if (!viewerId) throw new Error('Linear approval verification identity unavailable'); + const comment = result.value.comment as Awaited> ?? null; + // Diagnostic user-mode OAuth tokens can post genuine human comments. Workers + // holding that token must not manufacture consent from its own identity. + // Read the identity from Linear, including for installations predating this check. + if (comment?.user?.id === viewerId) return null; + return comment; +} + +/** Retry-safe posting for approval prompts and acknowledgements. */ +export async function postIdentifiedComment( + ctx: LinearFeedbackContext, + input: { id: string; issueId: string; body: string; parentId?: string }, +): Promise { + const token = await resolveToken(ctx); + if (!token) return { ok: false, retryable: false }; + const created = await graphqlData(token, ` + mutation ApprovalComment($input: CommentCreateInput!) { + commentCreate(input: $input) { success comment { id } } + }`, { input }); + if (created.ok && (created.value.commentCreate as { success?: boolean } | undefined)?.success) { + return { ok: true }; + } + // A successful write can lose its response. A duplicate ID is acceptable only + // when destination and content match, ignoring transport line endings only. + const existing = await graphqlData(token, ` + query ApprovalComment($id: String!) { + comment(id: $id) { body issue { id } parent { id } } + }`, { id: input.id }); + if (!existing.ok) return { ok: false, retryable: true }; + const comment = existing.value.comment as { + body?: string; issue?: { id?: string }; parent?: { id?: string }; + } | undefined; + const normalizeBody = (body: string) => body.replace(/\r\n?/g, '\n').replace(/\n+$/, ''); + return typeof comment?.body === 'string' && normalizeBody(comment.body) === normalizeBody(input.body) + && comment.issue?.id === input.issueId + && comment.parent?.id === input.parentId + ? { ok: true } : { ok: false, retryable: false }; +} + /** * Upsert the orchestration's live status block — ONE comment on the parent epic * that is rewritten as the run progresses, rather than a new comment per diff --git a/cdk/src/stacks/agent.ts b/cdk/src/stacks/agent.ts index fd1815534..ec5ba1edf 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -1704,6 +1704,7 @@ export class AgentStack extends Stack { userPool: taskApi.userPool, taskTable: taskTable.table, taskEventsTable: taskEventsTable.table, + taskApprovalsTable: taskApprovalsTable.table, budgetTable: budgetTable.table, repoTable: repoTable.table, // Enables the webhook processor's orchestration path @@ -2088,6 +2089,7 @@ export class AgentStack extends Stack { const fanOutConsumer = new FanOutConsumer(this, 'FanOutConsumer', { taskEventsTable: taskEventsTable.table, taskTable: taskTable.table, + taskApprovalsTable: taskApprovalsTable.table, repoTable: repoTable.table, githubTokenSecret, // Slack bot-token grant is guarded on this prop — pass the diff --git a/cdk/test/constructs/fanout-consumer.test.ts b/cdk/test/constructs/fanout-consumer.test.ts index c4343ce03..dece9caf8 100644 --- a/cdk/test/constructs/fanout-consumer.test.ts +++ b/cdk/test/constructs/fanout-consumer.test.ts @@ -287,4 +287,46 @@ describe('FanOutConsumer', () => { expect(vars.TASK_TABLE_NAME).toBeUndefined(); } }); + + test('approval notices (#1001): wires TASK_APPROVALS_TABLE_NAME with only GetItem + UpdateItem', () => { + const app = new App(); + const stack = new Stack(app, 'TestStack'); + const approvals = new dynamodb.Table(stack, 'ApprovalsTable', { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + sortKey: { name: 'request_id', type: dynamodb.AttributeType.STRING }, + }); + new FanOutConsumer(stack, 'FanOut', { + taskEventsTable: makeTaskEventsTable(stack), + taskApprovalsTable: approvals, + }); + const template = Template.fromStack(stack); + const approvalsId = stack.getLogicalId(approvals.node.defaultChild as dynamodb.CfnTable); + + template.hasResourceProperties('AWS::Lambda::Function', { + Environment: { Variables: Match.objectLike({ TASK_APPROVALS_TABLE_NAME: { Ref: approvalsId } }) }, + }); + const approvalActions: string[] = []; + for (const policy of Object.values(template.findResources('AWS::IAM::Policy'))) { + const stmts = (policy as { Properties: { PolicyDocument: { Statement: Array<{ Action: unknown; Resource: unknown }> } } }) + .Properties.PolicyDocument.Statement; + for (const s of stmts) { + if (JSON.stringify(s.Resource).includes(approvalsId)) { + approvalActions.push(...(Array.isArray(s.Action) ? s.Action : [s.Action]) as string[]); + } + } + } + expect(approvalActions.sort()).toEqual(['dynamodb:GetItem', 'dynamodb:UpdateItem']); + }); + + test('approval notices (#1001): no approvals env or grant when the table is omitted', () => { + const app = new App(); + const stack = new Stack(app, 'TestStack'); + new FanOutConsumer(stack, 'FanOut', { taskEventsTable: makeTaskEventsTable(stack) }); + const template = Template.fromStack(stack); + for (const fn of Object.values(template.findResources('AWS::Lambda::Function'))) { + const vars = ((fn as { Properties?: { Environment?: { Variables?: Record } } }) + .Properties?.Environment?.Variables) ?? {}; + expect(vars.TASK_APPROVALS_TABLE_NAME).toBeUndefined(); + } + }); }); diff --git a/cdk/test/constructs/linear-integration.test.ts b/cdk/test/constructs/linear-integration.test.ts index 5df92ed6c..eb9ee8e14 100644 --- a/cdk/test/constructs/linear-integration.test.ts +++ b/cdk/test/constructs/linear-integration.test.ts @@ -548,3 +548,68 @@ describe('LinearIntegration construct — agent sessions (ADR-018 Phase 2)', () expect(nudgeStatements(t)).toEqual([]); }); }); + +describe('LinearIntegration construct — approval replies (#1001)', () => { + function buildWith(opts: { withApprovals: boolean }): { t: Template; approvalsId?: string } { + const app = new App(); + const stack = new Stack(app, 'TestStack'); + const api = new apigw.RestApi(stack, 'TestApi'); + const userPool = new cognito.UserPool(stack, 'TestUserPool'); + const taskTable = new dynamodb.Table(stack, 'TaskTable', { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + }); + const taskEventsTable = new dynamodb.Table(stack, 'TaskEventsTable', { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + sortKey: { name: 'event_id', type: dynamodb.AttributeType.STRING }, + }); + const taskApprovalsTable = opts.withApprovals + ? new dynamodb.Table(stack, 'ApprovalsTable', { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + sortKey: { name: 'request_id', type: dynamodb.AttributeType.STRING }, + }) + : undefined; + new LinearIntegration(stack, 'LinearIntegration', { + api, + userPool, + taskTable, + taskEventsTable, + ...(taskApprovalsTable && { taskApprovalsTable }), + }); + return { + t: Template.fromStack(stack), + approvalsId: taskApprovalsTable && stack.getLogicalId(taskApprovalsTable.node.defaultChild as dynamodb.CfnTable), + }; + } + + test('wires TASK_APPROVALS_TABLE_NAME on the processor and grants it the approvals table', () => { + const { t, approvalsId } = buildWith({ withApprovals: true }); + t.hasResourceProperties('AWS::Lambda::Function', { + Environment: { + Variables: Match.objectLike({ + TASK_APPROVALS_TABLE_NAME: { Ref: approvalsId }, + LINEAR_WORKSPACE_REGISTRY_TABLE_NAME: Match.anyValue(), + }), + }, + }); + const grants = Object.values(t.findResources('AWS::IAM::Policy')).filter((p) => { + const stmts = (p as { Properties: { PolicyDocument: { Statement: Array<{ Action: unknown; Resource: unknown }> } } }) + .Properties.PolicyDocument.Statement; + return stmts.some((s) => { + const actions = Array.isArray(s.Action) ? s.Action : [s.Action]; + return actions.includes('dynamodb:UpdateItem') && actions.includes('dynamodb:GetItem') + && JSON.stringify(s.Resource).includes(approvalsId!); + }); + }); + expect(grants).toHaveLength(1); + }); + + test('does NOT set TASK_APPROVALS_TABLE_NAME when the table is omitted (back-compat)', () => { + const { t } = buildWith({ withApprovals: false }); + const fns = t.findResources('AWS::Lambda::Function', { + Properties: { + Environment: { Variables: Match.objectLike({ TASK_APPROVALS_TABLE_NAME: Match.anyValue() }) }, + }, + }); + expect(Object.keys(fns)).toHaveLength(0); + }); +}); diff --git a/cdk/test/handlers/approve-task.test.ts b/cdk/test/handlers/approve-task.test.ts index f05148b9b..3f1f1543d 100644 --- a/cdk/test/handlers/approve-task.test.ts +++ b/cdk/test/handlers/approve-task.test.ts @@ -61,7 +61,7 @@ process.env.TASK_APPROVALS_TABLE_NAME = 'Approvals'; process.env.TASK_EVENTS_TABLE_NAME = 'Events'; process.env.APPROVE_RATE_LIMIT_PER_MINUTE = '30'; -import { handler } from '../../src/handlers/approve-task'; +import { handler, recordApprovalForUser } from '../../src/handlers/approve-task'; function makeEvent(overrides: Partial = {}): APIGatewayProxyEvent { return { @@ -302,5 +302,41 @@ describe('trusted channel decision source', () => { await handler(makeEvent({ body: JSON.stringify({ request_id: 'gate', decision: 'approve', decisionSource: 'forged' }) })); const update = mockSend.mock.calls.find(([cmd]) => cmd._type === 'TransactWrite')![0].input.TransactItems[0].Update; expect(update.UpdateExpression).not.toContain('decision_source'); + +describe('approve-task — decision source (#1001)', () => { + test('API callers record no decision_source (behaviour unchanged)', async () => { + mockSend.mockResolvedValue({}); + await handler(makeEvent({ body: JSON.stringify({ request_id: '01KREQ1', decision: 'approve' }) })); + const tx = mockSend.mock.calls.find((c) => c[0]._type === 'TransactWrite')?.[0].input; + const update = tx.TransactItems[0].Update; + expect(update.UpdateExpression).not.toContain('decision_source'); + expect(update.ExpressionAttributeValues[':source']).toBeUndefined(); + const audit = mockSend.mock.calls.find((c) => c[0]._type === 'Put')?.[0].input; + expect(audit.Item.metadata.decision_source).toBeUndefined(); + }); + + test('recordApprovalForUser records the given decision_source on the row and the audit event', async () => { + mockSend.mockResolvedValue({}); + const res = await recordApprovalForUser({ + userId: 'user-alice', + taskId: 'task-1', + body: JSON.stringify({ request_id: '01KREQ1', decision: 'approve' }), + decisionSource: 'linear', + }); + expect(res.statusCode).toBe(202); + expect(JSON.parse(res.body).data.status).toBe('APPROVED'); + const tx = mockSend.mock.calls.find((c) => c[0]._type === 'TransactWrite')?.[0].input; + const update = tx.TransactItems[0].Update; + expect(update.UpdateExpression).toContain('decision_source = :source'); + expect(update.ExpressionAttributeValues[':source']).toBe('linear'); + const audit = mockSend.mock.calls.find((c) => c[0]._type === 'Put')?.[0].input; + expect(audit.Item.metadata.decision_source).toBe('linear'); + expect(audit.Item.metadata.caller_user_id).toBe('user-alice'); + }); + + test('recordApprovalForUser rejects a missing user with 401', async () => { + const res = await recordApprovalForUser({ userId: null, taskId: 'task-1', body: '{}', decisionSource: 'linear' }); + expect(res.statusCode).toBe(401); + expect(mockSend).not.toHaveBeenCalled(); }); }); diff --git a/cdk/test/handlers/deny-task.test.ts b/cdk/test/handlers/deny-task.test.ts index dcaeaf15f..dd7678455 100644 --- a/cdk/test/handlers/deny-task.test.ts +++ b/cdk/test/handlers/deny-task.test.ts @@ -53,7 +53,7 @@ process.env.TASK_TABLE_NAME = 'Tasks'; process.env.TASK_APPROVALS_TABLE_NAME = 'Approvals'; process.env.TASK_EVENTS_TABLE_NAME = 'Events'; -import { handler } from '../../src/handlers/deny-task'; +import { handler, recordDenialForUser } from '../../src/handlers/deny-task'; // Secret fixtures assembled at runtime so the source file itself // never holds a contiguous secret literal (Code Defender pre-commit @@ -337,5 +337,41 @@ describe('trusted channel decision source', () => { await handler(makeEvent({ body: JSON.stringify({ request_id: 'gate', decision: 'deny', decisionSource: 'forged' }) })); const update = mockSend.mock.calls.find(([cmd]) => cmd._type === 'TransactWrite')![0].input.TransactItems[0].Update; expect(update.UpdateExpression).not.toContain('decision_source'); + +describe('deny-task — decision source (#1001)', () => { + test('API callers record no decision_source (behaviour unchanged)', async () => { + mockSend.mockResolvedValue({}); + await handler(makeEvent({ body: JSON.stringify({ request_id: '01KREQ1', decision: 'deny' }) })); + const tx = mockSend.mock.calls.find((c) => c[0]._type === 'TransactWrite')?.[0].input; + const update = tx.TransactItems[0].Update; + expect(update.UpdateExpression).not.toContain('decision_source'); + expect(update.ExpressionAttributeValues[':source']).toBeUndefined(); + const audit = mockSend.mock.calls.find((c) => c[0]._type === 'Put')?.[0].input; + expect(audit.Item.metadata.decision_source).toBeUndefined(); + }); + + test('recordDenialForUser records the given decision_source on the row and the audit event', async () => { + mockSend.mockResolvedValue({}); + const res = await recordDenialForUser({ + userId: 'user-alice', + taskId: 'task-1', + body: JSON.stringify({ request_id: '01KREQ1', decision: 'deny' }), + decisionSource: 'linear', + }); + expect(res.statusCode).toBe(202); + expect(JSON.parse(res.body).data.status).toBe('DENIED'); + const tx = mockSend.mock.calls.find((c) => c[0]._type === 'TransactWrite')?.[0].input; + const update = tx.TransactItems[0].Update; + expect(update.UpdateExpression).toContain('decision_source = :source'); + expect(update.ExpressionAttributeValues[':source']).toBe('linear'); + const audit = mockSend.mock.calls.find((c) => c[0]._type === 'Put')?.[0].input; + expect(audit.Item.metadata.decision_source).toBe('linear'); + expect(audit.Item.metadata.caller_user_id).toBe('user-alice'); + }); + + test('recordDenialForUser rejects a missing user with 401', async () => { + const res = await recordDenialForUser({ userId: null, taskId: 'task-1', body: '{}', decisionSource: 'linear' }); + expect(res.statusCode).toBe(401); + expect(mockSend).not.toHaveBeenCalled(); }); }); diff --git a/cdk/test/handlers/fanout-task-events.test.ts b/cdk/test/handlers/fanout-task-events.test.ts index 6c6c7033a..fe522d76b 100644 --- a/cdk/test/handlers/fanout-task-events.test.ts +++ b/cdk/test/handlers/fanout-task-events.test.ts @@ -112,7 +112,9 @@ const mockSwapCommentReaction: jest.Mock = jest.fn().mockResolvedValue(true); // place) via upsertThreadedReply(ctx, issueId, parentCommentId, body, existingId?) // rather than posting a fresh replyToComment. const mockUpsertThreadedReply: jest.Mock = jest.fn().mockResolvedValue('reply-id'); +const mockPostIdentifiedComment: jest.Mock = jest.fn().mockResolvedValue({ ok: true }); jest.mock('../../src/handlers/shared/linear-feedback', () => ({ + postIdentifiedComment: (...args: unknown[]) => mockPostIdentifiedComment(...args), postIssueComment: ( ctx: { linearWorkspaceId: string; registryTableName: string }, issueId: string, @@ -191,6 +193,7 @@ jest.mock('../../src/handlers/shared/jira-feedback', () => ({ })); process.env.TASK_TABLE_NAME = 'Tasks'; +process.env.TASK_APPROVALS_TABLE_NAME = 'Approvals'; process.env.GITHUB_TOKEN_SECRET_ARN = 'arn:aws:secretsmanager:us-east-1:0:secret:platform'; process.env.LINEAR_WORKSPACE_REGISTRY_TABLE_NAME = 'LinearWorkspaceRegistry'; process.env.JIRA_WORKSPACE_REGISTRY_TABLE_NAME = 'JiraWorkspaceRegistry'; @@ -420,6 +423,10 @@ describe('fanout-task-events: per-channel filter contract (design §6.2)', () => // that times out still settles (matches Jira/Slack, which already had it). const f = CHANNEL_DEFAULTS.linear; expect([...f].sort()).toEqual([ + 'approval_decision_recorded', + 'approval_requested', + 'approval_stranded', + 'approval_timed_out', 'pr_created', 'task_cancelled', 'task_completed', @@ -1639,6 +1646,97 @@ describe('fanout-task-events: Linear dispatcher', () => { }); }; + describe('approval notices (#1001)', () => { + const pendingRow = { + user_id: 'u-1', + status: 'PENDING', + tool_name: 'Bash', + severity: 'medium', + reason: 'Review this', + tool_input_preview: '{"command":"git push"}', + timeout_s: 1800, + created_at: '2026-09-16T12:00:00Z', + }; + const awaiting = { ...TASK_RECORD_LINEAR, status: 'AWAITING_APPROVAL', awaiting_approval_request_id: 'g1' }; + const answer = (approvalRow: unknown, task: unknown) => mockDdbSend.mockImplementation(async (command: any) => { + if (command._type !== 'Get') return {}; + return { Item: command.input.TableName === 'Approvals' ? approvalRow : task }; + }); + + test.each([false, true])('posts the request as a reply-able notice without settling the task (post failure=%s)', async fails => { + answer(pendingRow, awaiting); + if (fails) mockPostIdentifiedComment.mockResolvedValueOnce({ ok: false, retryable: true }); + const outcome = await routeEvent({ + task_id: 't-lin', + event_id: 'approval-event', + event_type: 'agent_milestone', + timestamp: '2026-09-16T12:00:00Z', + metadata: { milestone: 'approval_requested', request_id: 'g1' }, + }); + expect(mockPostIdentifiedComment).toHaveBeenCalledTimes(1); + const posted = mockPostIdentifiedComment.mock.calls[0][1]; + expect(posted.issueId).toBe('issue-uuid-42'); + expect(posted.body).toContain('Approval needed'); + expect(posted.body).toContain('Reply approve, or deny with an optional reason'); + expect(posted.body).toContain('bgagent approve t-lin g1 --scope this_call'); + expect(mockPostIssueComment).not.toHaveBeenCalled(); + expect(mockUpsertThreadedReply).not.toHaveBeenCalled(); + const updates = mockDdbSend.mock.calls.filter(([c]: any[]) => c._type === 'Update'); + // Thread mapping first (keyed on the comment id), then the delivery receipt. + expect(updates[0][0].input.Key.task_id).toMatch(/^LINEAR_COMMENT#org-uuid-acme#/); + if (fails) { + expect(outcome.infraRejections).toHaveLength(1); + expect(updates).toHaveLength(1); + } else { + expect(outcome.infraRejections).toHaveLength(0); + expect(updates).toHaveLength(2); + expect(updates[1][0].input.ExpressionAttributeNames).toEqual({ '#marker': 'notified_linear_approval_requested' }); + } + }); + + test('an outcome notice closes the reply thread even when the post fails', async () => { + answer({ ...pendingRow, status: 'TIMED_OUT' }, { ...awaiting, status: 'RUNNING' }); + mockPostIssueComment.mockResolvedValueOnce({ ok: false, retryable: false }); + await routeEvent({ + task_id: 't-lin', + event_id: 'timeout-event', + event_type: 'agent_milestone', + timestamp: '2026-09-16T12:30:00Z', + metadata: { milestone: 'approval_timed_out', request_id: 'g1' }, + }); + const updates = mockDdbSend.mock.calls.filter(([c]: any[]) => c._type === 'Update'); + expect(updates[0][0].input.UpdateExpression).toBe('SET #ttl = if_not_exists(#ttl, :ttl)'); + expect(mockPostIssueComment.mock.calls[0][2]).toContain('Approval request timed out'); + expect(updates.some(([c]: any[]) => c.input.ExpressionAttributeNames?.['#marker'])).toBe(false); + }); + + test('a task that ends while waiting closes its reply thread before the terminal comment', async () => { + answer(pendingRow, { ...awaiting, status: 'CANCELLED' }); + await routeEvent({ + task_id: 't-lin', + event_id: 'cancel-event', + event_type: 'task_cancelled', + timestamp: '2026-09-16T12:10:00Z', + metadata: {}, + }); + const updates = mockDdbSend.mock.calls.filter(([c]: any[]) => c._type === 'Update'); + expect(updates[0][0].input.Key.task_id).toMatch(/^LINEAR_COMMENT#org-uuid-acme#/); + expect(updates[0][0].input.UpdateExpression).toBe('SET #ttl = if_not_exists(#ttl, :ttl)'); + }); + + test('a non-approval milestone is not treated as an approval', async () => { + answer(pendingRow, awaiting); + await routeEvent({ + task_id: 't-lin', + event_id: 'other', + event_type: 'agent_milestone', + timestamp: '2026-09-16T12:00:00Z', + metadata: { milestone: 'approval_gate_cap_reached', request_id: 'g1' }, + }); + expect(mockPostIdentifiedComment).not.toHaveBeenCalled(); + }); + }); + test('task_completed posts ✅ comment with cost / turns / duration on linked Linear issue', async () => { mockGet(TASK_RECORD_LINEAR); diff --git a/cdk/test/handlers/linear-webhook-processor-approval-reply.test.ts b/cdk/test/handlers/linear-webhook-processor-approval-reply.test.ts new file mode 100644 index 000000000..3980153f9 --- /dev/null +++ b/cdk/test/handlers/linear-webhook-processor-approval-reply.test.ts @@ -0,0 +1,114 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Routing of Linear approval replies (#1001) in the webhook processor: a + * Comment is offered to the approval-reply handler BEFORE the `@bgagent` + * comment-trigger path, and a handled reply stops there. The reply handler's + * own consent/owner checks are covered in linear-approval-reply.test.ts. + */ + +const ddbSend = jest.fn(); +jest.mock('@aws-sdk/client-dynamodb', () => ({ DynamoDBClient: jest.fn(() => ({})) })); +jest.mock('@aws-sdk/lib-dynamodb', () => ({ + DynamoDBDocumentClient: { from: jest.fn(() => ({ send: ddbSend })) }, + GetCommand: jest.fn((input: unknown) => ({ _type: 'Get', input })), +})); + +const createTaskCoreMock = jest.fn(); +jest.mock('../../src/handlers/shared/create-task-core', () => ({ + createTaskCore: (...args: unknown[]) => createTaskCoreMock(...args), +})); + +jest.mock('../../src/handlers/shared/linear-feedback', () => ({ + reportIssueFailure: jest.fn(), + fetchRecentComments: jest.fn(), +})); + +const resolveLinearOauthTokenMock = jest.fn(); +jest.mock('../../src/handlers/shared/linear-oauth-resolver', () => ({ + resolveLinearOauthToken: (...args: unknown[]) => resolveLinearOauthTokenMock(...args), + resolveSoleActiveLinearWorkspace: jest.fn(), +})); + +const handleLinearApprovalReplyMock = jest.fn(); +jest.mock('../../src/handlers/shared/linear-approval-reply', () => ({ + handleLinearApprovalReply: (...args: unknown[]) => handleLinearApprovalReplyMock(...args), +})); + +process.env.LINEAR_PROJECT_MAPPING_TABLE_NAME = 'LinearProjects'; +process.env.LINEAR_USER_MAPPING_TABLE_NAME = 'LinearUsers'; +process.env.LINEAR_WORKSPACE_REGISTRY_TABLE_NAME = 'LinearWorkspaceRegistry'; +process.env.ORCHESTRATION_TABLE_NAME = 'Orchestrations'; +process.env.TASK_TABLE_NAME = 'Tasks'; +process.env.TASK_APPROVALS_TABLE_NAME = 'Approvals'; + +import { handler } from '../../src/handlers/linear-webhook-processor'; + +function comment(body: string): { raw_body: string } { + return { + raw_body: JSON.stringify({ + action: 'create', + type: 'Comment', + organizationId: 'org-1', + actor: { id: 'linear-user-1', type: 'user' }, + data: { id: 'c-reply', body, issueId: 'issue-1', parentId: 'c-notice', userId: 'linear-user-1' }, + }), + }; +} + +beforeEach(() => { + jest.clearAllMocks(); + resolveLinearOauthTokenMock.mockResolvedValue(null); +}); + +describe('linear-webhook-processor approval reply routing (#1001)', () => { + test('offers the comment to the approval-reply handler with the approvals, task and registry tables', async () => { + handleLinearApprovalReplyMock.mockResolvedValue(true); + await handler(comment('approve')); + expect(handleLinearApprovalReplyMock).toHaveBeenCalledTimes(1); + const [payload, deps] = handleLinearApprovalReplyMock.mock.calls[0]; + expect(payload).toMatchObject({ type: 'Comment', data: { id: 'c-reply', body: 'approve' } }); + expect(deps).toMatchObject({ + approvalsTable: 'Approvals', + taskTable: 'Tasks', + registryTable: 'LinearWorkspaceRegistry', + }); + expect(typeof deps.lookupUser).toBe('function'); + }); + + test('a handled reply stops before the @bgagent comment-trigger path', async () => { + handleLinearApprovalReplyMock.mockResolvedValue(true); + await handler(comment('@bgagent approve')); + expect(resolveLinearOauthTokenMock).not.toHaveBeenCalled(); + expect(createTaskCoreMock).not.toHaveBeenCalled(); + }); + + test('an unhandled comment falls through to the @bgagent comment-trigger path', async () => { + handleLinearApprovalReplyMock.mockResolvedValue(false); + await handler(comment('@bgagent please address the review')); + expect(handleLinearApprovalReplyMock).toHaveBeenCalledTimes(1); + expect(resolveLinearOauthTokenMock).toHaveBeenCalledWith('org-1', 'LinearWorkspaceRegistry'); + }); + + test('Issue events never reach the approval-reply handler', async () => { + await handler({ raw_body: JSON.stringify({ action: 'create', type: 'Issue', organizationId: 'org-1', data: { id: 'issue-1' } }) }); + expect(handleLinearApprovalReplyMock).not.toHaveBeenCalled(); + }); +}); diff --git a/cdk/test/handlers/shared/approval-notifications.test.ts b/cdk/test/handlers/shared/approval-notifications.test.ts new file mode 100644 index 000000000..b8a3d0d3b --- /dev/null +++ b/cdk/test/handlers/shared/approval-notifications.test.ts @@ -0,0 +1,203 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { TaskStatus } from '../../../src/constructs/task-status'; +import { approvalNotificationMarkdown, loadApprovalNotification, markApprovalNotificationDelivered } from '../../../src/handlers/shared/approval-notifications'; +import type { TaskRecord } from '../../../src/handlers/shared/types'; + +const send = jest.fn(); +const ddb = { send } as unknown as DynamoDBDocumentClient; +const task = { + task_id: 'task', + user_id: 'owner', + status: TaskStatus.AWAITING_APPROVAL, + awaiting_approval_request_id: 'gate', +} as TaskRecord; +const row = { + status: 'PENDING', + user_id: 'owner', + tool_name: 'Bash', + severity: 'high', + reason: 'Destructive command', + tool_input_preview: 'git push --force', + created_at: '2026-09-16T12:00:00Z', + timeout_s: 1800, +}; +beforeEach(() => { + process.env.TASK_APPROVALS_TABLE_NAME = 'Approvals'; + send.mockReset().mockResolvedValue({ Item: row }); +}); + +test('shows the saved action and exact deadline, with one-call CLI approval', async () => { + const message = await loadApprovalNotification(ddb, task, 'approval_requested', { request_id: 'gate', reason: 'wrong' }, 'slack'); + expect(message?.text).toContain('Destructive command'); + expect(message?.text).toContain('git push --force'); + expect(message?.text).toContain('2026-09-16T12:30:00.000Z'); + expect(message?.text).toContain('bgagent approve task gate --scope this_call'); + expect(message?.text).toContain('bgagent deny task gate'); + expect(send.mock.calls[0][0].input.ConsistentRead).toBe(true); +}); + +test('explains the README decision before exposing internal policy and request IDs', async () => { + send.mockResolvedValue({ + Item: { + ...row, + tool_name: 'Read', + reason: 'Soft-deny: legacy_extra_0', + tool_input_preview: JSON.stringify({ file_path: '/workspace/task/README.md' }), + }, + }); + const message = (await loadApprovalNotification(ddb, { ...task, repo: 'owner/repo' }, 'approval_requested', { request_id: 'gate' }, 'linear'))!; + expect(message.text).toContain('The agent wants to read the file "README.md".'); + expect(message.text).toContain('Repository: owner/repo'); + expect(message.text).toContain('your configured policy requires a human decision'); + expect(message.text).toContain('Approve: allow this action once.'); + expect(message.text).toContain('Deny: block this action and return the decision to the agent.'); + const primary = message.text.split('Technical details / CLI alternative')[0]; + expect(primary).toContain('Reply approve, or deny with an optional reason'); + expect(primary).not.toMatch(/legacy_extra|Task:|Request:|severity:/); + expect(message.text).toContain('Policy detail: Soft-deny: legacy_extra_0'); +}); + +test.each([ + ['Write', { file_path: '/etc/config', content: 'replacement' }, 'creating the file or replacing its contents.'], + ['Edit', { file_path: '/workspace/task/app.py', old_string: 'before', new_string: 'after' }, 'change text in "app.py".'], + ['Bash', { command: 'git push --force', description: 'Publish the branch' }, 'Command: "git push --force"'], + ['WebFetch', { url: 'https://example.com' }, 'fetch content from "https://example.com".'], + ['Grep', { pattern: 'password', path: '/etc' }, 'search file contents.'], + ['mcp__custom__publish', { target: 'production' }, 'call the tool "mcp__custom__publish".'], +])('describes %s without hiding its saved arguments', async (tool, input, expected) => { + const preview = JSON.stringify(input); + send.mockResolvedValue({ Item: { ...row, tool_name: tool, tool_input_preview: preview } }); + const message = (await loadApprovalNotification(ddb, task, 'approval_requested', { request_id: 'gate' }, 'linear'))!; + expect(message.text).toContain(expected); + expect(message.text).toContain(`Saved arguments: ${preview}`); + if (tool === 'Bash') expect(message.text).toContain("Agent's explanation: Publish the branch"); + expect(message.text).not.toContain('incomplete'); +}); + +test('does not invent a read target from truncated arguments', async () => { + send.mockResolvedValue({ Item: { ...row, tool_name: 'Read', tool_input_preview: '{"file_path": "/workspace/task/secret...' } }); + const message = (await loadApprovalNotification(ddb, task, 'approval_requested', { request_id: 'gate' }, 'linear'))!; + expect(message.text).toContain('saved arguments are incomplete'); + expect(message.text).not.toContain('wants to read the file'); +}); + +test('redacts extracted command descriptions and makes display truncation explicit', async () => { + const token = `ghp_${'a'.repeat(36)}`; + send.mockResolvedValue({ + Item: { + ...row, + tool_input_preview: JSON.stringify({ + command: `echo ${token} ${'x'.repeat(600)}`, description: `Use ${token}`, + }), + }, + }); + const message = (await loadApprovalNotification(ddb, task, 'approval_requested', { request_id: 'gate' }, 'linear'))!; + expect(message.text).not.toContain(token); + expect(message.text).toContain('[REDACTED-GITHUB_TOKEN]'); + expect(message.text).toContain('[shortened]'); + expect(message.text).toContain('may not show the full action'); +}); + +test.each([ + ['cancelled task', { ...task, status: TaskStatus.CANCELLED }, row], + ['new gate', { ...task, awaiting_approval_request_id: 'new' }, row], + ['already decided', task, { ...row, status: 'APPROVED' }], + ['foreign owner', task, { ...row, user_id: 'other' }], + ['already delivered', task, { ...row, notified_slack_approval_requested: '2026-09-16' }], + ['missing approval', task, undefined], +])('suppresses a delayed request: %s', async (_label, owningTask, approval) => { + send.mockResolvedValue({ Item: approval }); + expect(await loadApprovalNotification(ddb, owningTask, 'approval_requested', { request_id: 'gate' }, 'slack')).toBeNull(); +}); + +test.each([ + ['APPROVED', 'approval_decision_recorded', 'Approval recorded'], + ['DENIED', 'approval_decision_recorded', 'Denial recorded'], + ['TIMED_OUT', 'approval_timed_out', 'Approval request timed out'], + ['STRANDED', 'approval_stranded', 'Approval wait could not continue'], +])('reports saved %s even when the task is now terminal', async (status, event, title) => { + send.mockResolvedValue({ Item: { ...row, status, cancellation_reason: 'Task cancelled by its owner' } }); + const message = await loadApprovalNotification(ddb, { ...task, status: TaskStatus.CANCELLED }, event, { request_id: 'gate' }, 'linear'); + expect(message?.title).toBe(title); + expect(message?.text).not.toContain('bgagent approve'); + if (status === 'APPROVED' || status === 'DENIED') { + expect(message?.text).toContain('Task status: CANCELLED. The task has already ended.'); + expect(message?.text).not.toContain('when its worker is ready'); + } +}); + +test.each([ + [undefined, 'The configured decision deadline was reached.'], + ['poll failed 3 consecutive times', 'poll failed 3 consecutive times'], +])('reports timeout closure instead of the original policy reason (%s)', async (denyReason, expected) => { + send.mockResolvedValue({ Item: { ...row, status: 'TIMED_OUT', deny_reason: denyReason } }); + const message = await loadApprovalNotification(ddb, task, 'approval_timed_out', { request_id: 'gate' }, 'slack'); + expect(message?.text).toContain(expected); + expect(message?.text).not.toContain(row.reason); +}); + +test('handles the actual stranded-reconciler event without changing the pending approval', async () => { + const failed = { ...task, status: TaskStatus.FAILED, error_message: 'Approval stranded: task paused for approval for 7200s with no resume transition.' }; + const message = await loadApprovalNotification(ddb, failed, 'approval_stranded', { reason: 'STRANDED_NO_HEARTBEAT' }, 'linear'); + expect(message).toMatchObject({ title: 'Approval wait could not continue', requestId: 'gate' }); + expect(message?.text).toContain(failed.error_message); + expect(message?.text).not.toContain('bgagent approve'); + expect(send).toHaveBeenCalledTimes(1); + expect(send.mock.calls[0][0].input.Key).toEqual({ task_id: 'task', request_id: 'gate' }); +}); + +test.each([ + [task, row], + [{ ...task, status: TaskStatus.FAILED, error_message: 'Unrelated failure' }, row], + [{ ...task, status: TaskStatus.FAILED, error_message: 'Approval stranded: old wait', awaiting_approval_request_id: undefined }, row], + [{ ...task, status: TaskStatus.FAILED, error_message: 'Approval stranded: old wait' }, { ...row, user_id: 'foreign' }], + [{ ...task, status: TaskStatus.FAILED, error_message: 'Approval stranded: old wait' }, { ...row, status: 'APPROVED' }], +])('does not infer a stranded request from an unrelated or decided task', async (owningTask, approval) => { + send.mockResolvedValue({ Item: approval }); + expect(await loadApprovalNotification(ddb, owningTask, 'approval_stranded', { reason: 'STRANDED_NO_HEARTBEAT' }, 'linear')).toBeNull(); +}); + +test('delivery receipts are separate for each request and channel and cannot recreate a deleted row', async () => { + const message = (await loadApprovalNotification(ddb, task, 'approval_requested', { request_id: 'gate' }, 'linear'))!; + await markApprovalNotificationDelivered(ddb, message); + expect(send.mock.calls[1][0].input).toMatchObject({ + Key: { task_id: 'task', request_id: 'gate' }, + ConditionExpression: 'attribute_exists(task_id) AND user_id = :user', + ExpressionAttributeNames: { '#marker': 'notified_linear_approval_requested' }, + }); +}); + +test('does not turn repository content into markdown or shell command substitutions', async () => { + send.mockResolvedValue({ Item: { ...row, tool_input_preview: '``` @everyone $(touch file)' } }); + const message = (await loadApprovalNotification(ddb, { ...task, awaiting_approval_request_id: '$(evil)' }, 'approval_requested', { request_id: '$(evil)' }, 'linear'))!; + expect(message.text).not.toContain('bgagent approve'); + expect(approvalNotificationMarkdown(message).match(/```/g)).toHaveLength(2); +}); + +test('redacts known credential shapes before posting a preview to a shared channel', async () => { + const token = `ghp_${'a'.repeat(36)}`; + send.mockResolvedValue({ Item: { ...row, tool_input_preview: `\u001b[31mTOKEN=${token}\u202eecho` } }); + const message = (await loadApprovalNotification(ddb, task, 'approval_requested', { request_id: 'gate' }, 'slack'))!; + expect(message.text).toContain('[REDACTED-GITHUB_TOKEN]'); + expect(message.text).not.toContain(token); + expect(message.text).not.toMatch(/[\u001b\u202e]/); +}); diff --git a/cdk/test/handlers/shared/linear-approval-reply.test.ts b/cdk/test/handlers/shared/linear-approval-reply.test.ts new file mode 100644 index 000000000..463e54dcb --- /dev/null +++ b/cdk/test/handlers/shared/linear-approval-reply.test.ts @@ -0,0 +1,226 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { handleLinearApprovalReply } from '../../../src/handlers/shared/linear-approval-reply'; +import { linearApprovalCommentId } from '../../../src/handlers/shared/linear-approval-thread'; + +const mockApprove = jest.fn(); +const mockDeny = jest.fn(); +const mockPost = jest.fn(); +const mockReadComment = jest.fn(); +jest.mock('../../../src/handlers/approve-task', () => ({ recordApprovalForUser: mockApprove })); +jest.mock('../../../src/handlers/deny-task', () => ({ recordDenialForUser: mockDeny })); +jest.mock('../../../src/handlers/shared/linear-feedback', () => ({ + postIdentifiedComment: (...args: unknown[]) => mockPost(...args), + readLinearApprovalComment: (...args: unknown[]) => mockReadComment(...args), +})); +const thread = { workspaceId: 'ws', issueId: 'issue', taskId: 'task', requestId: 'gate', userId: 'owner' }; +const root = linearApprovalCommentId(thread); +const event = { + action: 'create', + organizationId: 'ws', + actor: { id: 'actor' }, + data: { id: 'reply', body: 'approve', parentId: root, issueId: 'issue' }, +}; +const source = JSON.stringify(['linear', 'ws', 'reply']); +let approval: Record; +let task: Record; +const send = jest.fn(); +const lookupUser = jest.fn(); +const deps = { + ddb: { send } as unknown as DynamoDBDocumentClient, + approvalsTable: 'Approvals', + taskTable: 'Tasks', + registryTable: 'Registry', + lookupUser, +}; + +beforeEach(() => { + jest.clearAllMocks(); + approval = { user_id: 'owner', status: 'PENDING' }; + task = { + user_id: 'owner', + channel_source: 'linear', + status: 'AWAITING_APPROVAL', + channel_metadata: { linear_workspace_id: 'ws', linear_issue_id: 'issue' }, + }; + lookupUser.mockResolvedValue('owner'); + mockPost.mockResolvedValue({ ok: true }); + mockReadComment.mockResolvedValue({ + id: 'reply', + body: 'approve', + user: { id: 'real-author' }, + issue: { id: 'issue' }, + parent: { id: root }, + }); + mockApprove.mockResolvedValue({ statusCode: 202 }); + mockDeny.mockResolvedValue({ statusCode: 202 }); + send.mockImplementation(async command => { + if (command.input.UpdateExpression) return {}; + if (command.input.Key.task_id.startsWith('LINEAR_COMMENT#')) { + return { Item: { kind: 'linear_approval_thread', thread } }; + } + return { Item: command.input.TableName === 'Tasks' ? task : approval }; + }); +}); + +test.each(['approve', 'deny'])('records %s for the bound request and mapped owner', async body => { + mockReadComment.mockResolvedValue({ + id: 'reply', body, user: { id: 'real-author' }, issue: { id: 'issue' }, parent: { id: root }, + }); + expect(await handleLinearApprovalReply({ ...event, data: { ...event.data, body } }, deps)).toBe(true); + const record = body === 'approve' ? mockApprove : mockDeny; + expect(record).toHaveBeenCalledWith({ + userId: 'owner', + taskId: 'task', + decisionSource: source, + body: JSON.stringify({ request_id: 'gate', decision: body }), + }); + expect(mockPost).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ issueId: 'issue', parentId: root })); + expect(lookupUser).toHaveBeenCalledWith('ws', 'real-author'); +}); + +test('passes a denial reason from the verified comment to the deny path', async () => { + const body = 'deny use the staging config'; + mockReadComment.mockResolvedValue({ + id: 'reply', body, user: { id: 'real-author' }, issue: { id: 'issue' }, parent: { id: root }, + }); + expect(await handleLinearApprovalReply({ ...event, data: { ...event.data, body } }, deps)).toBe(true); + expect(mockDeny).toHaveBeenCalledWith({ + userId: 'owner', + taskId: 'task', + decisionSource: source, + body: JSON.stringify({ request_id: 'gate', decision: 'deny', reason: 'use the staging config' }), + }); + expect(mockApprove).not.toHaveBeenCalled(); +}); + +test('refuses a reply whose reason differs from what Linear holds (edited or forged)', async () => { + mockReadComment.mockResolvedValue({ + id: 'reply', body: 'deny something else', user: { id: 'real-author' }, issue: { id: 'issue' }, parent: { id: root }, + }); + const forged = { ...event, data: { ...event.data, body: 'deny use the staging config' } }; + expect(await handleLinearApprovalReply(forged, deps)).toBe(true); + expect(mockDeny).not.toHaveBeenCalled(); +}); + +test('refuses non-owners with a same-thread reply and records nothing', async () => { + lookupUser.mockResolvedValue('someone-else'); + expect(await handleLinearApprovalReply(event, deps)).toBe(true); + expect(mockApprove).not.toHaveBeenCalled(); + expect(mockPost).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + parentId: root, body: expect.stringContaining('Only the task owner'), + })); +}); + +test.each([ + null, + { body: 'deny' }, + { user: null }, + { botActor: { id: 'app' } }, + { issue: { id: 'elsewhere' } }, + { parent: { id: 'other-gate' } }, + { id: 'other-reply' }, +])('rejects forged, edited, deleted or bot consent: %j', async change => { + const original = await mockReadComment(); + mockReadComment.mockResolvedValue(change === null ? null : { ...original, ...change }); + expect(await handleLinearApprovalReply(event, deps)).toBe(true); + expect(mockApprove).not.toHaveBeenCalled(); + expect(mockDeny).not.toHaveBeenCalled(); + expect(mockPost).not.toHaveBeenCalled(); +}); + +test('retries unavailable verification without trusting the webhook actor', async () => { + mockReadComment.mockRejectedValue(new Error('Linear unavailable')); + await expect(handleLinearApprovalReply(event, deps)).rejects.toThrow('Linear unavailable'); + expect(lookupUser).not.toHaveBeenCalled(); + expect(mockApprove).not.toHaveBeenCalled(); +}); + +test.each(['update', 'remove'])('ignores %s events', async action => { + expect(await handleLinearApprovalReply({ ...event, action }, deps)).toBe(false); + expect(send).not.toHaveBeenCalled(); +}); + +test.each(['I approve', '> approve', 'approve and delete it', '@bgagent approve'])('ignores prose: %s', async body => { + expect(await handleLinearApprovalReply({ ...event, data: { ...event.data, body } }, deps)).toBe(false); + expect(send).not.toHaveBeenCalled(); +}); + +test('ignores top-level replies and unknown threads', async () => { + expect(await handleLinearApprovalReply({ ...event, data: { ...event.data, parentId: undefined } }, deps)).toBe(false); + send.mockResolvedValue({}); + expect(await handleLinearApprovalReply(event, deps)).toBe(false); + expect(mockApprove).not.toHaveBeenCalled(); +}); + +test.each([null, 'different-owner'])('rejects unmapped or different owner %s', async user => { + lookupUser.mockResolvedValue(user); + expect(await handleLinearApprovalReply(event, deps)).toBe(true); + expect(mockApprove).not.toHaveBeenCalled(); + expect(mockPost.mock.calls[0][1].body).toContain('Only the task owner'); +}); + +test('does not act across workspaces or issues', async () => { + expect(await handleLinearApprovalReply({ ...event, organizationId: 'other' }, deps)).toBe(false); + expect(await handleLinearApprovalReply({ ...event, data: { ...event.data, issueId: 'other' } }, deps)).toBe(true); + expect(mockApprove).not.toHaveBeenCalled(); + expect(mockPost).not.toHaveBeenCalled(); +}); + +test.each(['user_id', 'channel_source', 'channel_metadata'])('rejects changed task binding: %s', async field => { + task[field] = 'changed'; + await handleLinearApprovalReply(event, deps); + expect(mockApprove).not.toHaveBeenCalled(); + expect(mockPost.mock.calls[0][1].body).toContain('no longer available'); +}); + +test('acknowledges duplicate deliveries without recording again even after the task advances', async () => { + approval = { user_id: 'owner', status: 'APPROVED', decision_source: source }; + task.status = 'SUCCEEDED'; + await handleLinearApprovalReply(event, deps); + await handleLinearApprovalReply(event, deps); + expect(mockApprove).not.toHaveBeenCalled(); + expect(mockPost.mock.calls[0]).toEqual(mockPost.mock.calls[1]); +}); + +test.each([404, 409])('reports a closed or superseded gate (HTTP %s)', async statusCode => { + mockApprove.mockResolvedValue({ statusCode }); + await handleLinearApprovalReply(event, deps); + expect(mockPost.mock.calls[0][1].body).toContain('No new decision'); + expect(JSON.parse(mockApprove.mock.calls[0][0].body).request_id).toBe('gate'); +}); + +test('recognizes a duplicate that committed concurrently', async () => { + mockApprove.mockImplementation(async () => { + approval = { user_id: 'owner', status: 'APPROVED', decision_source: source }; + return { statusCode: 404 }; + }); + await handleLinearApprovalReply(event, deps); + expect(mockPost.mock.calls[0][1].body).toContain('Approved for this action once'); +}); + +test('retries transient decision and acknowledgement failures', async () => { + mockApprove.mockResolvedValue({ statusCode: 503 }); + await expect(handleLinearApprovalReply(event, deps)).rejects.toThrow('HTTP 503'); + mockApprove.mockResolvedValue({ statusCode: 202 }); + mockPost.mockResolvedValue({ ok: false, retryable: true }); + await expect(handleLinearApprovalReply(event, deps)).rejects.toThrow('acknowledgement failure'); +}); diff --git a/cdk/test/handlers/shared/linear-approval-thread.test.ts b/cdk/test/handlers/shared/linear-approval-thread.test.ts new file mode 100644 index 000000000..2138bdf64 --- /dev/null +++ b/cdk/test/handlers/shared/linear-approval-thread.test.ts @@ -0,0 +1,86 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { + closeLinearApprovalThread, linearApprovalCommentId, parseLinearApprovalReply, + readLinearApprovalThread, saveLinearApprovalThread, +} from '../../../src/handlers/shared/linear-approval-thread'; +const thread = { workspaceId: 'ws', issueId: 'issue', taskId: 'task', requestId: 'gate', userId: 'owner' }; +const send = jest.fn(); +const ddb = { send } as unknown as DynamoDBDocumentClient; +beforeEach(() => send.mockReset().mockResolvedValue({})); + +test('Linear-compatible UUIDv4 binds distinct workspace, issue, task and request identities', () => { + const id = linearApprovalCommentId(thread); + expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-a[0-9a-f]{3}-[0-9a-f]{12}$/); + expect(linearApprovalCommentId({ ...thread })).toBe(id); + for (const field of ['workspaceId', 'issueId', 'taskId', 'requestId']) { + expect(linearApprovalCommentId({ ...thread, [field]: 'other' })).not.toBe(id); + } +}); + +test('mapping writes preserve existing TTL and reject changed bindings', async () => { + await saveLinearApprovalThread(ddb, 'Approvals', thread); + const input = send.mock.calls[0][0].input; + expect(input.Key.task_id).toContain('LINEAR_COMMENT#ws#'); + expect(input.UpdateExpression).not.toContain('ttl'); + expect(input.ConditionExpression).toContain('#thread = :thread'); + expect(input.ExpressionAttributeNames).not.toHaveProperty('user_id'); +}); + +test('reads strongly and validates stored scope and shape', async () => { + const id = linearApprovalCommentId(thread); + send.mockResolvedValue({ Item: { kind: 'linear_approval_thread', thread } }); + expect(await readLinearApprovalThread(ddb, 'Approvals', 'ws', id)).toEqual(thread); + expect(send.mock.calls[0][0].input.ConsistentRead).toBe(true); + expect(await readLinearApprovalThread(ddb, 'Approvals', 'other', id)).toBeNull(); + send.mockResolvedValue({ Item: { kind: 'linear_approval_thread', thread: { ...thread, userId: undefined } } }); + expect(await readLinearApprovalThread(ddb, 'Approvals', 'ws', id)).toBeNull(); +}); + +test('closure starts retention once and never recreates a missing mapping', async () => { + await closeLinearApprovalThread(ddb, 'Approvals', thread); + const input = send.mock.calls[0][0].input; + expect(input.UpdateExpression).toContain('if_not_exists'); + expect(input.ConditionExpression).toBe('attribute_exists(task_id)'); + send.mockRejectedValue({ name: 'ConditionalCheckFailedException' }); + await expect(closeLinearApprovalThread(ddb, 'Approvals', thread)).resolves.toBeUndefined(); + send.mockRejectedValue(new Error('throttle')); + await expect(closeLinearApprovalThread(ddb, 'Approvals', thread)).rejects.toThrow('throttle'); +}); + +test.each(['approve', 'APPROVE!', ' approve. '])('accepts explicit answer %s', text => { + expect(parseLinearApprovalReply(text)).toEqual({ decision: 'approve' }); +}); +test.each(['deny', ' Deny! '])('accepts denial %s', text => { + expect(parseLinearApprovalReply(text)).toEqual({ decision: 'deny' }); +}); +test.each([ + ['deny use the staging config', 'use the staging config'], + ['Deny: not on main', 'not on main'], + ['deny - try the .example file', 'try the .example file'], + ['deny\nmulti-line\nreason', 'multi-line\nreason'], +])('accepts denial with a reason %j', (text, reason) => { + expect(parseLinearApprovalReply(text)).toEqual({ decision: 'deny', reason }); +}); +test.each([undefined, 'I approve', '`approve`', 'approve\ndeny', 'approved', 'approve because', 'denied', 'denyall'])( + 'rejects ambiguous input %j', text => { + expect(parseLinearApprovalReply(text)).toBeNull(); + }); diff --git a/docs/guides/LINEAR_SETUP_GUIDE.md b/docs/guides/LINEAR_SETUP_GUIDE.md index 4d8b84478..ed1d35243 100644 --- a/docs/guides/LINEAR_SETUP_GUIDE.md +++ b/docs/guides/LINEAR_SETUP_GUIDE.md @@ -159,6 +159,17 @@ Apply the trigger label to an issue in that project. Within ~30 seconds the agen - **Check status** — the issue's progress comments, or `bgagent list` / `bgagent status `. - **Cancel** — `bgagent cancel `. Removing the label does *not* cancel a running task. +### Approval gates + +When a task on a Linear issue hits a [Cedar approval gate](../design/CEDAR_HITL_GATES.md), ABCA posts an **approval notice** on the issue: what the agent wants to run, why it is gated, and its decision deadline. When the gate resolves (approved, denied, timed out, or stranded), it posts one **outcome** comment. Each request gets exactly one notice and one outcome, even if events are redelivered. + +To decide from Linear, **reply to the notice comment** while signed in as the task owner: + +- `approve` — approves this one action (the same as `bgagent approve ` with the default `this_call` scope). +- `deny` or `deny ` — denies it, and passes the reason to the agent. `deny: ` and `deny - ` also work. + +ABCA acknowledges the decision in the same thread. Only the Linear user linked to the task's owner (through [inviting teammates](#inviting-teammates)) can decide. A reply from anyone else, or to a request that has already been decided or has expired, gets a short explanation in the thread and changes nothing. Replies from bots and apps, replies whose text no longer matches what Linear holds (for example, edited before ABCA read them), and any other comments in the thread are ignored. Broader scopes (`--scope`) are available only through the CLI and API. + ### Trigger labels | Label | What it does | Use it when | diff --git a/docs/src/content/docs/using/Linear-setup-guide.md b/docs/src/content/docs/using/Linear-setup-guide.md index e83f0b304..4eaa2b7bb 100644 --- a/docs/src/content/docs/using/Linear-setup-guide.md +++ b/docs/src/content/docs/using/Linear-setup-guide.md @@ -161,6 +161,17 @@ Apply the trigger label to an issue in that project. Within ~30 seconds the agen - **Check status** — the issue's progress comments, or `bgagent list` / `bgagent status `. - **Cancel** — `bgagent cancel `. Removing the label does *not* cancel a running task. +### Approval gates + +When a task on a Linear issue hits a [Cedar approval gate](/sample-autonomous-cloud-coding-agents/architecture/cedar-hitl-gates), ABCA posts an **approval notice** on the issue: what the agent wants to run, why it is gated, and its decision deadline. When the gate resolves (approved, denied, timed out, or stranded), it posts one **outcome** comment. Each request gets exactly one notice and one outcome, even if events are redelivered. + +To decide from Linear, **reply to the notice comment** while signed in as the task owner: + +- `approve` — approves this one action (the same as `bgagent approve ` with the default `this_call` scope). +- `deny` or `deny ` — denies it, and passes the reason to the agent. `deny: ` and `deny - ` also work. + +ABCA acknowledges the decision in the same thread. Only the Linear user linked to the task's owner (through [inviting teammates](#inviting-teammates)) can decide. A reply from anyone else, or to a request that has already been decided or has expired, gets a short explanation in the thread and changes nothing. Replies from bots and apps, replies whose text no longer matches what Linear holds (for example, edited before ABCA read them), and any other comments in the thread are ignored. Broader scopes (`--scope`) are available only through the CLI and API. + ### Trigger labels | Label | What it does | Use it when | From 589fcce7fb95d3b01a5335dcda5eb09545846f9b Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Mon, 16 Nov 2026 01:55:02 +0000 Subject: [PATCH 11/27] fix(linear): pass the new complexity ceiling and coverage contract - approval-notifications: render the notice text in two helpers, so loadApprovalNotification is under the complexity ceiling of 40 (was 46) - fanout: move the Linear approval notice and the ended-task thread close out of dispatchToLinear (was 42) - pin cdk's jest moduleNameMapper in contracts/coverage-thresholds.json. The decision handlers are imported lazily with a .js extension (they validate their environment at load, and nodenext needs the extension on a dynamic import), so jest maps "./x.js" to "./x". The mapper resolves file names only: it changes no floor, no measured file and no test command. It needs a maintainer's agreement. The moved code is unchanged. (cherry picked from commit 5c2a97e2be2aa40941250d77c3e317af0c625e9f) --- cdk/src/handlers/fanout-task-events.ts | 124 ++++++++++------- .../handlers/shared/approval-notifications.ts | 130 +++++++++++------- contracts/coverage-thresholds.json | 3 + 3 files changed, 154 insertions(+), 103 deletions(-) diff --git a/cdk/src/handlers/fanout-task-events.ts b/cdk/src/handlers/fanout-task-events.ts index 7fe993fc1..dd557ff51 100644 --- a/cdk/src/handlers/fanout-task-events.ts +++ b/cdk/src/handlers/fanout-task-events.ts @@ -1210,6 +1210,78 @@ function formatDuration(seconds: number): string { return s === 0 ? `${m}m` : `${m}m ${s}s`; } +/** The Linear issue comment for an approval event: a request waiting for a decision, the decision, a timeout or a stranded wait. */ +async function dispatchLinearApprovalNotice( + event: FanOutEvent, + task: TaskRecord, + effectiveType: string, + approvalsTable: string | undefined, + workspaceId: string, + issueId: string, + registryTableName: string, +): Promise { + if (!approvalsTable) { + logger.warn('[fanout/linear] approval notice skipped: TASK_APPROVALS_TABLE_NAME unset', { + event: 'fanout.linear.approval_unconfigured', task_id: event.task_id, + }); + return; + } + // The notice compares the task's live gate with the saved row, so read the + // task consistently: a stale read would silently drop a real request. + const liveTask = (await ddb.send(new GetCommand({ + TableName: process.env.TASK_TABLE_NAME, Key: { task_id: task.task_id }, ConsistentRead: true, + }))).Item as TaskRecord | undefined; + if (!liveTask) return; + const notification = await loadApprovalNotification(ddb, liveTask, effectiveType, event.metadata ?? {}, 'linear'); + if (!notification) return; + const thread: LinearApprovalThread = { + workspaceId, issueId, taskId: task.task_id, requestId: notification.requestId, userId: notification.userId, + }; + const ctx = { linearWorkspaceId: workspaceId, registryTableName }; + const body = approvalNotificationMarkdown(notification); + // Retention follows the saved closure even if Linear cannot take the notice. + if (effectiveType !== 'approval_requested') await closeLinearApprovalThread(ddb, approvalsTable, thread); + const result = effectiveType === 'approval_requested' + ? await postIdentifiedComment(ctx, { id: await saveLinearApprovalThread(ddb, approvalsTable, thread), issueId, body }) + : await postIssueComment(ctx, issueId, body); + if (!result.ok) { + logger.warn('Linear approval notification failed', { + event: 'fanout.linear.approval_post_failed', + task_id: task.task_id, + request_id: notification.requestId, + retryable: result.retryable, + }); + if (result.retryable) throw new Error('Retryable Linear approval notification failure'); + return; + } + await markApprovalNotificationDelivered(ddb, notification); + logger.info('Linear approval notification delivered', { + event: 'fanout.linear.approval_dispatched', task_id: task.task_id, request_id: notification.requestId, + }); +} + +/** A task that ends while waiting for approval: start the retention of its Linear reply thread. */ +async function closeEndedApprovalThread( + event: FanOutEvent, + task: TaskRecord, + approvalsTable: string | undefined, + workspaceId: string, + issueId: string, +): Promise { + // A task that ends while waiting (e.g. cancelled) leaves its reply thread + // open; start its retention so late replies find nothing to decide. + if (approvalsTable && task.awaiting_approval_request_id + && (TERMINAL_EVENT_TYPES as readonly string[]).includes(event.event_type)) { + await closeLinearApprovalThread(ddb, approvalsTable, { + workspaceId, + issueId, + taskId: task.task_id, + requestId: task.awaiting_approval_request_id, + userId: task.user_id, + }); + } +} + /** * Linear dispatcher — posts a deterministic final-status comment when a * Linear-origin task reaches a terminal event. Mirrors Slack's structural @@ -1311,58 +1383,10 @@ async function dispatchToLinear(event: FanOutEvent): Promise { const approvalsTable = process.env.TASK_APPROVALS_TABLE_NAME; const effectiveType = effectiveEventType(event); if (isApprovalNotification(effectiveType)) { - if (!approvalsTable) { - logger.warn('[fanout/linear] approval notice skipped: TASK_APPROVALS_TABLE_NAME unset', { - event: 'fanout.linear.approval_unconfigured', task_id: event.task_id, - }); - return; - } - // The notice compares the task's live gate with the saved row, so read the - // task consistently: a stale read would silently drop a real request. - const liveTask = (await ddb.send(new GetCommand({ - TableName: process.env.TASK_TABLE_NAME, Key: { task_id: task.task_id }, ConsistentRead: true, - }))).Item as TaskRecord | undefined; - if (!liveTask) return; - const notification = await loadApprovalNotification(ddb, liveTask, effectiveType, event.metadata ?? {}, 'linear'); - if (!notification) return; - const thread: LinearApprovalThread = { - workspaceId, issueId, taskId: task.task_id, requestId: notification.requestId, userId: notification.userId, - }; - const ctx = { linearWorkspaceId: workspaceId, registryTableName }; - const body = approvalNotificationMarkdown(notification); - // Retention follows the saved closure even if Linear cannot take the notice. - if (effectiveType !== 'approval_requested') await closeLinearApprovalThread(ddb, approvalsTable, thread); - const result = effectiveType === 'approval_requested' - ? await postIdentifiedComment(ctx, { id: await saveLinearApprovalThread(ddb, approvalsTable, thread), issueId, body }) - : await postIssueComment(ctx, issueId, body); - if (!result.ok) { - logger.warn('Linear approval notification failed', { - event: 'fanout.linear.approval_post_failed', - task_id: task.task_id, - request_id: notification.requestId, - retryable: result.retryable, - }); - if (result.retryable) throw new Error('Retryable Linear approval notification failure'); - return; - } - await markApprovalNotificationDelivered(ddb, notification); - logger.info('Linear approval notification delivered', { - event: 'fanout.linear.approval_dispatched', task_id: task.task_id, request_id: notification.requestId, - }); + await dispatchLinearApprovalNotice(event, task, effectiveType, approvalsTable, workspaceId, issueId, registryTableName); return; // An approval notice never settles the task's final status. } - // A task that ends while waiting (e.g. cancelled) leaves its reply thread - // open; start its retention so late replies find nothing to decide. - if (approvalsTable && task.awaiting_approval_request_id - && (TERMINAL_EVENT_TYPES as readonly string[]).includes(event.event_type)) { - await closeLinearApprovalThread(ddb, approvalsTable, { - workspaceId, - issueId, - taskId: task.task_id, - requestId: task.awaiting_approval_request_id, - userId: task.user_id, - }); - } + await closeEndedApprovalThread(event, task, approvalsTable, workspaceId, issueId); // Iteration-UX: this task is a comment-iteration when it carries a maturing // reply id (set at trigger time). For those, the progress + terminal status diff --git a/cdk/src/handlers/shared/approval-notifications.ts b/cdk/src/handlers/shared/approval-notifications.ts index 8f5c33546..0c08a75f5 100644 --- a/cdk/src/handlers/shared/approval-notifications.ts +++ b/cdk/src/handlers/shared/approval-notifications.ts @@ -105,6 +105,82 @@ function describeAction(row: Record, task: TaskRecord): string[ return lines; } +/** The body of a request that is still waiting for a decision: the action, why, the deadline and how to answer. */ +function pendingLines( + row: Record, + task: TaskRecord, + requestId: string, + channel: 'slack' | 'linear', +): string[] { + const lines: string[] = []; + lines.push('', ...describeAction(row, task), ''); + const reason = text(row.reason); + lines.push(reason.startsWith('Soft-deny:') + ? 'Why approval is required: your configured policy requires a human decision for this action.' + : `Why approval is required: ${reason || 'No explanation was saved with this request.'}`); + lines.push('Approve: allow this action once.', + 'Deny: block this action and return the decision to the agent.'); + const deadline = Date.parse(String(row.created_at)) + Number(row.timeout_s) * 1000; + if (Number.isFinite(deadline) && Number(row.timeout_s) > 0) { + lines.push(`Decision deadline: ${new Date(deadline).toISOString()}`); + } + if (channel === 'linear') { + lines.push('', 'Reply approve, or deny with an optional reason (for example "deny use the staging config"),', + 'to this comment while signed in as the task owner.'); + } + lines.push('', 'Technical details / CLI alternative', + `Task: ${task.task_id}`, `Request: ${requestId}`, + `Tool: ${text(row.tool_name, 100)}`, `Policy severity: ${text(row.severity, SEVERITY_MAX_LENGTH)}`, + `Policy detail: ${reason}`); + // Never interpolate untrusted text into suggested shell commands. + if ([task.task_id, requestId].every(id => /^[A-Za-z0-9_-]{1,128}$/.test(id))) { + lines.push('Respond using the CLI while signed in as the task owner:', + `bgagent approve ${task.task_id} ${requestId} --scope this_call`, + `bgagent deny ${task.task_id} ${requestId}`); + } + lines.push('Run bgagent pending to see currently open requests.'); + return lines; +} + +/** The notification's title and text lines for an approval row in `status`. */ +function renderApproval( + status: string, + row: Record, + task: TaskRecord, + requestId: string, + channel: 'slack' | 'linear', +): { title: string; lines: string[] } { + const title = status === 'PENDING' ? 'Approval needed' + : status === 'APPROVED' ? 'Approval recorded' + : status === 'DENIED' ? 'Denial recorded' + : status === 'TIMED_OUT' ? 'Approval request timed out' : 'Approval wait could not continue'; + const lines = [title]; + if (status === 'PENDING') { + lines.push(...pendingLines(row, task, requestId, channel)); + } else if (status === 'APPROVED') { + lines.push(`Task: ${task.task_id}`, `Request: ${requestId}`); + lines.push(`Scope: ${text(row.scope, SCOPE_MAX_LENGTH)}`); + lines.push(TERMINAL_STATUSES.includes(task.status) + ? `The decision is saved. Task status: ${task.status}. The task has already ended.` + : 'The decision is saved. The agent continues with this action.'); + } else if (status === 'DENIED') { + lines.push(`Task: ${task.task_id}`, `Request: ${requestId}`); + lines.push(`Reason: ${text(row.deny_reason) || 'No reason supplied.'}`); + lines.push(TERMINAL_STATUSES.includes(task.status) + ? `The decision is saved. Task status: ${task.status}. The task has already ended.` + : 'The decision is saved. The agent receives the denial and continues without this action.'); + } else { + lines.push(`Task: ${task.task_id}`, `Request: ${requestId}`); + // reason is the original policy explanation, not the cause of closure. + // The agent stores a polling failure in deny_reason on its timeout path. + const reason = status === 'TIMED_OUT' + ? text(row.deny_reason) || 'The configured decision deadline was reached.' + : text(task.error_message) || 'The agent could not continue this approval wait.'; + lines.push(`Reason: ${reason}`); + } + return { title, lines }; +} + /** Read saved state instead of showing an old, delayed "please approve" event. */ export async function loadApprovalNotification( ddb: DynamoDBDocumentClient, @@ -148,59 +224,7 @@ export async function loadApprovalNotification( if (status === 'PENDING' && (task.status !== 'AWAITING_APPROVAL' || task.awaiting_approval_request_id !== requestId)) return null; - const title = status === 'PENDING' ? 'Approval needed' - : status === 'APPROVED' ? 'Approval recorded' - : status === 'DENIED' ? 'Denial recorded' - : status === 'TIMED_OUT' ? 'Approval request timed out' : 'Approval wait could not continue'; - const lines = [title]; - if (status === 'PENDING') { - lines.push('', ...describeAction(row, task), ''); - const reason = text(row.reason); - lines.push(reason.startsWith('Soft-deny:') - ? 'Why approval is required: your configured policy requires a human decision for this action.' - : `Why approval is required: ${reason || 'No explanation was saved with this request.'}`); - lines.push('Approve: allow this action once.', - 'Deny: block this action and return the decision to the agent.'); - const deadline = Date.parse(row.created_at) + Number(row.timeout_s) * 1000; - if (Number.isFinite(deadline) && Number(row.timeout_s) > 0) { - lines.push(`Decision deadline: ${new Date(deadline).toISOString()}`); - } - if (channel === 'linear') { - lines.push('', 'Reply approve, or deny with an optional reason (for example "deny use the staging config"),', - 'to this comment while signed in as the task owner.'); - } - lines.push('', 'Technical details / CLI alternative', - `Task: ${task.task_id}`, `Request: ${requestId}`, - `Tool: ${text(row.tool_name, 100)}`, `Policy severity: ${text(row.severity, SEVERITY_MAX_LENGTH)}`, - `Policy detail: ${reason}`); - // Never interpolate untrusted text into suggested shell commands. - if ([task.task_id, requestId].every(id => /^[A-Za-z0-9_-]{1,128}$/.test(id))) { - lines.push('Respond using the CLI while signed in as the task owner:', - `bgagent approve ${task.task_id} ${requestId} --scope this_call`, - `bgagent deny ${task.task_id} ${requestId}`); - } - lines.push('Run bgagent pending to see currently open requests.'); - } else if (status === 'APPROVED') { - lines.push(`Task: ${task.task_id}`, `Request: ${requestId}`); - lines.push(`Scope: ${text(row.scope, SCOPE_MAX_LENGTH)}`); - lines.push(TERMINAL_STATUSES.includes(task.status) - ? `The decision is saved. Task status: ${task.status}. The task has already ended.` - : 'The decision is saved. The agent continues with this action.'); - } else if (status === 'DENIED') { - lines.push(`Task: ${task.task_id}`, `Request: ${requestId}`); - lines.push(`Reason: ${text(row.deny_reason) || 'No reason supplied.'}`); - lines.push(TERMINAL_STATUSES.includes(task.status) - ? `The decision is saved. Task status: ${task.status}. The task has already ended.` - : 'The decision is saved. The agent receives the denial and continues without this action.'); - } else { - lines.push(`Task: ${task.task_id}`, `Request: ${requestId}`); - // reason is the original policy explanation, not the cause of closure. - // The agent stores a polling failure in deny_reason on its timeout path. - const reason = status === 'TIMED_OUT' - ? text(row.deny_reason) || 'The configured decision deadline was reached.' - : text(task.error_message) || 'The agent could not continue this approval wait.'; - lines.push(`Reason: ${reason}`); - } + const { title, lines } = renderApproval(status, row, task, requestId, channel); return { title, text: lines.join('\n'), taskId: task.task_id, requestId, userId: task.user_id, marker }; } diff --git a/contracts/coverage-thresholds.json b/contracts/coverage-thresholds.json index d263e1185..564803aa6 100644 --- a/contracts/coverage-thresholds.json +++ b/contracts/coverage-thresholds.json @@ -7,6 +7,9 @@ "/@(src|test)/**/*(*.)@(spec|test).ts?(x)", "/@(src|test)/**/__tests__/**/*.ts?(x)" ], + "moduleNameMapper": { + "^(\\.{1,2}/.*)\\.js$": "$1" + }, "collectCoverage": true, "collectCoverageFrom": [ "src/**/*.ts", From 2faaaf0da4cf6b2fe8b8dcda8202e1778cb65545 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 13:54:07 +0000 Subject: [PATCH 12/27] fix(linear): carry the vault, grant-probe and approval-reply changes onto main The Linear changes of #996, #998, #1001 and #1004 were written before main's MicroVM approval lifecycle (#904), the nested maintenance stack, the shared Linear user lookup and the stricter lint. This adapts them: - approve/deny: recordApprovalForUser / recordDenialForUser keep main's post-commit step (audit and MicroVM wake) and add decision_source to its audit metadata; the API handler passes its invocation start and context - the grant health probe runs before the webhook processor's existing handler, which keeps its complexity record; the reconciler that triggers it stays in the maintenance nested stack, and the trigger sits inside main's `if (linearIntegration)` guard - the vault default resolves to on only with both Linear and AgentCore, and keeps main's guard for an explicit true without Linear - the shared Linear user lookup reads consistently, since approval replies and a session stop are authorized from it - the approval-reply check in handleCommentTrigger moves to a helper (the function was past the complexity ceiling); the control-character regexes that strip terminal escapes from untrusted text are marked as intended - stack tests count the vault's three functions and its consent-page stack --- cdk/src/handlers/linear-webhook-processor.ts | 27 ++++++++++++------- cdk/test/handlers/approve-task.test.ts | 2 ++ cdk/test/handlers/deny-task.test.ts | 2 ++ .../shared/approval-notifications.test.ts | 1 + cdk/test/stacks/agent.test.ts | 9 ++++--- 5 files changed, 28 insertions(+), 13 deletions(-) diff --git a/cdk/src/handlers/linear-webhook-processor.ts b/cdk/src/handlers/linear-webhook-processor.ts index bff8fb35a..aa0ad767a 100644 --- a/cdk/src/handlers/linear-webhook-processor.ts +++ b/cdk/src/handlers/linear-webhook-processor.ts @@ -2046,17 +2046,24 @@ function commentTargetBelongsToWorkspace( return false; } +/** + * A reply to an approval notice is a decision, not a task request. It is handled + * only for the exact thread ABCA created, and only for the owner. True when handled. + */ +async function handledAsApprovalReply(payload: LinearCommentEvent): Promise { + const approvalsTable = process.env.TASK_APPROVALS_TABLE_NAME; + if (!approvalsTable || !WORKSPACE_REGISTRY_TABLE) return false; + return handleLinearApprovalReply(payload, { + ddb, + approvalsTable, + taskTable: process.env.TASK_TABLE_NAME!, + registryTable: WORKSPACE_REGISTRY_TABLE, + lookupUser: lookupPlatformUser, + }); +} + async function handleCommentTrigger(payload: LinearCommentEvent): Promise { - // A reply to an approval notice is a decision, not a task request. It is - // handled only for the exact thread ABCA created, and only for the owner. - if (process.env.TASK_APPROVALS_TABLE_NAME && WORKSPACE_REGISTRY_TABLE - && await handleLinearApprovalReply(payload, { - ddb, - approvalsTable: process.env.TASK_APPROVALS_TABLE_NAME, - taskTable: process.env.TASK_TABLE_NAME!, - registryTable: WORKSPACE_REGISTRY_TABLE, - lookupUser: lookupPlatformUser, - })) return; + if (await handledAsApprovalReply(payload)) return; // Orchestration must be enabled + a workspace token resolvable. if (!ORCHESTRATION_TABLE || !WORKSPACE_REGISTRY_TABLE) { diff --git a/cdk/test/handlers/approve-task.test.ts b/cdk/test/handlers/approve-task.test.ts index 3f1f1543d..67e5f5d73 100644 --- a/cdk/test/handlers/approve-task.test.ts +++ b/cdk/test/handlers/approve-task.test.ts @@ -302,6 +302,8 @@ describe('trusted channel decision source', () => { await handler(makeEvent({ body: JSON.stringify({ request_id: 'gate', decision: 'approve', decisionSource: 'forged' }) })); const update = mockSend.mock.calls.find(([cmd]) => cmd._type === 'TransactWrite')![0].input.TransactItems[0].Update; expect(update.UpdateExpression).not.toContain('decision_source'); + }); +}); describe('approve-task — decision source (#1001)', () => { test('API callers record no decision_source (behaviour unchanged)', async () => { diff --git a/cdk/test/handlers/deny-task.test.ts b/cdk/test/handlers/deny-task.test.ts index dd7678455..2a9cc22df 100644 --- a/cdk/test/handlers/deny-task.test.ts +++ b/cdk/test/handlers/deny-task.test.ts @@ -337,6 +337,8 @@ describe('trusted channel decision source', () => { await handler(makeEvent({ body: JSON.stringify({ request_id: 'gate', decision: 'deny', decisionSource: 'forged' }) })); const update = mockSend.mock.calls.find(([cmd]) => cmd._type === 'TransactWrite')![0].input.TransactItems[0].Update; expect(update.UpdateExpression).not.toContain('decision_source'); + }); +}); describe('deny-task — decision source (#1001)', () => { test('API callers record no decision_source (behaviour unchanged)', async () => { diff --git a/cdk/test/handlers/shared/approval-notifications.test.ts b/cdk/test/handlers/shared/approval-notifications.test.ts index b8a3d0d3b..f137bb687 100644 --- a/cdk/test/handlers/shared/approval-notifications.test.ts +++ b/cdk/test/handlers/shared/approval-notifications.test.ts @@ -199,5 +199,6 @@ test('redacts known credential shapes before posting a preview to a shared chann const message = (await loadApprovalNotification(ddb, task, 'approval_requested', { request_id: 'gate' }, 'slack'))!; expect(message.text).toContain('[REDACTED-GITHUB_TOKEN]'); expect(message.text).not.toContain(token); + // eslint-disable-next-line no-control-regex -- asserts the escape character was stripped expect(message.text).not.toMatch(/[\u001b\u202e]/); }); diff --git a/cdk/test/stacks/agent.test.ts b/cdk/test/stacks/agent.test.ts index 70fa0e22d..48d4b4256 100644 --- a/cdk/test/stacks/agent.test.ts +++ b/cdk/test/stacks/agent.test.ts @@ -1248,6 +1248,8 @@ describe('AgentStack', () => { 'TestAgentStack/AgentRegistryStack': [], 'TestAgentStack/RegistryApi': [], 'TestAgentStack/ConcurrencyMaintenance': Array(2).fill(notifiesTopic), + // On by default with Linear and AgentCore; the consent page has no alarms of its own. + 'TestAgentStack/LinearVaultConsentPageStack': [], }); }); @@ -1925,10 +1927,11 @@ describe('AgentStack solution attribution (#319): AWS_SDK_UA_APP_ID via stack-le // unnoticed; the exact count fails if a Lambda is dropped OR if a new one // is added without being attributed below. // 48 existing handlers (5 scheduled maintenance jobs nested) + 2 registry - // provisioning handlers + 4 registry API handlers in nested stacks, + 2 now + // provisioning handlers + 4 registry API handlers in nested stacks, + 3 now // that the Linear identity vault is on by default (its provider onEvent - // handler and the provider framework function). - expect(abcaLambdas.length).toBe(56); + // handler, the provider framework function and the consent page's function + // in its nested stack). + expect(abcaLambdas.length).toBe(57); // Every ABCA-authored Lambda must carry the canonical `#` app-id. Collect // any offenders so a failure names the exact logical id(s) that are naked. const unattributed = abcaLambdas From 8bcf2f5eea48abce08723836c46d619a121cdc7d Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 14:22:11 +0000 Subject: [PATCH 13/27] feat(linear): approval requests in the agent session, and redact what goes out Approval requests in a Linear agent session (#1066): - a pending Cedar request is posted as an elicitation with Approve / Deny buttons (signal: select) and the time by which it is denied unanswered, from the same notice loader as the comment channel, so a delayed request that is no longer open is never shown and the text gets the same redaction - a reply in the session decides the task's open request (awaiting_approval_request_id) through recordApprovalForUser / recordDenialForUser with a linear_session decision source; only the task owner can decide, and any other reply posts the choice again so the session keeps waiting for input - a decision made elsewhere, a timeout or a stranded wait is a note; a decision made in the session is not echoed - an approve / deny when nothing is waiting is answered and starts nothing, so a late answer after a timeout cannot start new work Outbound redaction: every Linear GraphQL call's variables and every GitHub comment body the platform posts pass through the secret scanner, so agent-originated text the platform relays cannot carry a credential out. Linear API keys and OAuth tokens (lin_api_, lin_oauth_) join the scanner's patterns in the CDK and the agent, with a shared vector. --- agent/src/output_scanner.py | 2 + cdk/src/handlers/fanout-task-events.ts | 52 ++++++ .../handlers/shared/approval-notifications.ts | 31 +++- .../handlers/shared/deny-reason-scanner.ts | 22 +++ cdk/src/handlers/shared/github-comment.ts | 5 +- .../shared/linear-agent-session-handler.ts | 95 ++++++++++- .../handlers/shared/linear-agent-session.ts | 16 +- cdk/src/handlers/shared/linear-console.ts | 3 +- cdk/src/handlers/shared/linear-feedback.ts | 5 +- .../shared/linear-session-approval.ts | 154 ++++++++++++++++++ .../fanout-linear-session-progress.test.ts | 72 ++++++++ .../shared/deny-reason-scanner.test.ts | 20 ++- .../linear-agent-session-handler.test.ts | 82 ++++++++++ .../handlers/shared/linear-feedback.test.ts | 7 + .../shared/linear-session-approval.test.ts | 86 ++++++++++ contracts/secret-scan-vectors.json | 5 + docs/guides/LINEAR_SETUP_GUIDE.md | 2 + .../content/docs/using/Linear-setup-guide.md | 2 + 18 files changed, 643 insertions(+), 18 deletions(-) create mode 100644 cdk/src/handlers/shared/linear-session-approval.ts create mode 100644 cdk/test/handlers/shared/linear-session-approval.test.ts diff --git a/agent/src/output_scanner.py b/agent/src/output_scanner.py index 9230fff84..08e6e8fd8 100644 --- a/agent/src/output_scanner.py +++ b/agent/src/output_scanner.py @@ -94,6 +94,8 @@ class ScanResult: ), # Slack tokens (xoxb-, xoxp-, ...) ("SLACK_TOKEN", re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}\b")), + # Linear personal API keys (lin_api_) and OAuth access tokens (lin_oauth_). + ("LINEAR_TOKEN", re.compile(r"\blin_(?:api|oauth)_[A-Za-z0-9]{16,}")), # Generic Bearer / token patterns (min 20-char token to avoid false positives # on natural English like "bearer of good news") ("BEARER_TOKEN", re.compile(r"Bearer\s+[a-zA-Z0-9\-._~+/]{20,}=*", re.IGNORECASE)), diff --git a/cdk/src/handlers/fanout-task-events.ts b/cdk/src/handlers/fanout-task-events.ts index dd557ff51..98ca124e8 100644 --- a/cdk/src/handlers/fanout-task-events.ts +++ b/cdk/src/handlers/fanout-task-events.ts @@ -86,6 +86,7 @@ import { type LinearFeedbackContext, type LinearPostResult, } from './shared/linear-feedback'; +import { sessionApprovalActivity } from './shared/linear-session-approval'; import { checklistKind, checklistMoveForEvent, @@ -1633,6 +1634,10 @@ async function dispatchToLinearAgentSession( ctx: LinearFeedbackContext, ): Promise { const effective = effectiveEventType(event); + if (isApprovalNotification(effective)) { + await dispatchSessionApproval(event, task, agentSessionId, ctx); + return; + } await advanceSessionChecklist(event, task, agentSessionId, ctx); if (LINEAR_SESSION_PROGRESS_EVENTS.has(effective)) { const progress = sessionProgressActivity(effective, event.metadata); @@ -1724,6 +1729,53 @@ async function dispatchToLinearAgentSession( } } +/** + * An approval notice in the task's session (#1066): a pending request is a choice with + * Approve / Deny buttons, anything after it a note. Same loader as the comment channel, + * so a delayed "please approve" for a request that is no longer open is never shown. + * Retried through the batch like the comment channel's notice; the activity id is + * derived from the notice, so a retry is the same activity. + */ +async function dispatchSessionApproval( + event: FanOutEvent, + task: TaskRecord, + agentSessionId: string, + ctx: LinearFeedbackContext, +): Promise { + const effective = effectiveEventType(event); + const logCtx = { task_id: task.task_id, linear_agent_session_id: agentSessionId, event_type: effective }; + const approvalsTable = process.env.TASK_APPROVALS_TABLE_NAME; + if (!approvalsTable) { + logger.warn('[fanout/linear-session] approval notice skipped: TASK_APPROVALS_TABLE_NAME unset', logCtx); + return; + } + // After the final response a new activity would reopen the session. + if (task.linear_final_comment_event_id) return; + // A decision made in the session already has its reply there. + if (effective === 'approval_decision_recorded' + && String(event.metadata?.decision_source ?? '').startsWith('["linear_session"')) return; + const liveTask = (await ddb.send(new GetCommand({ + TableName: process.env.TASK_TABLE_NAME, Key: { task_id: task.task_id }, ConsistentRead: true, + }))).Item as TaskRecord | undefined; + if (!liveTask) return; + const notification = await loadApprovalNotification(ddb, liveTask, effective, event.metadata ?? {}, 'linear_session'); + if (!notification) return; + const token = await resolveToken(ctx); + if (!token) return; + const activity = sessionApprovalActivity(effective, notification); + const result = await emitAgentActivity(token, agentSessionId, activity.content, { + id: progressActivityId(`${notification.marker}#${notification.requestId}`), + ...(activity.signal && { signal: activity.signal, signalMetadata: activity.signalMetadata }), + }); + if (!result.ok) { + logger.warn('[fanout/linear-session] approval notice failed', { ...logCtx, retryable: result.retryable }); + if (result.retryable) throw new Error(`[fanout/linear-session] transient approval notice failure for task ${task.task_id}`); + return; + } + await markApprovalNotificationDelivered(ddb, notification); + logger.info('[fanout/linear-session] approval notice dispatched', { ...logCtx, request_id: notification.requestId }); +} + /** * How a finished task reads in its session: a pull request to review (also one shipped * by a run that then stopped early), a question back, no change, a stop, or a failure. diff --git a/cdk/src/handlers/shared/approval-notifications.ts b/cdk/src/handlers/shared/approval-notifications.ts index 0c08a75f5..6e5401738 100644 --- a/cdk/src/handlers/shared/approval-notifications.ts +++ b/cdk/src/handlers/shared/approval-notifications.ts @@ -18,10 +18,10 @@ */ import { GetCommand, UpdateCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { TaskStatus, TERMINAL_STATUSES } from '../../constructs/task-status'; import { scanDenyReason } from './deny-reason-scanner'; import { logger } from './logger'; import type { TaskRecord } from './types'; -import { TaskStatus, TERMINAL_STATUSES } from '../../constructs/task-status'; const REQUEST_ID_MAX_LENGTH = 128; const SEVERITY_MAX_LENGTH = 20; @@ -47,13 +47,20 @@ export interface ApprovalNotification { readonly requestId: string; readonly userId: string; readonly marker: string; + /** When a pending request is denied unanswered (ISO), if it has a timeout. */ + readonly deadline?: string; } +/** Where a notice goes. A Linear agent session answers with buttons, not a comment reply. */ +export type ApprovalChannel = 'slack' | 'linear' | 'linear_session'; + function text(value: unknown, max = 500): string { if (typeof value !== 'string') return ''; // Redact before truncation so cutting a token cannot hide its recognizable shape. const clean = scanDenyReason(value) + // eslint-disable-next-line no-control-regex -- strips terminal escape sequences from untrusted text .replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '') + // eslint-disable-next-line no-control-regex -- strips control and bidi characters from untrusted text .replace(/[\u0000-\u0008\u000b-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, ''); return clean.length > max ? `${clean.slice(0, max)}… [shortened]` : clean; } @@ -110,7 +117,7 @@ function pendingLines( row: Record, task: TaskRecord, requestId: string, - channel: 'slack' | 'linear', + channel: ApprovalChannel, ): string[] { const lines: string[] = []; lines.push('', ...describeAction(row, task), ''); @@ -127,6 +134,9 @@ function pendingLines( if (channel === 'linear') { lines.push('', 'Reply approve, or deny with an optional reason (for example "deny use the staging config"),', 'to this comment while signed in as the task owner.'); + } else if (channel === 'linear_session') { + lines.push('', 'Choose Approve or Deny below, or reply deny with a reason (for example "deny use the staging config").', + 'Only the task owner can decide.'); } lines.push('', 'Technical details / CLI alternative', `Task: ${task.task_id}`, `Request: ${requestId}`, @@ -148,7 +158,7 @@ function renderApproval( row: Record, task: TaskRecord, requestId: string, - channel: 'slack' | 'linear', + channel: ApprovalChannel, ): { title: string; lines: string[] } { const title = status === 'PENDING' ? 'Approval needed' : status === 'APPROVED' ? 'Approval recorded' @@ -187,7 +197,7 @@ export async function loadApprovalNotification( task: TaskRecord, eventType: string, metadata: Record, - channel: 'slack' | 'linear', + channel: ApprovalChannel, ): Promise { if (!isApprovalNotification(eventType)) return null; const tableName = process.env.TASK_APPROVALS_TABLE_NAME; @@ -225,7 +235,18 @@ export async function loadApprovalNotification( && (task.status !== 'AWAITING_APPROVAL' || task.awaiting_approval_request_id !== requestId)) return null; const { title, lines } = renderApproval(status, row, task, requestId, channel); - return { title, text: lines.join('\n'), taskId: task.task_id, requestId, userId: task.user_id, marker }; + const deadlineMs = Date.parse(String(row.created_at)) + Number(row.timeout_s) * 1000; + const deadline = status === 'PENDING' && Number.isFinite(deadlineMs) && Number(row.timeout_s) > 0 + ? new Date(deadlineMs).toISOString() : undefined; + return { + title, + text: lines.join('\n'), + taskId: task.task_id, + requestId, + userId: task.user_id, + marker, + ...(deadline && { deadline }), + }; } /** Persist only after the external service accepted the message, so failures retry. */ diff --git a/cdk/src/handlers/shared/deny-reason-scanner.ts b/cdk/src/handlers/shared/deny-reason-scanner.ts index 334d59a54..38d124f1c 100644 --- a/cdk/src/handlers/shared/deny-reason-scanner.ts +++ b/cdk/src/handlers/shared/deny-reason-scanner.ts @@ -100,6 +100,11 @@ const PATTERNS: readonly SecretPattern[] = [ name: 'SLACK_TOKEN', regex: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, }, + { + name: 'LINEAR_TOKEN', + // Linear personal API keys (`lin_api_`) and OAuth access tokens (`lin_oauth_`). + regex: /\blin_(?:api|oauth)_[A-Za-z0-9]{16,}/g, + }, { name: 'GENERIC_BEARER', regex: /\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/gi, @@ -190,3 +195,20 @@ export function scanDenyReason(text: string): string { */ export const DENY_REASON_SECRET_NAMES: readonly string[] = PATTERNS.map((p) => p.name); + +/** + * {@link scanDenyReason} over every string in a JSON-shaped value. Applied to the + * variables of every outbound Linear GraphQL call and to GitHub comment bodies, so + * agent-originated text the platform relays (answers, error messages, event + * details) cannot carry a credential out, whatever path it took. + * @param value - a JSON-shaped value. + * @returns the same shape with known secrets replaced. + */ +export function redactValue(value: T): T { + if (typeof value === 'string') return scanDenyReason(value) as T; + if (Array.isArray(value)) return value.map((v: unknown) => redactValue(v)) as T; + if (value !== null && typeof value === 'object') { + return Object.fromEntries(Object.entries(value as Record).map(([k, v]) => [k, redactValue(v)])) as T; + } + return value; +} diff --git a/cdk/src/handlers/shared/github-comment.ts b/cdk/src/handlers/shared/github-comment.ts index 25eeb38b8..34832e67d 100644 --- a/cdk/src/handlers/shared/github-comment.ts +++ b/cdk/src/handlers/shared/github-comment.ts @@ -46,6 +46,7 @@ * codebase pattern (``preflight.ts``, ``context-hydration.ts``). */ +import { scanDenyReason } from './deny-reason-scanner'; import { logger } from './logger'; import { coerceNumericOrNull } from './numeric'; @@ -187,7 +188,7 @@ async function patchExistingComment(params: { 'User-Agent': USER_AGENT, 'Content-Type': 'application/json', }, - body: JSON.stringify({ body }), + body: JSON.stringify({ body: scanDenyReason(body) }), signal: AbortSignal.timeout(GITHUB_TIMEOUT_MS), }); } catch (err) { @@ -226,7 +227,7 @@ async function createComment(params: { 'User-Agent': USER_AGENT, 'Content-Type': 'application/json', }, - body: JSON.stringify({ body }), + body: JSON.stringify({ body: scanDenyReason(body) }), signal: AbortSignal.timeout(GITHUB_TIMEOUT_MS), }); } catch (err) { diff --git a/cdk/src/handlers/shared/linear-agent-session-handler.ts b/cdk/src/handlers/shared/linear-agent-session-handler.ts index 75f96b55e..d6c6c9449 100644 --- a/cdk/src/handlers/shared/linear-agent-session-handler.ts +++ b/cdk/src/handlers/shared/linear-agent-session-handler.ts @@ -38,6 +38,7 @@ import { type AgentSessionRequest, type LinearAgentSessionEvent, } from './linear-agent-session-event'; +import { parseLinearApprovalReply } from './linear-approval-thread'; import { lookupLinearPlatformUser, lookupLinearProjectMapping, @@ -47,6 +48,12 @@ import { writeSessionTaskPointer, } from './linear-channel-metadata'; import { resolveLinearOauthToken, type ResolvedLinearToken } from './linear-oauth-resolver'; +import { + NOTHING_TO_APPROVE_MESSAGE, + repeatedApprovalChoice, + sessionDecisionNote, + type SessionApprovalActivity, +} from './linear-session-approval'; import { fetchIssueParentId } from './linear-subissue-fetch'; import { lookupTaskByLinearIssue, type LinearIssueTask } from './linear-task-by-issue'; import { logger } from './logger'; @@ -70,6 +77,8 @@ const TASK_EVENTS_TABLE_NAME = process.env.TASK_EVENTS_TABLE_NAME!; const TASK_RETENTION_DAYS = Number(process.env.TASK_RETENTION_DAYS ?? '90'); /** Optional: without it a follow-up to a running task cannot be forwarded to the agent. */ const NUDGES_TABLE_NAME = process.env.NUDGES_TABLE_NAME; +/** Set when approval replies are configured; a session decides a request only then. */ +const TASK_APPROVALS_TABLE_NAME = process.env.TASK_APPROVALS_TABLE_NAME; /** Same value TaskApi gives `POST /tasks/{id}/nudge`: both paths share one counter row. */ const NUDGE_RATE_LIMIT_PER_MINUTE = Number(process.env.NUDGE_RATE_LIMIT_PER_MINUTE ?? '10'); /** Optional: holds the session → task pointer that covers the issue index's lag. */ @@ -130,8 +139,8 @@ export async function handleAgentSessionEvent(payload: LinearAgentSessionEvent): logger.warn('Agent-session delivery for an unresolvable workspace — ignoring', logCtx); return; } - const emit = (content: AgentActivityContent, ephemeral = false) => - emitSessionActivity(resolved.accessToken, request, content, ephemeral); + const emit = (content: AgentActivityContent, ephemeral = false, signal?: Omit) => + emitSessionActivity(resolved.accessToken, request, content, ephemeral, signal); // Per-workspace evidence that sessions open here; the comment trigger only // yields to sessions in workspaces that carry it. Started now but awaited // only once the delivery is handled, so its round trip never sits between @@ -192,6 +201,12 @@ async function respondToAgentSession( await steerRunningTask(request, priorTask, platformUserId, emit); return; } + // A late "approve" / "deny" (after its request timed out, or in the wrong session) + // is an answer to nothing. Taken as a prompt it would start new work. + if (parseLinearApprovalReply(request.directive)) { + await emit({ type: 'response', body: NOTHING_TO_APPROVE_MESSAGE }); + return; + } const issueResult = await fetchAgentSessionIssue(resolved.accessToken, request.issueId); if (isLookupFailure(issueResult)) { @@ -421,10 +436,19 @@ async function steerRunningTask( request: AgentSessionRequest, task: PriorTask, platformUserId: string, - emit: (content: AgentActivityContent) => Promise, + emit: SessionEmit, ): Promise { const ownSession = isRunningTasksOwnSession(request, task); const reply = (body: string) => emit(ownSession ? { type: 'thought', body } : { type: 'response', body }); + const openRequest = task.status === 'AWAITING_APPROVAL' ? task.awaiting_approval_request_id : undefined; + if (ownSession && openRequest && request.directive) { + await decideSessionApproval(request, task, openRequest, platformUserId, emit); + return; + } + if (parseLinearApprovalReply(request.directive)) { + await reply(NOTHING_TO_APPROVE_MESSAGE); + return; + } if (!request.directive) { await reply(ownSession ? `Already working on this (task \`${task.task_id}\`) — I'll report back here.` @@ -464,9 +488,69 @@ async function steerRunningTask( await reply(body); } +type SessionEmit = ( + content: AgentActivityContent, ephemeral?: boolean, signal?: Omit, +) => Promise; + +/** + * A reply in the session while its task waits on an approval request: an approve / + * deny from the task's owner decides that request through the API's decision path. + * Anything else shows the choice again, so the request stays the session's last + * activity (a thought would end its waiting-for-input state and bury it). + */ +async function decideSessionApproval( + request: AgentSessionRequest, + task: PriorTask, + requestId: string, + platformUserId: string, + emit: SessionEmit, +): Promise { + const again = async (lead: string) => { + const activity = repeatedApprovalChoice(lead); + await emit(activity.content, false, activity); + }; + const answer = parseLinearApprovalReply(request.directive); + if (!answer) { + await again('That isn\'t an answer to the open approval request, so I haven\'t passed it to the agent.'); + return; + } + if (task.user_id !== platformUserId) { + await again(`Only the task owner can decide this request. ${NOT_OWNER_MESSAGE}`); + return; + } + if (!TASK_APPROVALS_TABLE_NAME) { + await emit({ type: 'thought', body: 'Approvals can\'t be answered in Linear on this deployment. Use `bgagent approve` / `bgagent deny`.' }); + return; + } + // Loaded only when a session decides: other session deliveries do not need the + // decision handlers' environment. + const record = answer.decision === 'approve' + ? (await import('../approve-task.js')).recordApprovalForUser + : (await import('../deny-task.js')).recordDenialForUser; + const result = await record({ + userId: platformUserId, + taskId: task.task_id, + decisionSource: JSON.stringify(['linear_session', request.workspaceId, request.deliveryId]), + body: JSON.stringify({ + request_id: requestId, + decision: answer.decision, + ...(answer.decision === 'deny' && answer.reason ? { reason: answer.reason } : {}), + }), + }); + logger.info('Agent-session approval reply', { + linear_agent_session_id: request.sessionId, + task_id: task.task_id, + request_id: requestId, + decision: answer.decision, + status_code: result.statusCode, + }); + await emit({ type: 'thought', body: sessionDecisionNote(answer, result) }); +} + /** The prior task as read from the base table (strongly consistent). */ type PriorTask = LinearIssueTask & ClarifyHoldRow - & Pick + & Pick & { readonly status: TaskStatusType; readonly channel_metadata?: Readonly>; @@ -582,8 +666,9 @@ async function emitSessionActivity( request: AgentSessionRequest, content: AgentActivityContent, ephemeral: boolean, + signal?: Omit, ): Promise { - const result = await emitAgentActivity(accessToken, request.sessionId, content, { ephemeral }); + const result = await emitAgentActivity(accessToken, request.sessionId, content, { ephemeral, ...signal }); if (!result.ok) { // Best-effort: the task outcome is still delivered by the fan-out plane. logger.warn('Failed to emit Linear agent activity', { diff --git a/cdk/src/handlers/shared/linear-agent-session.ts b/cdk/src/handlers/shared/linear-agent-session.ts index d333d1478..dccce5f16 100644 --- a/cdk/src/handlers/shared/linear-agent-session.ts +++ b/cdk/src/handlers/shared/linear-agent-session.ts @@ -76,12 +76,24 @@ export async function emitAgentActivity( accessToken: string, agentSessionId: string, content: AgentActivityContent, - options: { readonly ephemeral?: boolean; readonly id?: string } = {}, + options: { + readonly ephemeral?: boolean; + readonly id?: string; + /** ``select`` turns an elicitation into buttons; ``signalMetadata.options`` lists them. */ + readonly signal?: 'select'; + readonly signalMetadata?: Readonly>; + } = {}, ): Promise { const ephemeral = options.ephemeral === true && (content.type === 'thought' || content.type === 'action'); return graphqlRequest(accessToken, AGENT_ACTIVITY_CREATE_MUTATION, { // `id` (a version-4 UUID) makes a retried emit the same activity rather than a second one. - input: { agentSessionId, content, ...(ephemeral && { ephemeral: true }), ...(options.id && { id: options.id }) }, + input: { + agentSessionId, + content, + ...(ephemeral && { ephemeral: true }), + ...(options.id && { id: options.id }), + ...(options.signal && { signal: options.signal, signalMetadata: options.signalMetadata ?? {} }), + }, }); } diff --git a/cdk/src/handlers/shared/linear-console.ts b/cdk/src/handlers/shared/linear-console.ts index 9c763b713..e6b3e1916 100644 --- a/cdk/src/handlers/shared/linear-console.ts +++ b/cdk/src/handlers/shared/linear-console.ts @@ -19,6 +19,7 @@ import { ConditionalCheckFailedException } from '@aws-sdk/client-dynamodb'; import { DeleteCommand, type DynamoDBDocumentClient, GetCommand, PutCommand } from '@aws-sdk/lib-dynamodb'; +import { redactValue } from './deny-reason-scanner'; /** * Linear helpers for the operator console: list a mapped project's open issues, and @@ -50,7 +51,7 @@ async function linearQuery(accessToken: string, query: string, variables: Rec resp = await fetchImpl(LINEAR_GRAPHQL_URL, { method: 'POST', headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' }, - body: JSON.stringify({ query, variables }), + body: JSON.stringify({ query, variables: redactValue(variables) }), signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), }); } catch (err) { diff --git a/cdk/src/handlers/shared/linear-feedback.ts b/cdk/src/handlers/shared/linear-feedback.ts index 4454e1b16..a6d77f08a 100644 --- a/cdk/src/handlers/shared/linear-feedback.ts +++ b/cdk/src/handlers/shared/linear-feedback.ts @@ -17,6 +17,7 @@ * SOFTWARE. */ +import { redactValue } from './deny-reason-scanner'; import { isTerminalMaturingReply, preservePreviewSuffix } from './iteration-reply'; import { resolveLinearOauthToken } from './linear-oauth-resolver'; import { logger } from './logger'; @@ -255,7 +256,7 @@ export async function graphqlData( const resp = await fetch(LINEAR_GRAPHQL_URL, { method: 'POST', headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' }, - body: JSON.stringify({ query, variables }), + body: JSON.stringify({ query, variables: redactValue(variables) }), signal: controller.signal, }); if (!resp.ok) { @@ -308,7 +309,7 @@ export async function graphqlRequest( 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json', }, - body: JSON.stringify({ query, variables }), + body: JSON.stringify({ query, variables: redactValue(variables) }), signal: controller.signal, }); if (!resp.ok) { diff --git a/cdk/src/handlers/shared/linear-session-approval.ts b/cdk/src/handlers/shared/linear-session-approval.ts new file mode 100644 index 000000000..e49e11498 --- /dev/null +++ b/cdk/src/handlers/shared/linear-session-approval.ts @@ -0,0 +1,154 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Cedar approval requests answered inside a Linear agent session (#1066). + * + * The fan-out posts a pending request as an ``elicitation`` with Approve / Deny + * buttons (``signal: select``) and a reply-by line, using the same notice text as + * the comment channel (``approval-notifications.ts``, so the same redaction and + * escaping). A reply in the session decides the task's open request through the + * API's decision path (``recordApprovalForUser`` / ``recordDenialForUser``): only + * the task's owner can decide, and a request that already timed out or was + * answered is left alone. The open request is the task record's + * ``awaiting_approval_request_id``, so a session needs no pointer rows. + */ + +import { approvalNotificationMarkdown, type ApprovalNotification } from './approval-notifications'; +import type { AgentActivityContent } from './linear-agent-session'; +import type { LinearApprovalReply } from './linear-approval-thread'; + +/** The buttons. Their values are what the session sends back as the prompt, and what the reply parser reads. */ +export const SESSION_APPROVAL_OPTIONS: ReadonlyArray<{ readonly label: string; readonly value: string }> = [ + { label: 'Approve', value: 'approve' }, + { label: 'Deny', value: 'deny' }, +]; + +/** One activity plus the options ``emitAgentActivity`` takes. */ +export interface SessionApprovalActivity { + readonly content: AgentActivityContent; + readonly signal?: 'select'; + readonly signalMetadata?: Readonly>; +} + +const MINUTE_MS = 60_000; +const MINUTES_PER_HOUR = 60; +const HOURS_PER_DAY = 24; +const ISO_CLOCK = { start: 11, end: 16 } as const; +const ISO_DATE_END = 10; +const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] as const; +const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] as const; + +/** ``in 30 min``, ``in 3 h``, ``in 2 days``, ``now``. */ +function relativeTime(ms: number): string { + const min = Math.round(ms / MINUTE_MS); + if (min <= 0) return 'now'; + if (min < MINUTES_PER_HOUR * 2) return `in ${min} min`; + const hours = Math.round(min / MINUTES_PER_HOUR); + if (hours < HOURS_PER_DAY * 2) return `in ${hours} h`; + return `in ${Math.round(hours / HOURS_PER_DAY)} days`; +} + +/** + * A deadline as a person reads it: ``21:40 UTC (in 30 min)``, with the date when it + * is not today (``Tue 17 Nov, 09:40 UTC (in 12 h)``). Null for an unparseable time. + * @param iso - the deadline. + * @param now - the reference time. + */ +export function formatDeadline(iso: string, now: Date = new Date()): string | null { + const at = new Date(iso); + if (Number.isNaN(at.getTime())) return null; + const hhmm = at.toISOString().slice(ISO_CLOCK.start, ISO_CLOCK.end); + const sameDay = at.toISOString().slice(0, ISO_DATE_END) === now.toISOString().slice(0, ISO_DATE_END); + const day = sameDay ? '' : `${WEEKDAYS[at.getUTCDay()]} ${at.getUTCDate()} ${MONTHS[at.getUTCMonth()]}, `; + return `${day}${hhmm} UTC (${relativeTime(at.getTime() - now.getTime())})`; +} + +/** + * The line that says the reader has to act, and by when. + * @param deadline - when the request is denied unanswered (ISO), if it has one. + * @param now - the reference time. + */ +export function waitingOnYouLine(deadline: string | undefined, now: Date = new Date()): string { + const when = deadline ? formatDeadline(deadline, now) : null; + return when + ? `**Waiting on you.** Reply by ${when}, or it is denied and the agent carries on without it.` + : '**Waiting on you.** The agent is paused until you answer.'; +} + +/** The buttons, as ``emitAgentActivity`` options. */ +function choice(body: string): SessionApprovalActivity { + return { content: { type: 'elicitation', body }, signal: 'select', signalMetadata: { options: SESSION_APPROVAL_OPTIONS } }; +} + +/** + * The session activity for an approval notice: a pending request is a choice with + * buttons; a decision, a timeout or a stranded wait is a thought. + * @param eventType - the approval event. + * @param notification - the notice loaded for the ``linear_session`` channel. + * @param now - the reference time for the deadline. + */ +export function sessionApprovalActivity( + eventType: string, notification: ApprovalNotification, now: Date = new Date(), +): SessionApprovalActivity { + const body = approvalNotificationMarkdown(notification); + if (eventType === 'approval_requested') return choice(`${body}\n\n${waitingOnYouLine(notification.deadline, now)}`); + return { content: { type: 'thought', body } }; +} + +/** + * The choice again, with a line above it. Posted when a reply could not decide the + * request, so the request stays the session's last activity and Linear keeps + * showing the session as waiting for input. + * @param lead - why it is shown again. + */ +export function repeatedApprovalChoice(lead: string): SessionApprovalActivity { + return choice(`${lead}\n\nChoose **Approve** or **Deny**, or reply deny with a reason.`); +} + +/** What the decision handlers return. */ +export interface DecisionResult { readonly statusCode: number } + +const HTTP_OK_MIN = 200; +const HTTP_OK_END = 300; +const HTTP_NOT_FOUND = 404; +const HTTP_CONFLICT = 409; +const HTTP_TOO_MANY = 429; + +/** + * The note after a decision was attempted. + * @param reply - the parsed answer. + * @param result - the decision handler's result. + */ +export function sessionDecisionNote(reply: LinearApprovalReply, result: DecisionResult): string { + if (result.statusCode >= HTTP_OK_MIN && result.statusCode < HTTP_OK_END) { + return reply.decision === 'approve' + ? 'Approved. The agent continues with this action.' + : `Denied. The agent carries on without it${reply.reason ? ` (your reason: ${reply.reason})` : ''}.`; + } + if (result.statusCode === HTTP_CONFLICT || result.statusCode === HTTP_NOT_FOUND) { + return 'That request was already answered or timed out, so nothing changed. The agent asks again if it still needs to.'; + } + if (result.statusCode === HTTP_TOO_MANY) return 'Too many approval decisions in the last minute. Reply again in a moment.'; + return 'I couldn\'t record that decision. Reply again, or use `bgagent approve` / `bgagent deny`.'; +} + +/** The reply to an approve / deny when nothing in the session is waiting for one. */ +export const NOTHING_TO_APPROVE_MESSAGE = 'Nothing is waiting for your approval here, so nothing was approved or denied. ' + + 'I haven\'t started or re-run anything. To ask for more work, say what you want done.'; diff --git a/cdk/test/handlers/fanout-linear-session-progress.test.ts b/cdk/test/handlers/fanout-linear-session-progress.test.ts index 059a582b6..ec19377e7 100644 --- a/cdk/test/handlers/fanout-linear-session-progress.test.ts +++ b/cdk/test/handlers/fanout-linear-session-progress.test.ts @@ -52,7 +52,16 @@ jest.mock('../../src/handlers/shared/linear-agent-session', () => ({ addAgentSessionExternalUrl: jest.fn().mockResolvedValue({ ok: true }), })); +const mockLoadApproval = jest.fn(); +const mockMarkApproval = jest.fn().mockResolvedValue(undefined); +jest.mock('../../src/handlers/shared/approval-notifications', () => ({ + ...jest.requireActual('../../src/handlers/shared/approval-notifications'), + loadApprovalNotification: (...args: unknown[]) => mockLoadApproval(...args), + markApprovalNotificationDelivered: (...args: unknown[]) => mockMarkApproval(...args), +})); + process.env.LINEAR_AGENT_SESSIONS_ENABLED = 'true'; +process.env.TASK_APPROVALS_TABLE_NAME = 'Approvals'; process.env.TASK_TABLE_NAME = 'Tasks'; process.env.LINEAR_WORKSPACE_REGISTRY_TABLE_NAME = 'LinearWorkspaceRegistry'; @@ -100,6 +109,8 @@ beforeEach(() => { mockEmitAgentActivity.mockReset().mockResolvedValue({ ok: true }); mockSetPlan.mockReset().mockResolvedValue({ ok: true }); mockTransitionIssueState.mockClear(); + mockLoadApproval.mockReset(); + mockMarkApproval.mockClear(); resetLinearHeartbeatMemoForTests(); }); @@ -256,3 +267,64 @@ test('a failed checklist write never blocks the final response', async () => { expect(outcome.infraRejections).toEqual([]); expect(mockEmitAgentActivity).toHaveBeenCalledWith('lin_tok', 'session-1', expect.objectContaining({ type: 'response' })); }); + +// --- Approval requests in the session --- + +const PENDING_NOTICE = { + title: 'Approval needed', + text: 'Approval needed\nThe agent wants to run a shell command.', + taskId: 't-sess', + requestId: 'req-1', + userId: 'u-1', + marker: 'notified_linear_session_approval_requested', + deadline: '2026-11-20T00:30:00Z', +}; + +test('a pending request goes into the session as Approve / Deny buttons, once', async () => { + mockTask({ ...SESSION_TASK, status: 'AWAITING_APPROVAL', awaiting_approval_request_id: 'req-1' }); + mockLoadApproval.mockResolvedValue(PENDING_NOTICE); + await routeEvent(ev('agent_milestone', { milestone: 'approval_requested', request_id: 'req-1' }), LINEAR_ONLY); + expect(mockLoadApproval).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ task_id: 't-sess' }), + 'approval_requested', expect.objectContaining({ request_id: 'req-1' }), 'linear_session'); + const [, session, content, options] = mockEmitAgentActivity.mock.calls[0]; + expect(session).toBe('session-1'); + expect(content.type).toBe('elicitation'); + expect(content.body).toContain('**Waiting on you.**'); + expect(options).toEqual(expect.objectContaining({ signal: 'select', id: expect.stringMatching(/^[0-9a-f-]{36}$/) })); + expect(mockMarkApproval).toHaveBeenCalledWith(expect.anything(), PENDING_NOTICE); + expect(mockPostIssueComment).not.toHaveBeenCalled(); +}); + +test('a request that is no longer open is not shown', async () => { + mockTask(SESSION_TASK); + mockLoadApproval.mockResolvedValue(null); + await routeEvent(ev('agent_milestone', { milestone: 'approval_requested', request_id: 'req-1' }), LINEAR_ONLY); + expect(mockEmitAgentActivity).not.toHaveBeenCalled(); +}); + +test('a decision made in the session is not echoed; one made elsewhere is a note', async () => { + mockTask(SESSION_TASK); + mockLoadApproval.mockResolvedValue({ ...PENDING_NOTICE, title: 'Approval recorded', marker: 'notified_linear_session_approval_decision_recorded' }); + await routeEvent(ev('agent_milestone', { + milestone: 'approval_decision_recorded', request_id: 'req-1', decision_source: '["linear_session","org-1","p-1"]', + }), LINEAR_ONLY); + expect(mockLoadApproval).not.toHaveBeenCalled(); + await routeEvent(ev('agent_milestone', { milestone: 'approval_decision_recorded', request_id: 'req-1' }, 'e-cli'), LINEAR_ONLY); + expect(mockEmitAgentActivity).toHaveBeenCalledWith('lin_tok', 'session-1', expect.objectContaining({ type: 'thought' }), expect.anything()); +}); + +test('a transient failure retries the batch, and nothing is marked delivered', async () => { + mockTask({ ...SESSION_TASK, status: 'AWAITING_APPROVAL', awaiting_approval_request_id: 'req-1' }); + mockLoadApproval.mockResolvedValue(PENDING_NOTICE); + mockEmitAgentActivity.mockResolvedValueOnce({ ok: false, retryable: true }); + const outcome = await routeEvent(ev('agent_milestone', { milestone: 'approval_requested', request_id: 'req-1' }), LINEAR_ONLY); + expect(outcome.infraRejections).toEqual(['linear']); + expect(mockMarkApproval).not.toHaveBeenCalled(); +}); + +test('after the final response nothing reopens the session', async () => { + mockTask({ ...SESSION_TASK, linear_final_comment_event_id: 'e-done' }); + mockLoadApproval.mockResolvedValue(PENDING_NOTICE); + await routeEvent(ev('agent_milestone', { milestone: 'approval_timed_out', request_id: 'req-1' }), LINEAR_ONLY); + expect(mockEmitAgentActivity).not.toHaveBeenCalled(); +}); diff --git a/cdk/test/handlers/shared/deny-reason-scanner.test.ts b/cdk/test/handlers/shared/deny-reason-scanner.test.ts index 4cbc50995..dd982c560 100644 --- a/cdk/test/handlers/shared/deny-reason-scanner.test.ts +++ b/cdk/test/handlers/shared/deny-reason-scanner.test.ts @@ -19,7 +19,7 @@ import * as fs from 'fs'; import * as path from 'path'; -import { DENY_REASON_SECRET_NAMES, scanDenyReason } from '../../../src/handlers/shared/deny-reason-scanner'; +import { DENY_REASON_SECRET_NAMES, redactValue, scanDenyReason } from '../../../src/handlers/shared/deny-reason-scanner'; // Shared with agent/tests/test_output_scanner.py: the agent's scanner has to // give the same text for a URL with a user and a password. @@ -381,3 +381,21 @@ describe('scanDenyReason', () => { expect(DENY_REASON_SECRET_NAMES).toContain('PRIVATE_KEY'); }); }); + +describe('redactValue (outbound Linear and GitHub text, #1066)', () => { + test('redacts every string in a nested value and keeps the shape and other values', () => { + const value = { + input: { body: 'token lin_api_EXAMPLE0EXAMPLE0EX here', count: 3, ok: true }, + list: ['AKIAIOSFODNN7EXAMPLE', null], + }; + expect(redactValue(value)).toEqual({ + input: { body: 'token [REDACTED-LINEAR_TOKEN] here', count: 3, ok: true }, + list: ['[REDACTED-AWS_KEY]', null], + }); + }); + + test('leaves ids and ordinary text alone', () => { + const value = { id: '420f1277-9f2b-4058-b9c1-ddbceeee6b96', body: 'Opened pull request https://github.com/acme/web/pull/7' }; + expect(redactValue(value)).toEqual(value); + }); +}); diff --git a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts index afdf004f3..5efad164e 100644 --- a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts +++ b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts @@ -93,6 +93,12 @@ process.env.TASK_EVENTS_TABLE_NAME = 'TaskEvents'; process.env.NUDGES_TABLE_NAME = 'Nudges'; process.env.NUDGE_RATE_LIMIT_PER_MINUTE = '4'; process.env.LINEAR_WEBHOOK_DEDUP_TABLE_NAME = 'LinearDedup'; +process.env.TASK_APPROVALS_TABLE_NAME = 'Approvals'; + +const recordApprovalMock = jest.fn(); +const recordDenialMock = jest.fn(); +jest.mock('../../../src/handlers/approve-task', () => ({ recordApprovalForUser: (...a: unknown[]) => recordApprovalMock(...a) })); +jest.mock('../../../src/handlers/deny-task', () => ({ recordDenialForUser: (...a: unknown[]) => recordDenialMock(...a) })); import { SESSION_STOP_CANCELLED_VIA } from '../../../src/handlers/shared/linear-agent-session-event'; import { handleAgentSessionEvent } from '../../../src/handlers/shared/linear-agent-session-handler'; @@ -797,3 +803,79 @@ describe('channel_metadata builders', () => { expect(offenders).toEqual([]); }); }); + +describe('handleAgentSessionEvent — approval requests in the session (#1066)', () => { + const waiting = (user = 'platform-user-1') => priorTask({ + task_id: 't-1', + status: 'AWAITING_APPROVAL', + awaiting_approval_request_id: 'req-1', + user_id: user, + linear_workspace_id: 'org-1', + session: 'session-1', + }); + const lastEmit = () => emitAgentActivityMock.mock.calls.at(-1)!; + + beforeEach(() => { + recordApprovalMock.mockResolvedValue({ statusCode: 202 }); + recordDenialMock.mockResolvedValue({ statusCode: 202 }); + }); + + test('the owner\'s Approve decides the open request through the API path, not as a nudge', async () => { + waiting(); + await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); + expect(recordApprovalMock).toHaveBeenCalledWith({ + userId: 'platform-user-1', + taskId: 't-1', + decisionSource: JSON.stringify(['linear_session', 'org-1', 'activity-9']), + body: JSON.stringify({ request_id: 'req-1', decision: 'approve' }), + }); + expect(submitNudgeMock).not.toHaveBeenCalled(); + expect(lastEmit()[2]).toEqual({ type: 'thought', body: 'Approved. The agent continues with this action.' }); + }); + + test('a deny with a reason passes the reason on', async () => { + waiting(); + await handleAgentSessionEvent(prompted({ content: { body: 'deny use the staging config' } })); + expect(JSON.parse(recordDenialMock.mock.calls[0][0].body)).toEqual({ request_id: 'req-1', decision: 'deny', reason: 'use the staging config' }); + expect(String(lastEmit()[2].body)).toContain('your reason: use the staging config'); + }); + + test('a request that was already answered or timed out changes nothing, and says so', async () => { + waiting(); + recordApprovalMock.mockResolvedValue({ statusCode: 409 }); + await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); + expect(String(lastEmit()[2].body)).toContain('already answered or timed out'); + }); + + test('someone other than the owner gets the choice again, and nothing is decided', async () => { + waiting('someone-else'); + await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); + expect(recordApprovalMock).not.toHaveBeenCalled(); + const [, , content, options] = lastEmit(); + expect(content.type).toBe('elicitation'); + expect(String(content.body)).toMatch(/^Only the task owner can decide this request\./); + expect(options).toEqual(expect.objectContaining({ signal: 'select' })); + }); + + test('anything else keeps the request open: the choice comes back, nothing is nudged', async () => { + waiting(); + await handleAgentSessionEvent(prompted({ content: { body: 'what does this command do?' } })); + expect(recordApprovalMock).not.toHaveBeenCalled(); + expect(submitNudgeMock).not.toHaveBeenCalled(); + expect(lastEmit()[2].type).toBe('elicitation'); + }); + + test('a late Approve after the task finished starts nothing', async () => { + priorTask({ task_id: 't-1', status: 'COMPLETED', repo: 'acme/web', linear_workspace_id: 'org-1', session: 'session-1' }); + await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); + expect(createTaskCoreMock).not.toHaveBeenCalled(); + expect(lastEmit()[2]).toEqual(expect.objectContaining({ type: 'response', body: expect.stringContaining('Nothing is waiting for your approval') })); + }); + + test('an Approve while the task runs without a request is not passed to the agent', async () => { + priorTask({ task_id: 't-1', status: 'RUNNING', user_id: 'platform-user-1', linear_workspace_id: 'org-1', session: 'session-1' }); + await handleAgentSessionEvent(prompted({ content: { body: 'deny' } })); + expect(submitNudgeMock).not.toHaveBeenCalled(); + expect(lastEmit()[2]).toEqual(expect.objectContaining({ type: 'thought', body: expect.stringContaining('Nothing is waiting') })); + }); +}); diff --git a/cdk/test/handlers/shared/linear-feedback.test.ts b/cdk/test/handlers/shared/linear-feedback.test.ts index 50d668657..4e22e88d4 100644 --- a/cdk/test/handlers/shared/linear-feedback.test.ts +++ b/cdk/test/handlers/shared/linear-feedback.test.ts @@ -91,6 +91,13 @@ describe('linear-feedback', () => { expect(body.variables).toEqual({ issueId: ISSUE_ID, body: '❌ blocked' }); }); + test('a credential in the text is redacted before it leaves for Linear, the request token is not touched', async () => { + await postIssueComment(CTX, ISSUE_ID, 'Failed: push rejected for ghp_abcdefghijklmnopqrstuvwxyz0123456789AB'); + const [, init] = fetchMock.mock.calls[0]; + expect(JSON.parse(init.body as string).variables.body).toBe('Failed: push rejected for [REDACTED-GITHUB_TOKEN]'); + expect(init.headers).toMatchObject({ Authorization: `Bearer ${TOKEN}` }); + }); + test('terminal failure (not retryable) when the token cannot be resolved', async () => { resolveLinearOauthTokenMock.mockResolvedValueOnce(null); diff --git a/cdk/test/handlers/shared/linear-session-approval.test.ts b/cdk/test/handlers/shared/linear-session-approval.test.ts new file mode 100644 index 000000000..8d9057764 --- /dev/null +++ b/cdk/test/handlers/shared/linear-session-approval.test.ts @@ -0,0 +1,86 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import type { ApprovalNotification } from '../../../src/handlers/shared/approval-notifications'; +import { + formatDeadline, + repeatedApprovalChoice, + SESSION_APPROVAL_OPTIONS, + sessionApprovalActivity, + sessionDecisionNote, + waitingOnYouLine, +} from '../../../src/handlers/shared/linear-session-approval'; + +const NOW = new Date('2026-11-25T21:10:00Z'); +const notice = (deadline?: string): ApprovalNotification => ({ + title: 'Approval needed', + text: 'Approval needed\nThe agent wants to run a shell command.', + taskId: 't-1', + requestId: 'r-1', + userId: 'u-1', + marker: 'notified_linear_session_approval_requested', + ...(deadline && { deadline }), +}); + +test('a deadline reads as a clock time and how long is left, with the date when it is not today', () => { + expect(formatDeadline('2026-11-25T21:40:00Z', NOW)).toBe('21:40 UTC (in 30 min)'); + expect(formatDeadline('2026-11-26T09:40:00Z', NOW)).toBe('Thu 26 Nov, 09:40 UTC (in 13 h)'); + expect(formatDeadline('not a date', NOW)).toBeNull(); +}); + +test('the waiting line says what happens if nobody answers', () => { + expect(waitingOnYouLine('2026-11-25T21:40:00Z', NOW)) + .toBe('**Waiting on you.** Reply by 21:40 UTC (in 30 min), or it is denied and the agent carries on without it.'); + expect(waitingOnYouLine(undefined, NOW)).toBe('**Waiting on you.** The agent is paused until you answer.'); +}); + +test('a pending request is a choice with Approve / Deny buttons and the waiting line', () => { + const a = sessionApprovalActivity('approval_requested', notice('2026-11-25T21:40:00Z'), NOW); + expect(a.content.type).toBe('elicitation'); + expect(a.signal).toBe('select'); + expect(a.signalMetadata).toEqual({ options: SESSION_APPROVAL_OPTIONS }); + expect(SESSION_APPROVAL_OPTIONS.map((o) => o.value)).toEqual(['approve', 'deny']); + const body = (a.content as { body: string }).body; + expect(body).toContain('The agent wants to run a shell command.'); + expect(body.endsWith('Reply by 21:40 UTC (in 30 min), or it is denied and the agent carries on without it.')).toBe(true); +}); + +test('a decision, timeout or stranded wait is a note without buttons', () => { + for (const type of ['approval_decision_recorded', 'approval_timed_out', 'approval_stranded']) { + const a = sessionApprovalActivity(type, notice(), NOW); + expect(a.content.type).toBe('thought'); + expect(a.signal).toBeUndefined(); + } +}); + +test('the repeated choice keeps the buttons', () => { + const a = repeatedApprovalChoice('Only the task owner can decide this request.'); + expect(a.content).toEqual({ type: 'elicitation', body: expect.stringMatching(/^Only the task owner can decide this request\./) }); + expect(a.signal).toBe('select'); +}); + +test('the note after a decision says what happened', () => { + expect(sessionDecisionNote({ decision: 'approve' }, { statusCode: 202 })).toBe('Approved. The agent continues with this action.'); + expect(sessionDecisionNote({ decision: 'deny', reason: 'use staging' }, { statusCode: 202 })) + .toBe('Denied. The agent carries on without it (your reason: use staging).'); + expect(sessionDecisionNote({ decision: 'approve' }, { statusCode: 409 })).toContain('already answered or timed out'); + expect(sessionDecisionNote({ decision: 'approve' }, { statusCode: 404 })).toContain('already answered or timed out'); + expect(sessionDecisionNote({ decision: 'deny' }, { statusCode: 429 })).toContain('Too many'); + expect(sessionDecisionNote({ decision: 'deny' }, { statusCode: 500 })).toContain('bgagent approve'); +}); diff --git a/contracts/secret-scan-vectors.json b/contracts/secret-scan-vectors.json index a22129026..f916d7cd7 100644 --- a/contracts/secret-scan-vectors.json +++ b/contracts/secret-scan-vectors.json @@ -185,6 +185,11 @@ "input": "redis://:@localhost:6379/0", "expected": "redis://:@localhost:6379/0", "note": "an empty user and an empty password" + }, + { + "input": "Linear said: token lin_oauth_EXAMPLE0EXAMPLE0EX is invalid", + "expected": "Linear said: token [REDACTED-LINEAR_TOKEN] is invalid", + "note": "a Linear OAuth access token" } ] } diff --git a/docs/guides/LINEAR_SETUP_GUIDE.md b/docs/guides/LINEAR_SETUP_GUIDE.md index ed1d35243..68876cf59 100644 --- a/docs/guides/LINEAR_SETUP_GUIDE.md +++ b/docs/guides/LINEAR_SETUP_GUIDE.md @@ -251,8 +251,10 @@ If you do these the other way round, every mention in the meantime opens a sessi | — the agent opens a PR | Attaches the pull request to the session header and posts an **Opened pull request** action. | | — a long run is in progress | Posts a short-lived "Still working" thought at most every 10 minutes, so the session never goes stale (Linear's idle limit is 30 minutes). | | — the task finishes | Posts one final activity carrying the same outcome, cost, turns and duration as the comment channel: a *response* on success, an *elicitation* if the run stopped to ask you a question, an *error* on failure. Its last line says whether you need to do anything. Linear turns it into the thread comment. A task that ends with a pull request moves the issue to *In Review*. | +| — the agent hits an approval gate | Posts the request with **Approve** / **Deny** buttons and the time by which it is denied if nobody answers. Choose one, or reply `deny `. Only the task owner can decide; anyone else, or any other reply, gets the choice again. A decision made elsewhere (`bgagent approve`, a comment reply) or a timeout shows up as a note. | | — you're at your concurrency limit | Posts a "Queued" thought in the session, and "Still queued (N min so far)" every 15 minutes. The task starts on its own when a slot frees up. | | Reply inside the session while the task runs | Your message goes to the running agent as a nudge (the same guardrail screening, 2,000-character cap and per-minute limit as `bgagent nudge`). The agent picks it up at its next step. Only the task's owner can steer it. | +| Reply `approve` or `deny` when nothing is waiting | Says nothing is waiting and starts nothing, so a late answer after a timeout can't start new work. | | Reply after the task has finished | Starts a follow-up task. If the run stopped to ask a question, your reply resumes the original request with the answer. Otherwise it's a PR iteration if a PR exists, or new work from your message plus the issue. | | Click **Stop** in the session | Cancels the running task and shuts its agent down, like `bgagent cancel`, then confirms with a final response. Only the task's owner can stop it. | diff --git a/docs/src/content/docs/using/Linear-setup-guide.md b/docs/src/content/docs/using/Linear-setup-guide.md index 4eaa2b7bb..4c00bff5c 100644 --- a/docs/src/content/docs/using/Linear-setup-guide.md +++ b/docs/src/content/docs/using/Linear-setup-guide.md @@ -253,8 +253,10 @@ If you do these the other way round, every mention in the meantime opens a sessi | — the agent opens a PR | Attaches the pull request to the session header and posts an **Opened pull request** action. | | — a long run is in progress | Posts a short-lived "Still working" thought at most every 10 minutes, so the session never goes stale (Linear's idle limit is 30 minutes). | | — the task finishes | Posts one final activity carrying the same outcome, cost, turns and duration as the comment channel: a *response* on success, an *elicitation* if the run stopped to ask you a question, an *error* on failure. Its last line says whether you need to do anything. Linear turns it into the thread comment. A task that ends with a pull request moves the issue to *In Review*. | +| — the agent hits an approval gate | Posts the request with **Approve** / **Deny** buttons and the time by which it is denied if nobody answers. Choose one, or reply `deny `. Only the task owner can decide; anyone else, or any other reply, gets the choice again. A decision made elsewhere (`bgagent approve`, a comment reply) or a timeout shows up as a note. | | — you're at your concurrency limit | Posts a "Queued" thought in the session, and "Still queued (N min so far)" every 15 minutes. The task starts on its own when a slot frees up. | | Reply inside the session while the task runs | Your message goes to the running agent as a nudge (the same guardrail screening, 2,000-character cap and per-minute limit as `bgagent nudge`). The agent picks it up at its next step. Only the task's owner can steer it. | +| Reply `approve` or `deny` when nothing is waiting | Says nothing is waiting and starts nothing, so a late answer after a timeout can't start new work. | | Reply after the task has finished | Starts a follow-up task. If the run stopped to ask a question, your reply resumes the original request with the answer. Otherwise it's a PR iteration if a PR exists, or new work from your message plus the issue. | | Click **Stop** in the session | Cancels the running task and shuts its agent down, like `bgagent cancel`, then confirms with a final response. Only the task's owner can stop it. | From c81d4314dd6ce380323b59c9883dca4dd62bcbe6 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 15:28:00 +0000 Subject: [PATCH 14/27] feat(approvals): 30-minute approval window by default, settable per repo An approval request on a Linear task gave a person five minutes: the effective window is the minimum of the matching rules' @approval_timeout_s and the task's approval_timeout_s, and the task default was 300 s. Someone away from the session for a meeting missed it, and the request was denied. - contracts/constants.json: approval_timeout_s.default 300 -> 1800 (the CDK, CLI and agent read it; min 30 and max 3600 are unchanged) - the built-in soft-deny rules (force pushes, protected-branch pushes, .env and credentials files) allow 3600 s, so the task's window decides instead of the rule clipping it; a team's stricter rule still clips its own window - Blueprint security.approvalTimeoutSeconds (30..3600, validated at synth) sets a repo's default. It is resolved at submit time onto the TaskRecord, like approvalGateCap, so a blueprint edit never changes a running task's window; a request's own approval_timeout_s wins. An out-of-range value in a hand-edited row is logged and ignored rather than refusing the task. - a MicroVM waiting on a default gate now sleeps up to 1740 s instead of 240 s - docs: user guide, constants, Cedar design doc, compute design, submit --help --- agent/policies/soft_deny.cedar | 14 ++--- agent/tests/test_blueprint_cedar_routing.py | 2 +- agent/tests/test_policy_three_outcome.py | 9 ++-- cdk/src/constructs/blueprint.ts | 51 ++++++++++++++++++- cdk/src/handlers/shared/builtin-policies.ts | 14 ++--- cdk/src/handlers/shared/create-task-core.ts | 24 ++++++++- cdk/src/handlers/shared/repo-config.ts | 7 +++ cdk/test/constructs/blueprint.test.ts | 25 +++++++++ cdk/test/handlers/get-policies.test.ts | 2 +- .../reconcile-admission-queue.test.ts | 3 +- .../handlers/shared/create-task-core.test.ts | 25 +++++++++ .../handlers/shared/microvm/lifecycle.test.ts | 25 +++++---- cli/src/commands/submit.ts | 2 +- contracts/constants.json | 2 +- contracts/constants.md | 8 +-- docs/design/CEDAR_HITL_GATES.md | 15 +++--- docs/design/COMPUTE.md | 2 +- docs/guides/USER_GUIDE.md | 4 +- .../docs/architecture/Cedar-hitl-gates.md | 15 +++--- docs/src/content/docs/architecture/Compute.md | 2 +- .../docs/using/Approval-gates-cedar-hitl.md | 2 +- docs/src/content/docs/using/Using-the-cli.md | 2 +- 22 files changed, 200 insertions(+), 55 deletions(-) diff --git a/agent/policies/soft_deny.cedar b/agent/policies/soft_deny.cedar index 6bfd286e2..45ba9865b 100644 --- a/agent/policies/soft_deny.cedar +++ b/agent/policies/soft_deny.cedar @@ -24,7 +24,9 @@ permit (principal, action, resource); // `security.cedarPolicies.disable: [rule_id]`. They may NOT disable any // rule in hard_deny.cedar (blueprint loader rejects those at task start). -// Gate any git --force / -f push. 300s default approval window, medium severity. +// Gate any git --force / -f push. Medium severity. Each built-in rule allows the +// platform maximum (3600s), so the task's window decides (default 1800s, per repo +// via security.approvalTimeoutSeconds, per task via approval_timeout_s). // Covers both long-form (--force) and short-form (-f) variants, including // the bare `git push -f` invocation with no branch argument, and the flag // after the remote and branch (`git push origin feature --force`). After @@ -37,7 +39,7 @@ permit (principal, action, resource); // other option that begins with `-f`. @tier("soft") @rule_id("force_push_any") -@approval_timeout_s("300") +@approval_timeout_s("3600") @severity("medium") @category("destructive") forbid (principal, action == Agent::Action::"execute_bash", resource) @@ -61,7 +63,7 @@ when { context.command like "*git push --force*" // merging picks min(300, 600)=300s and max(medium, high)=high. @tier("soft") @rule_id("force_push_main") -@approval_timeout_s("600") +@approval_timeout_s("3600") @severity("high") @category("destructive") forbid (principal, action == Agent::Action::"execute_bash", resource) @@ -74,7 +76,7 @@ when { context.command like "*git push --force origin main*" // agent bypasses PR workflow by pushing directly. @tier("soft") @rule_id("push_to_protected_branch") -@approval_timeout_s("300") +@approval_timeout_s("3600") @severity("medium") @category("destructive") forbid (principal, action == Agent::Action::"execute_bash", resource) @@ -86,7 +88,7 @@ when { context.command like "*git push origin main*" // Writes to `.env` files typically contain secrets. 600s window, high severity. @tier("soft") @rule_id("write_env_files") -@approval_timeout_s("600") +@approval_timeout_s("3600") @severity("high") @category("filesystem") forbid (principal, action == Agent::Action::"write_file", resource) @@ -96,7 +98,7 @@ when { context.file_path like "*.env" }; // service-account JSON, etc. 300s window, high severity. @tier("soft") @rule_id("write_credentials") -@approval_timeout_s("300") +@approval_timeout_s("3600") @severity("high") @category("auth") forbid (principal, action == Agent::Action::"write_file", resource) diff --git a/agent/tests/test_blueprint_cedar_routing.py b/agent/tests/test_blueprint_cedar_routing.py index f63990007..f84c8fad5 100644 --- a/agent/tests/test_blueprint_cedar_routing.py +++ b/agent/tests/test_blueprint_cedar_routing.py @@ -61,7 +61,7 @@ def test_guide_hard_rule_matches_the_prod_directory(guide_policies, tool, path, assert "block_prod_writes" in decision.reason -@pytest.mark.parametrize(("task_timeout", "expected"), [(None, 300), (600, 600), (3600, 900)]) +@pytest.mark.parametrize(("task_timeout", "expected"), [(None, 900), (600, 600), (3600, 900)]) def test_guide_soft_rule_uses_shorter_approval_window(guide_policies, task_timeout, expected): engine = engine_for(guide_policies, timeout_s=task_timeout) decision = engine.evaluate_tool_use("Bash", {"command": "terraform apply"}) diff --git a/agent/tests/test_policy_three_outcome.py b/agent/tests/test_policy_three_outcome.py index 0b5d80cba..1b72bf63e 100644 --- a/agent/tests/test_policy_three_outcome.py +++ b/agent/tests/test_policy_three_outcome.py @@ -439,19 +439,20 @@ def test_soft_deny_force_push_returns_require_approval(self): d = engine.evaluate_tool_use("Bash", {"command": "git push --force origin feature"}) assert d.outcome == Outcome.REQUIRE_APPROVAL assert "force_push_any" in d.matching_rule_ids - assert d.timeout_s == 300 + # The rule allows 3600s; the task default (1800s) decides. + assert d.timeout_s == 1800 assert d.severity == "medium" def test_soft_deny_multi_match_merges_annotations(self): - # force_push_any (300s, medium) + force_push_main (600s, high) both - # match "git push --force origin main". Merge picks min(300, 600)=300s + # force_push_any (3600s, medium) + force_push_main (3600s, high) both + # match "git push --force origin main". Merge picks min(3600, 3600, 1800)=1800s # and max(medium, high)=high. §6.3. engine = PolicyEngine(task_type="new_task", repo="owner/repo") d = engine.evaluate_tool_use("Bash", {"command": "git push --force origin main"}) assert d.outcome == Outcome.REQUIRE_APPROVAL assert "force_push_any" in d.matching_rule_ids assert "force_push_main" in d.matching_rule_ids - assert d.timeout_s == 300 # min across rules + task default + assert d.timeout_s == 1800 # min across rules (3600) + task default (1800) assert d.severity == "high" # max across rules def test_default_allow_on_no_match(self): diff --git a/cdk/src/constructs/blueprint.ts b/cdk/src/constructs/blueprint.ts index bcc6f5dfc..c611fb043 100644 --- a/cdk/src/constructs/blueprint.ts +++ b/cdk/src/constructs/blueprint.ts @@ -46,6 +46,8 @@ const DOMAIN_PATTERN = /^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9 */ const APPROVAL_GATE_CAP_MIN = sharedConstants.approval_gate_cap.min; const APPROVAL_GATE_CAP_MAX = sharedConstants.approval_gate_cap.max; +const APPROVAL_TIMEOUT_S_MIN = sharedConstants.approval_timeout_s.min; +const APPROVAL_TIMEOUT_S_MAX = sharedConstants.approval_timeout_s.max; /** * Bounds on a per-repo cost budget (#748). Same JSON the task-submit path @@ -209,6 +211,18 @@ export interface BlueprintProps { * back to the platform default of 50 defined in the handler layer. */ readonly approvalGateCap?: number; + + /** + * How long, in seconds, a person has to answer an approval request on this + * repo's tasks before it is denied. Captured at task-submit time onto the + * TaskRecord; a task submitted with its own ``approval_timeout_s`` keeps + * that. A rule's own ``@approval_timeout_s`` still caps it for that rule. + * + * Must be an integer in the platform's ``approval_timeout_s`` range + * (``contracts/constants.json``: 30 to 3600). When omitted, the platform + * default applies. + */ + readonly approvalTimeoutSeconds?: number; }; /** @@ -277,6 +291,9 @@ export class Blueprint extends Construct { */ public readonly approvalGateCap?: number; + /** Default approval window in seconds from security.approvalTimeoutSeconds, if set. */ + public readonly approvalTimeoutSeconds?: number; + /** * Per-repo cost budget in USD from the agent.maxBudgetUsd prop (#748), * exposed for inspection. Undefined when the blueprint did not configure @@ -306,7 +323,7 @@ export class Blueprint extends Construct { this.egressAllowlist = [...(props.networking?.egressAllowlist ?? [])]; this.cedarPolicies = [...(props.security?.cedarPolicies ?? [])]; - this.approvalGateCap = props.security?.approvalGateCap; + ({ approvalGateCap: this.approvalGateCap, approvalTimeoutSeconds: this.approvalTimeoutSeconds } = approvalSettings(props)); const { maxBudgetUsd, memoryTokenBudget } = props.agent ?? {}; this.maxBudgetUsd = maxBudgetUsd; this.memoryTokenBudget = memoryTokenBudget; @@ -331,6 +348,7 @@ export class Blueprint extends Construct { this.node.addValidation(new RepoFormatValidation(props.repo)); this.node.addValidation(new DomainFormatValidation(this.egressAllowlist)); this.node.addValidation(new ApprovalGateCapValidation(this.approvalGateCap)); + this.node.addValidation(new ApprovalTimeoutValidation(this.approvalTimeoutSeconds)); this.node.addValidation(new MaxBudgetUsdValidation(this.maxBudgetUsd)); this.node.addValidation(new MemoryTokenBudgetValidation(this.memoryTokenBudget)); this.node.addValidation(new RegistryRefValidation('assets.mcpServers', this.mcpServerRefs, 'mcp_server')); @@ -396,6 +414,9 @@ export class Blueprint extends Construct { if (this.approvalGateCap !== undefined) { item.approval_gate_cap = { N: String(this.approvalGateCap) }; } + if (this.approvalTimeoutSeconds !== undefined) { + item.approval_timeout_s = { N: String(this.approvalTimeoutSeconds) }; + } if (this.mcpServerRefs.length > 0) { item.mcp_servers = { L: this.mcpServerRefs.map(r => ({ S: r })) }; } @@ -482,6 +503,7 @@ export class Blueprint extends Construct { if (this.egressAllowlist.length > 0) fields.push(', #egress_allowlist = :egress_allowlist'); if (this.cedarPolicies.length > 0) fields.push(', #cedar_policies = :cedar_policies'); if (this.approvalGateCap !== undefined) fields.push(', #approval_gate_cap = :approval_gate_cap'); + if (this.approvalTimeoutSeconds !== undefined) fields.push(', #approval_timeout_s = :approval_timeout_s'); // Registry asset refs (#246) — must mirror onCreate's item, else a redeploy // of an already-onboarded repo silently drops asset-ref changes. if (this.mcpServerRefs.length > 0) fields.push(', #mcp_servers = :mcp_servers'); @@ -506,6 +528,7 @@ export class Blueprint extends Construct { if (this.egressAllowlist.length > 0) names['#egress_allowlist'] = 'egress_allowlist'; if (this.cedarPolicies.length > 0) names['#cedar_policies'] = 'cedar_policies'; if (this.approvalGateCap !== undefined) names['#approval_gate_cap'] = 'approval_gate_cap'; + if (this.approvalTimeoutSeconds !== undefined) names['#approval_timeout_s'] = 'approval_timeout_s'; if (this.mcpServerRefs.length > 0) names['#mcp_servers'] = 'mcp_servers'; if (this.cedarPolicyModuleRefs.length > 0) names['#cedar_policy_modules'] = 'cedar_policy_modules'; if (this.skillRefs.length > 0) names['#skills'] = 'skills'; @@ -528,6 +551,7 @@ export class Blueprint extends Construct { if (this.egressAllowlist.length > 0) values[':egress_allowlist'] = { L: this.egressAllowlist.map(d => ({ S: d })) }; if (this.cedarPolicies.length > 0) values[':cedar_policies'] = { L: this.cedarPolicies.map(p => ({ S: p })) }; if (this.approvalGateCap !== undefined) values[':approval_gate_cap'] = { N: String(this.approvalGateCap) }; + if (this.approvalTimeoutSeconds !== undefined) values[':approval_timeout_s'] = { N: String(this.approvalTimeoutSeconds) }; if (this.mcpServerRefs.length > 0) values[':mcp_servers'] = { L: this.mcpServerRefs.map(r => ({ S: r })) }; if (this.cedarPolicyModuleRefs.length > 0) values[':cedar_policy_modules'] = { L: this.cedarPolicyModuleRefs.map(r => ({ S: r })) }; if (this.skillRefs.length > 0) values[':skills'] = { L: this.skillRefs.map(r => ({ S: r })) }; @@ -617,6 +641,31 @@ class ApprovalGateCapValidation implements IValidation { } } +/** The blueprint's approval settings (read here to keep the constructor under the complexity ceiling). */ +function approvalSettings(props: BlueprintProps): { approvalGateCap?: number; approvalTimeoutSeconds?: number } { + const security = props.security ?? {}; + return { approvalGateCap: security.approvalGateCap, approvalTimeoutSeconds: security.approvalTimeoutSeconds }; +} + +/** Validates ``security.approvalTimeoutSeconds`` against the platform's ``approval_timeout_s`` range. */ +class ApprovalTimeoutValidation implements IValidation { + constructor(private readonly seconds: number | undefined) {} + + public validate(): string[] { + if (this.seconds === undefined) return []; + if (!Number.isInteger(this.seconds)) { + return [`Invalid security.approvalTimeoutSeconds: ${this.seconds}. Must be an integer.`]; + } + if (this.seconds < APPROVAL_TIMEOUT_S_MIN || this.seconds > APPROVAL_TIMEOUT_S_MAX) { + return [ + `Invalid security.approvalTimeoutSeconds: ${this.seconds}. ` + + `Must be between ${APPROVAL_TIMEOUT_S_MIN} and ${APPROVAL_TIMEOUT_S_MAX}.`, + ]; + } + return []; + } +} + /** * #748 — validates the per-repo cost budget is a finite number inside * ``[MAX_BUDGET_USD_MIN, MAX_BUDGET_USD_MAX]``. Bounds come from diff --git a/cdk/src/handlers/shared/builtin-policies.ts b/cdk/src/handlers/shared/builtin-policies.ts index 0418f482c..cd019395c 100644 --- a/cdk/src/handlers/shared/builtin-policies.ts +++ b/cdk/src/handlers/shared/builtin-policies.ts @@ -135,7 +135,9 @@ permit (principal, action, resource); // \`security.cedarPolicies.disable: [rule_id]\`. They may NOT disable any // rule in hard_deny.cedar (blueprint loader rejects those at task start). -// Gate any git --force / -f push. 300s default approval window, medium severity. +// Gate any git --force / -f push. Medium severity. Each built-in rule allows the +// platform maximum (3600s), so the task's window decides (default 1800s, per repo +// via security.approvalTimeoutSeconds, per task via approval_timeout_s). // Covers both long-form (--force) and short-form (-f) variants, including // the bare \`git push -f\` invocation with no branch argument, and the flag // after the remote and branch (\`git push origin feature --force\`). After @@ -148,7 +150,7 @@ permit (principal, action, resource); // other option that begins with \`-f\`. @tier("soft") @rule_id("force_push_any") -@approval_timeout_s("300") +@approval_timeout_s("3600") @severity("medium") @category("destructive") forbid (principal, action == Agent::Action::"execute_bash", resource) @@ -172,7 +174,7 @@ when { context.command like "*git push --force*" // merging picks min(300, 600)=300s and max(medium, high)=high. @tier("soft") @rule_id("force_push_main") -@approval_timeout_s("600") +@approval_timeout_s("3600") @severity("high") @category("destructive") forbid (principal, action == Agent::Action::"execute_bash", resource) @@ -185,7 +187,7 @@ when { context.command like "*git push --force origin main*" // agent bypasses PR workflow by pushing directly. @tier("soft") @rule_id("push_to_protected_branch") -@approval_timeout_s("300") +@approval_timeout_s("3600") @severity("medium") @category("destructive") forbid (principal, action == Agent::Action::"execute_bash", resource) @@ -197,7 +199,7 @@ when { context.command like "*git push origin main*" // Writes to \`.env\` files typically contain secrets. 600s window, high severity. @tier("soft") @rule_id("write_env_files") -@approval_timeout_s("600") +@approval_timeout_s("3600") @severity("high") @category("filesystem") forbid (principal, action == Agent::Action::"write_file", resource) @@ -207,7 +209,7 @@ when { context.file_path like "*.env" }; // service-account JSON, etc. 300s window, high severity. @tier("soft") @rule_id("write_credentials") -@approval_timeout_s("300") +@approval_timeout_s("3600") @severity("high") @category("auth") forbid (principal, action == Agent::Action::"write_file", resource) diff --git a/cdk/src/handlers/shared/create-task-core.ts b/cdk/src/handlers/shared/create-task-core.ts index 3bd419e0b..e3c932ce5 100644 --- a/cdk/src/handlers/shared/create-task-core.ts +++ b/cdk/src/handlers/shared/create-task-core.ts @@ -200,11 +200,14 @@ export async function createTaskCore( // in the "Task created" log. A repo-less submission has no blueprint, so it // stays false. let capFromBlueprint = false; + // The blueprint's approval window, the default for this task unless the request sets its own. + let blueprintApprovalTimeoutS: number | undefined; if (body.repo) { const { onboarded, config: repoConfig } = await lookupRepo(body.repo); if (!onboarded) { return errorResponse(422, ErrorCode.REPO_NOT_ONBOARDED, `Repository '${body.repo}' is not onboarded. Register it with a Blueprint before submitting tasks.`, requestId); } + blueprintApprovalTimeoutS = blueprintApprovalTimeout(repoConfig, body.repo, requestId); const blueprintCap = repoConfig?.approval_gate_cap; if (blueprintCap !== undefined) { if (typeof blueprintCap !== 'number' || !Number.isInteger(blueprintCap)) { @@ -331,7 +334,7 @@ export async function createTaskCore( // maxLifetime-based ceiling clip is applied at orchestrator // invocation time; at submit time we only enforce the `[floor, cap]` // envelope. - let approvalTimeoutS: number | undefined; + let approvalTimeoutS: number | undefined = blueprintApprovalTimeoutS; if (body.approval_timeout_s !== undefined) { if (typeof body.approval_timeout_s !== 'number' || !Number.isInteger(body.approval_timeout_s)) { @@ -950,6 +953,25 @@ export async function createTaskCore( * @param entry - the entry as the request body holds it. * @returns the parsed scope, or the message of the 400 that refuses the entry. */ +/** + * The blueprint's ``approval_timeout_s``, or undefined when it has none. A value out + * of the ``[min, max]`` envelope (a hand-edited row; the construct validates at + * synth) is logged and ignored, so the task gets the platform default rather than + * being refused: a wrong waiting time is not a reason to stop work. + */ +function blueprintApprovalTimeout( + config: { readonly approval_timeout_s?: unknown } | null, repo: string, requestId: string, +): number | undefined { + const value = config?.approval_timeout_s; + if (value === undefined) return undefined; + if (typeof value === 'number' && Number.isInteger(value) + && value >= APPROVAL_TIMEOUT_S_MIN && value <= APPROVAL_TIMEOUT_S_MAX) return value; + logger.error('Blueprint misconfiguration — approval_timeout_s ignored', { + repo, blueprint_approval_timeout_s: value, min: APPROVAL_TIMEOUT_S_MIN, max: APPROVAL_TIMEOUT_S_MAX, request_id: requestId, + }); + return undefined; +} + function checkInitialApproval(entry: unknown): { ok: true; scope: string } | { ok: false; message: string } { const parseResult = parseApprovalScope(String(entry)); if (!parseResult.ok) { diff --git a/cdk/src/handlers/shared/repo-config.ts b/cdk/src/handlers/shared/repo-config.ts index 57a123b4d..5374aecf3 100644 --- a/cdk/src/handlers/shared/repo-config.ts +++ b/cdk/src/handlers/shared/repo-config.ts @@ -67,6 +67,13 @@ export interface RepoConfig { * path falls back to the platform default of 50. */ readonly approval_gate_cap?: number; + /** + * Cedar HITL: per-blueprint default approval window in seconds, written by the + * Blueprint construct from ``security.approvalTimeoutSeconds``. Resolved at + * submit time onto the TaskRecord's ``approval_timeout_s`` (a request's own + * value wins). Absent: the platform default from ``contracts/constants.json``. + */ + readonly approval_timeout_s?: number; /** * Registry (#246) ``registry://`` refs for MCP servers pinned by the * blueprint. Resolved by the orchestrator at task start and merged into the diff --git a/cdk/test/constructs/blueprint.test.ts b/cdk/test/constructs/blueprint.test.ts index 6a7e607ee..fdff87bd3 100644 --- a/cdk/test/constructs/blueprint.test.ts +++ b/cdk/test/constructs/blueprint.test.ts @@ -563,6 +563,31 @@ describe('Blueprint construct', () => { ); }); + // --- security.approvalTimeoutSeconds (#1066) ----------------------------- + + test('persists approval_timeout_s on create and update when approvalTimeoutSeconds is set', () => { + const { template } = createStack({ security: { approvalTimeoutSeconds: 2700 } }); + expect(getCreateJoinParts(template).join('')).toContain('"approval_timeout_s":{"N":"2700"}'); + const update = getUpdateJoinParts(template).join(''); + expect(update).toContain('#approval_timeout_s'); + expect(update).toContain('"N":"2700"'); + }); + + test('omits approval_timeout_s when approvalTimeoutSeconds is unset', () => { + const { template } = createStack({ security: { approvalGateCap: 10 } }); + expect(getCreateJoinParts(template).join('')).not.toContain('approval_timeout_s'); + }); + + test.each([10, 3601, 90.5])('rejects approvalTimeoutSeconds %p at synth', (seconds) => { + const app = new App(); + const stack = new Stack(app, 'TestStack'); + const repoTable = new dynamodb.Table(stack, 'RepoTable', { + partitionKey: { name: 'repo', type: dynamodb.AttributeType.STRING }, + }); + new Blueprint(stack, 'Blueprint', { repo: 'org/my-repo', repoTable, security: { approvalTimeoutSeconds: seconds } }); + expect(() => Template.fromStack(stack)).toThrow(/Invalid security.approvalTimeoutSeconds/); + }); + // --- Chunk 7b: security.approvalGateCap --------------------------------- test('exposes approvalGateCap as public property when configured', () => { diff --git a/cdk/test/handlers/get-policies.test.ts b/cdk/test/handlers/get-policies.test.ts index 2d9dd59f3..f9fa7186b 100644 --- a/cdk/test/handlers/get-policies.test.ts +++ b/cdk/test/handlers/get-policies.test.ts @@ -355,6 +355,6 @@ describe('get-policies', () => { (r: { rule_id: string }) => r.rule_id === 'force_push_any', ); expect(soft.severity).toBe('medium'); - expect(soft.approval_timeout_s).toBe(300); + expect(soft.approval_timeout_s).toBe(3600); }); }); diff --git a/cdk/test/handlers/reconcile-admission-queue.test.ts b/cdk/test/handlers/reconcile-admission-queue.test.ts index 597c84997..60342286c 100644 --- a/cdk/test/handlers/reconcile-admission-queue.test.ts +++ b/cdk/test/handlers/reconcile-admission-queue.test.ts @@ -512,7 +512,8 @@ describe('reconcile-admission-queue — queue heartbeat (#1066)', () => { expect(puts[0].task_id).toEqual({ S: 'LONG' }); expect(puts[0].event_type).toEqual({ S: 'admission_queued' }); expect(puts[0].metadata.M.reason).toEqual({ S: 'concurrency_limit' }); - expect(Number(puts[0].metadata.M.waited_s.N)).toBeGreaterThanOrEqual(920); + // Past the 15-minute mark; the exact second depends on how long the test took to reach the handler. + expect(Number(puts[0].metadata.M.waited_s.N)).toBeGreaterThanOrEqual(900); expect(mockLambdaSend).not.toHaveBeenCalled(); }); diff --git a/cdk/test/handlers/shared/create-task-core.test.ts b/cdk/test/handlers/shared/create-task-core.test.ts index 4b7ec6e1b..684892ec4 100644 --- a/cdk/test/handlers/shared/create-task-core.test.ts +++ b/cdk/test/handlers/shared/create-task-core.test.ts @@ -1178,6 +1178,31 @@ describe('createTaskCore', () => { expect(record.approval_gate_cap).toBe(50); }); + // --- approval window: request > blueprint > platform default (#1066) --- + + test('the blueprint\'s approval window becomes the task\'s when the request sets none', async () => { + mockOnboardedWithConfig({ approval_timeout_s: 2700 }); + const result = await createTaskCore({ repo: 'org/repo', task_description: 'x' }, makeContext(), 'req-ats-repo'); + expect(result.statusCode).toBe(201); + expect(getPersistedTaskRecord().approval_timeout_s).toBe(2700); + }); + + test('a request\'s own approval window wins over the blueprint\'s', async () => { + mockOnboardedWithConfig({ approval_timeout_s: 2700 }); + const result = await createTaskCore( + { repo: 'org/repo', task_description: 'x', approval_timeout_s: 120 }, makeContext(), 'req-ats-body', + ); + expect(result.statusCode).toBe(201); + expect(getPersistedTaskRecord().approval_timeout_s).toBe(120); + }); + + test.each([5, 7200, 90.5, '1800'])('a blueprint window of %p is ignored, not a reason to refuse the task', async (bad) => { + mockOnboardedWithConfig({ approval_timeout_s: bad }); + const result = await createTaskCore({ repo: 'org/repo', task_description: 'x' }, makeContext(), 'req-ats-bad'); + expect(result.statusCode).toBe(201); + expect(getPersistedTaskRecord().approval_timeout_s).toBeUndefined(); + }); + test('persists blueprint-configured approval_gate_cap when within bounds', async () => { mockOnboardedWithConfig({ approval_gate_cap: 150 }); const result = await createTaskCore( diff --git a/cdk/test/handlers/shared/microvm/lifecycle.test.ts b/cdk/test/handlers/shared/microvm/lifecycle.test.ts index 7cf55cc3c..be1e67fde 100644 --- a/cdk/test/handlers/shared/microvm/lifecycle.test.ts +++ b/cdk/test/handlers/shared/microvm/lifecycle.test.ts @@ -100,28 +100,31 @@ describe('MicroVM lifecycle policy', () => { deadlineMs: NOW + sharedConstants.approval_timeout_s.default * 1000, }, }); - test('default timing: a 300 s gate sleeps after 60 s and wakes 60 s before its deadline', () => { - expect(sharedConstants.approval_timeout_s.default).toBe(300); + test('default timing: a default gate sleeps after 60 s and wakes 60 s before its deadline', () => { + expect(sharedConstants.approval_timeout_s.default).toBe(1800); expect(sharedConstants.microvm_sleep_after_s.default).toBe(60); + const gateMs = sharedConstants.approval_timeout_s.default * 1000; const current = defaultGate(); expect(policy('RUNNING', { snapshot: current, nowMs: NOW + 59_000 })) .toMatchObject({ action: 'wait', reason: 'suspend-grace', nextPollInMs: 1000 }); expect(policy('RUNNING', { snapshot: current, nowMs: NOW + 60_000 })).toMatchObject({ action: 'suspend' }); // Once the suspend intent for this gate is recorded, it stays asleep until the - // wake margin before the ORIGINAL deadline (300 - 60 = 240 s). - const asleep = { ...current, intent: { ...intent(), deadline_ms: NOW + 300_000 } }; - expect(policy('SUSPENDED', { snapshot: asleep, nowMs: NOW + 239_000 })) + // wake margin before the ORIGINAL deadline (1800 - 60 = 1740 s). + const asleep = { ...current, intent: { ...intent(), deadline_ms: NOW + gateMs } }; + expect(policy('SUSPENDED', { snapshot: asleep, nowMs: NOW + gateMs - 61_000 })) .toMatchObject({ action: 'wait', reason: 'intentionally-suspended', nextPollInMs: 1000 }); - expect(policy('SUSPENDED', { snapshot: asleep, nowMs: NOW + 240_000 })) + expect(policy('SUSPENDED', { snapshot: asleep, nowMs: NOW + gateMs - 60_000 })) .toMatchObject({ action: 'resume', reason: 'wake-deadline' }); - expect(current.approval).toMatchObject({ deadlineMs: NOW + 300_000 }); + expect(current.approval).toMatchObject({ deadlineMs: NOW + gateMs }); }); - test('a 600 s sleep-after never suspends a default 300 s gate', () => { - const current = { ...defaultGate(), sleepAfterSeconds: 600 }; - for (const elapsed of [60_000, 200_000, 239_000]) { + + test('a sleep-after as long as the gate never suspends it', () => { + const gateS = sharedConstants.approval_timeout_s.default; + const current = { ...defaultGate(), sleepAfterSeconds: gateS }; + for (const elapsed of [60_000, (gateS / 2) * 1000, gateS * 1000 - 61_000]) { expect(policy('RUNNING', { snapshot: current, nowMs: NOW + elapsed })).toMatchObject({ action: 'wait' }); } - expect(policy('RUNNING', { snapshot: current, nowMs: NOW + 240_000 })) + expect(policy('RUNNING', { snapshot: current, nowMs: NOW + gateS * 1000 - 60_000 })) .toMatchObject({ action: 'resume', reason: 'wake-deadline' }); }); test.each([0, -1, NaN, Infinity, 0.5, 3601, '30', null])('off or malformed delay %s keeps awake and repairs existing sleep', value => { diff --git a/cli/src/commands/submit.ts b/cli/src/commands/submit.ts index 78d406741..5cefddd69 100644 --- a/cli/src/commands/submit.ts +++ b/cli/src/commands/submit.ts @@ -88,7 +88,7 @@ export function makeSubmitCommand(): Command { .option( '--approval-timeout ', `Cedar HITL per-task default approval timeout (${APPROVAL_TIMEOUT_S_MIN}-${APPROVAL_TIMEOUT_S_MAX}s). ` - + 'Overrides the platform default of 300s. Per-rule @approval_timeout_s still min-wins at gate-firing.', + + 'Overrides the platform default of 1800s and the repo blueprint\'s. Per-rule @approval_timeout_s still min-wins at gate-firing.', parseInt, ) .option( diff --git a/contracts/constants.json b/contracts/constants.json index 5ebd494ff..e9f0aa1c2 100644 --- a/contracts/constants.json +++ b/contracts/constants.json @@ -7,7 +7,7 @@ "approval_timeout_s": { "min": 30, "max": 3600, - "default": 300 + "default": 1800 }, "microvm_sleep_after_s": { "min": 0, diff --git a/contracts/constants.md b/contracts/constants.md index 8ec8e0c78..9c7f8e479 100644 --- a/contracts/constants.md +++ b/contracts/constants.md @@ -104,7 +104,9 @@ JSON at TypeScript compile time via `resolveJsonModule`. before the `maxLifetime - 300` clip is applied (§7.3). 3600 seconds (1 hour). - **`approval_timeout_s.default`** — value applied when the submit payload - omits `approval_timeout_s`. 300 seconds (5 minutes) per §6 decision #6. + omits `approval_timeout_s` and the repo's blueprint sets no + `security.approvalTimeoutSeconds`. 1800 seconds (30 minutes): long enough for + someone away from the session to answer. Was 300 s (§6 decision #6). - **`max_budget_usd.min`** — floor for a task's `max_budget_usd` (1 cent). Validated server-side (`validation.ts`) and pre-validated by `bgagent submit --max-budget` (#258). @@ -198,9 +200,9 @@ fails the drift check *and* the image build. The coordinator suspends only images whose launched version declares this protocol. - **`microvm_sleep_after_s`** — per-task approval-wait delay before MicroVM sleep (`min` 0 = off, `max` 3,600, `default` 60). The default is chosen against - `approval_timeout_s.default` (300 s): the supervisor wakes 60 s before the + `approval_timeout_s.default` (1800 s): the supervisor wakes 60 s before the deadline and never suspends for less than 30 s, so a default gate sleeps from - 60 s to 240 s. + 60 s to 1740 s. The published CLI package contains only `lib/`, so it cannot load the repository contract at runtime. It mirrors these values as literals and diff --git a/docs/design/CEDAR_HITL_GATES.md b/docs/design/CEDAR_HITL_GATES.md index 7c75fbe5d..2483d3920 100644 --- a/docs/design/CEDAR_HITL_GATES.md +++ b/docs/design/CEDAR_HITL_GATES.md @@ -388,6 +388,7 @@ security: - write_infrastructure # example: repo has its own stricter rule maxPreApprovalScope: "tool_type_session" # optional; caps what --pre-approve can grant approvalGateCap: 50 # optional; per-task lifetime cap on gates (1 ≤ N ≤ 500, default 50). See §3 decision #13. + approvalTimeoutSeconds: 1800 # optional; how long a person has to answer a request on this repo's tasks (30 ≤ N ≤ 3600, default 1800). A task's own approval_timeout_s wins. ``` **`approvalGateCap` sizing guidance:** @@ -482,7 +483,7 @@ forbid (principal, action == Agent::Action::"execute_bash", resource) || context.command like "*git push origin release/*" }; ``` -A force-push to any branch needs approval in 300s. A force-push to `main` or `prod` gives the user 600s with elevated severity. A non-force push to a protected branch (`main`/`prod`/`master`/`release/*`) also gates — catches the case where an agent directly pushes rather than opening a PR. If a command matches both `force_push_any` and `force_push_main`, multi-match merging picks `min(300, 600) = 300s` and `max(medium, high) = high`. +A force-push to any branch needs approval within the task's approval window (30 minutes by default). A force-push to `main` or `prod` raises the severity. A non-force push to a protected branch (`main`/`prod`/`master`/`release/*`) also gates — catches the case where an agent directly pushes rather than opening a PR. If a command matches both `force_push_any` and `force_push_main`, multi-match merging picks `min(300, 600) = 300s` and `max(medium, high) = high`. **Protect sensitive file paths** (soft-deny — part of the built-in starter set): ```cedar @@ -2231,11 +2232,13 @@ Built-in policies shipped with the agent: **Hard-deny (absolute, cannot be disabled by blueprint)**: `rm_slash`, `write_git_internals`, `write_git_internals_nested`, `drop_table`. Absolute; no scope bypasses them; blueprint `disable:` cannot remove them (§5.1, finding #9). **Soft-deny starter set (require approval by default, may be disabled by blueprint)**: -- `force_push_any` — `like "*git push --force*"` — medium, 300s -- `push_to_protected_branch` — pushes to `main`/`master`/`prod`/`release/*` (non-force) — medium, 300s -- `force_push_main` — force-push specifically to `main`/`prod` — high, 600s -- `write_env_files` — `like "*.env"` — high, 600s -- `write_credentials` — `like "*credentials*"` — high, 300s +- `force_push_any` — `like "*git push --force*"` — medium, 3600s +- `push_to_protected_branch` — pushes to `main`/`master`/`prod`/`release/*` (non-force) — medium, 3600s +- `force_push_main` — force-push specifically to `main`/`prod` — high, 3600s +- `write_env_files` — `like "*.env"` — high, 3600s +- `write_credentials` — `like "*credentials*"` — high, 3600s + +Each built-in rule allows the 3600s maximum, so the task's window decides: 1800s by default, set per repo with the blueprint's `security.approvalTimeoutSeconds` or per task with `approval_timeout_s`. (Before #1066 the rules were 300s / 600s and the default 300s, which gave a person five minutes.) Users who want fully autonomous execution (no approval gates) pass `--pre-approve all_session --yes` at submit. Repos that want additional gates add them via `Blueprint.security.cedarPolicies.soft`. Repos that want a different policy set can override specific built-in **soft-deny** rules by `@rule_id` via the blueprint's `security.cedarPolicies.disable` list. The `disable:` mechanism is restricted: it may NOT include any built-in hard-deny rule_id, and the blueprint loader rejects such configurations at task start. diff --git a/docs/design/COMPUTE.md b/docs/design/COMPUTE.md index 79a8c6797..0eba180e0 100644 --- a/docs/design/COMPUTE.md +++ b/docs/design/COMPUTE.md @@ -121,7 +121,7 @@ Because a snapshot freezes its build-time environment, deployment-specific, non- Networking separates image build from execution: the build-only connector permits TCP 80 and 443 because the Dockerfile uses `apt-get`, while running MicroVMs retain 443-only egress through the platform VPC. Every launch explicitly passes the Lambda-managed `NO_INGRESS` connector; omission would select the service's public-ingress default. The P2 image declares and serves `/ready` and `/validate` at build time and `/run` and `/terminate` at runtime. The P3 image also serves `/suspend` and `/resume`. -**Approval-wait sleep (P3).** While a task waits for a human decision, the orchestrator can suspend its MicroVM: compute billing stops and memory and disk are preserved. It suspends only when the deployment enables `microvm_approval_suspend_enabled`, the live Parameter Store switch is on, the launched image version declares the lifecycle protocol, and enough of the gate remains after the task's `microvm_sleep_after_s` delay (default 60 s). It resumes inline when the decision is recorded, with the orchestrator poll as a backstop, and always 60 s before the original deadline. Approval windows stay bounded (300 s default, 3,600 s ceiling), so a suspended worker never outlives its gate. The guest declines an unsafe suspend with HTTP 200 because any other answer makes the service terminate the VM. See [ADR-021 P3 as delivered](../decisions/ADR-021-lambda-microvms-compute-backend.md#p3-as-delivered). +**Approval-wait sleep (P3).** While a task waits for a human decision, the orchestrator can suspend its MicroVM: compute billing stops and memory and disk are preserved. It suspends only when the deployment enables `microvm_approval_suspend_enabled`, the live Parameter Store switch is on, the launched image version declares the lifecycle protocol, and enough of the gate remains after the task's `microvm_sleep_after_s` delay (default 60 s). It resumes inline when the decision is recorded, with the orchestrator poll as a backstop, and always 60 s before the original deadline. Approval windows stay bounded (1,800 s default, 3,600 s ceiling), so a suspended worker never outlives its gate. The guest declines an unsafe suspend with HTTP 200 because any other answer makes the service terminate the VM. See [ADR-021 P3 as delivered](../decisions/ADR-021-lambda-microvms-compute-backend.md#p3-as-delivered). New MicroVM deployments place these resources in a nested stack (`--context microvm_nested_stack=true`, bootstrap 1.9.0 or later); existing flat installations keep `false` until migrated. diff --git a/docs/guides/USER_GUIDE.md b/docs/guides/USER_GUIDE.md index 678168d05..77c77c3d1 100644 --- a/docs/guides/USER_GUIDE.md +++ b/docs/guides/USER_GUIDE.md @@ -668,7 +668,7 @@ Created: 2026-04-01T00:39:51.271Z | `--max-budget` | Maximum cost budget in USD (0.01–100). Overrides per-repo Blueprint default. No default limit. | | `--idempotency-key` | Idempotency key for deduplication. | | `--trace` | Enable detailed tracing: raises progress preview cap to 4 KB and uploads full NDJSON trajectory to S3 on completion. Download with `bgagent trace download`. | -| `--approval-timeout` | Cedar HITL per-task approval timeout in seconds (default 300). A matching rule with its own `@approval_timeout_s` annotation still takes the minimum. See [Approval gates](#approval-gates-cedar-hitl). | +| `--approval-timeout` | Cedar HITL per-task approval timeout in seconds (default 1800, or the repo blueprint's `security.approvalTimeoutSeconds`). A matching rule with its own `@approval_timeout_s` annotation still takes the minimum. See [Approval gates](#approval-gates-cedar-hitl). | | `--microvm-sleep-after` | Seconds to wait for approval before putting a Lambda MicroVM to sleep (default 60; 0–3600 accepted). Use `off` to keep it awake. Requires the deployment's automatic-sleep feature to be enabled; does not change approval deadlines or affect other compute backends. | | `--pre-approve` | Cedar HITL scope to approve up-front (repeatable). Scope forms: `all_session`, `tool_type:`, `tool_group:`, `bash_pattern:`, `write_path:`, `rule:`. Hard-deny rules are always enforced. | | `--wait` | Poll until the task reaches a terminal status. | @@ -905,7 +905,7 @@ When a rule marked `@tier("soft")` matches a tool call: 1. The agent stops before invoking the tool. 2. A row is atomically written to the approvals table and the task status flips to `AWAITING_APPROVAL`. 3. A progress event (`approval_requested`) is emitted so `bgagent watch` shows the gate in real time. -4. The task waits for your decision up to the rule's timeout (default 300 s, configurable per-rule and per-task). +4. The task waits for your decision up to the approval window (default 30 minutes; configurable per repo with the blueprint's `security.approvalTimeoutSeconds`, per task, and per rule, up to 1 hour). 5. On approval, the agent proceeds; on denial, the deny reason is best-effort injected back into the agent's context so it can adapt; on timeout, the gate is treated as a denial with `timed_out` as the reason. A decision is recorded at most once per request. Replaying approve/deny on the same `(task_id, request_id)` is idempotent. diff --git a/docs/src/content/docs/architecture/Cedar-hitl-gates.md b/docs/src/content/docs/architecture/Cedar-hitl-gates.md index be074348d..4133f6223 100644 --- a/docs/src/content/docs/architecture/Cedar-hitl-gates.md +++ b/docs/src/content/docs/architecture/Cedar-hitl-gates.md @@ -390,6 +390,7 @@ security: - write_infrastructure # example: repo has its own stricter rule maxPreApprovalScope: "tool_type_session" # optional; caps what --pre-approve can grant approvalGateCap: 50 # optional; per-task lifetime cap on gates (1 ≤ N ≤ 500, default 50). See §3 decision #13. + approvalTimeoutSeconds: 1800 # optional; how long a person has to answer a request on this repo's tasks (30 ≤ N ≤ 3600, default 1800). A task's own approval_timeout_s wins. ``` **`approvalGateCap` sizing guidance:** @@ -484,7 +485,7 @@ forbid (principal, action == Agent::Action::"execute_bash", resource) || context.command like "*git push origin release/*" }; ``` -A force-push to any branch needs approval in 300s. A force-push to `main` or `prod` gives the user 600s with elevated severity. A non-force push to a protected branch (`main`/`prod`/`master`/`release/*`) also gates — catches the case where an agent directly pushes rather than opening a PR. If a command matches both `force_push_any` and `force_push_main`, multi-match merging picks `min(300, 600) = 300s` and `max(medium, high) = high`. +A force-push to any branch needs approval within the task's approval window (30 minutes by default). A force-push to `main` or `prod` raises the severity. A non-force push to a protected branch (`main`/`prod`/`master`/`release/*`) also gates — catches the case where an agent directly pushes rather than opening a PR. If a command matches both `force_push_any` and `force_push_main`, multi-match merging picks `min(300, 600) = 300s` and `max(medium, high) = high`. **Protect sensitive file paths** (soft-deny — part of the built-in starter set): ```cedar @@ -2233,11 +2234,13 @@ Built-in policies shipped with the agent: **Hard-deny (absolute, cannot be disabled by blueprint)**: `rm_slash`, `write_git_internals`, `write_git_internals_nested`, `drop_table`. Absolute; no scope bypasses them; blueprint `disable:` cannot remove them (§5.1, finding #9). **Soft-deny starter set (require approval by default, may be disabled by blueprint)**: -- `force_push_any` — `like "*git push --force*"` — medium, 300s -- `push_to_protected_branch` — pushes to `main`/`master`/`prod`/`release/*` (non-force) — medium, 300s -- `force_push_main` — force-push specifically to `main`/`prod` — high, 600s -- `write_env_files` — `like "*.env"` — high, 600s -- `write_credentials` — `like "*credentials*"` — high, 300s +- `force_push_any` — `like "*git push --force*"` — medium, 3600s +- `push_to_protected_branch` — pushes to `main`/`master`/`prod`/`release/*` (non-force) — medium, 3600s +- `force_push_main` — force-push specifically to `main`/`prod` — high, 3600s +- `write_env_files` — `like "*.env"` — high, 3600s +- `write_credentials` — `like "*credentials*"` — high, 3600s + +Each built-in rule allows the 3600s maximum, so the task's window decides: 1800s by default, set per repo with the blueprint's `security.approvalTimeoutSeconds` or per task with `approval_timeout_s`. (Before #1066 the rules were 300s / 600s and the default 300s, which gave a person five minutes.) Users who want fully autonomous execution (no approval gates) pass `--pre-approve all_session --yes` at submit. Repos that want additional gates add them via `Blueprint.security.cedarPolicies.soft`. Repos that want a different policy set can override specific built-in **soft-deny** rules by `@rule_id` via the blueprint's `security.cedarPolicies.disable` list. The `disable:` mechanism is restricted: it may NOT include any built-in hard-deny rule_id, and the blueprint loader rejects such configurations at task start. diff --git a/docs/src/content/docs/architecture/Compute.md b/docs/src/content/docs/architecture/Compute.md index 62296be74..55b3c3ca5 100644 --- a/docs/src/content/docs/architecture/Compute.md +++ b/docs/src/content/docs/architecture/Compute.md @@ -123,7 +123,7 @@ Because a snapshot freezes its build-time environment, deployment-specific, non- Networking separates image build from execution: the build-only connector permits TCP 80 and 443 because the Dockerfile uses `apt-get`, while running MicroVMs retain 443-only egress through the platform VPC. Every launch explicitly passes the Lambda-managed `NO_INGRESS` connector; omission would select the service's public-ingress default. The P2 image declares and serves `/ready` and `/validate` at build time and `/run` and `/terminate` at runtime. The P3 image also serves `/suspend` and `/resume`. -**Approval-wait sleep (P3).** While a task waits for a human decision, the orchestrator can suspend its MicroVM: compute billing stops and memory and disk are preserved. It suspends only when the deployment enables `microvm_approval_suspend_enabled`, the live Parameter Store switch is on, the launched image version declares the lifecycle protocol, and enough of the gate remains after the task's `microvm_sleep_after_s` delay (default 60 s). It resumes inline when the decision is recorded, with the orchestrator poll as a backstop, and always 60 s before the original deadline. Approval windows stay bounded (300 s default, 3,600 s ceiling), so a suspended worker never outlives its gate. The guest declines an unsafe suspend with HTTP 200 because any other answer makes the service terminate the VM. See [ADR-021 P3 as delivered](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend#p3-as-delivered). +**Approval-wait sleep (P3).** While a task waits for a human decision, the orchestrator can suspend its MicroVM: compute billing stops and memory and disk are preserved. It suspends only when the deployment enables `microvm_approval_suspend_enabled`, the live Parameter Store switch is on, the launched image version declares the lifecycle protocol, and enough of the gate remains after the task's `microvm_sleep_after_s` delay (default 60 s). It resumes inline when the decision is recorded, with the orchestrator poll as a backstop, and always 60 s before the original deadline. Approval windows stay bounded (1,800 s default, 3,600 s ceiling), so a suspended worker never outlives its gate. The guest declines an unsafe suspend with HTTP 200 because any other answer makes the service terminate the VM. See [ADR-021 P3 as delivered](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend#p3-as-delivered). New MicroVM deployments place these resources in a nested stack (`--context microvm_nested_stack=true`, bootstrap 1.9.0 or later); existing flat installations keep `false` until migrated. diff --git a/docs/src/content/docs/using/Approval-gates-cedar-hitl.md b/docs/src/content/docs/using/Approval-gates-cedar-hitl.md index 35d859163..0856cf3e0 100644 --- a/docs/src/content/docs/using/Approval-gates-cedar-hitl.md +++ b/docs/src/content/docs/using/Approval-gates-cedar-hitl.md @@ -15,7 +15,7 @@ When a rule marked `@tier("soft")` matches a tool call: 1. The agent stops before invoking the tool. 2. A row is atomically written to the approvals table and the task status flips to `AWAITING_APPROVAL`. 3. A progress event (`approval_requested`) is emitted so `bgagent watch` shows the gate in real time. -4. The task waits for your decision up to the rule's timeout (default 300 s, configurable per-rule and per-task). +4. The task waits for your decision up to the approval window (default 30 minutes; configurable per repo with the blueprint's `security.approvalTimeoutSeconds`, per task, and per rule, up to 1 hour). 5. On approval, the agent proceeds; on denial, the deny reason is best-effort injected back into the agent's context so it can adapt; on timeout, the gate is treated as a denial with `timed_out` as the reason. A decision is recorded at most once per request. Replaying approve/deny on the same `(task_id, request_id)` is idempotent. diff --git a/docs/src/content/docs/using/Using-the-cli.md b/docs/src/content/docs/using/Using-the-cli.md index c9051bc0c..3b0a59d38 100644 --- a/docs/src/content/docs/using/Using-the-cli.md +++ b/docs/src/content/docs/using/Using-the-cli.md @@ -114,7 +114,7 @@ Created: 2026-04-01T00:39:51.271Z | `--max-budget` | Maximum cost budget in USD (0.01–100). Overrides per-repo Blueprint default. No default limit. | | `--idempotency-key` | Idempotency key for deduplication. | | `--trace` | Enable detailed tracing: raises progress preview cap to 4 KB and uploads full NDJSON trajectory to S3 on completion. Download with `bgagent trace download`. | -| `--approval-timeout` | Cedar HITL per-task approval timeout in seconds (default 300). A matching rule with its own `@approval_timeout_s` annotation still takes the minimum. See [Approval gates](/sample-autonomous-cloud-coding-agents/using/approval-gates-cedar-hitl). | +| `--approval-timeout` | Cedar HITL per-task approval timeout in seconds (default 1800, or the repo blueprint's `security.approvalTimeoutSeconds`). A matching rule with its own `@approval_timeout_s` annotation still takes the minimum. See [Approval gates](/sample-autonomous-cloud-coding-agents/using/approval-gates-cedar-hitl). | | `--microvm-sleep-after` | Seconds to wait for approval before putting a Lambda MicroVM to sleep (default 60; 0–3600 accepted). Use `off` to keep it awake. Requires the deployment's automatic-sleep feature to be enabled; does not change approval deadlines or affect other compute backends. | | `--pre-approve` | Cedar HITL scope to approve up-front (repeatable). Scope forms: `all_session`, `tool_type:`, `tool_group:`, `bash_pattern:`, `write_path:`, `rule:`. Hard-deny rules are always enforced. | | `--wait` | Poll until the task reaches a terminal status. | From 31a071e70ea6750953e49110f9b481c95f2ccdde Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 15:45:38 +0000 Subject: [PATCH 15/27] fix(linear): Linear's delegation comment is not the task's instruction When an issue is delegated, the session's comment is the one Linear writes itself ("This thread is for an agent session with ."). It was read as the person's directive, so it led the task description and named every delegated task's branch (bgagent//this-thread-is-for-an-agent-session- with-...). Seen live on three delegated issues. The placeholder alone now reads as no directive; a person's comment that starts the same way is kept. --- cdk/src/handlers/shared/linear-agent-session-event.ts | 9 +++++++++ cdk/test/handlers/shared/linear-agent-session.test.ts | 11 +++++++++++ 2 files changed, 20 insertions(+) diff --git a/cdk/src/handlers/shared/linear-agent-session-event.ts b/cdk/src/handlers/shared/linear-agent-session-event.ts index 449b11d8b..85a8b1587 100644 --- a/cdk/src/handlers/shared/linear-agent-session-event.ts +++ b/cdk/src/handlers/shared/linear-agent-session-event.ts @@ -160,8 +160,17 @@ const LEADING_PROFILE_MENTION = /^(?:\[[^\]\n]*\]\(\s*https:\/\/linear\.app\/[^\ * goes through the comment trigger's parser so both channels read it the same * way. */ +/** + * The comment Linear itself writes when an issue is delegated to an agent: it opens + * the session's thread and carries no instruction. Taken as one, it led the task + * description and named every delegated task's branch + * (``…/this-thread-is-for-an-agent-session-with-…``). + */ +const DELEGATION_THREAD_PLACEHOLDER = /^This thread is for an agent session with \S+\.?$/i; + function mentionDirective(body: string | undefined): string { const trimmed = (body ?? '').trim().replace(LEADING_PROFILE_MENTION, '').trim(); + if (DELEGATION_THREAD_PLACEHOLDER.test(trimmed)) return ''; const trigger = parseCommentTrigger(trimmed); return trigger.triggered ? trigger.instruction : trimmed; } diff --git a/cdk/test/handlers/shared/linear-agent-session.test.ts b/cdk/test/handlers/shared/linear-agent-session.test.ts index 1cd071dfe..5560dd7a9 100644 --- a/cdk/test/handlers/shared/linear-agent-session.test.ts +++ b/cdk/test/handlers/shared/linear-agent-session.test.ts @@ -109,6 +109,17 @@ describe('parseAgentSessionEvent', () => { expect(at('https://linear.app/acme/issue/ENG-1 is related')).toBe('https://linear.app/acme/issue/ENG-1 is related'); }); + test('Linear\'s own delegation comment is not an instruction (it named every delegated branch)', () => { + const at = (body: string) => parseAgentSessionEvent({ + ...base, action: 'created', agentSession: { id: 's-1', issueId: 'i-1', comment: { body } }, + })?.directive; + expect(at('This thread is for an agent session with alanturing2.')).toBe(''); + expect(at('this thread is for an agent session with bgagent')).toBe(''); + // A person's comment that merely starts the same way is still theirs. + expect(at('This thread is for an agent session with bgagent, so please add tests')).toBe( + 'This thread is for an agent session with bgagent, so please add tests'); + }); + test('created by delegation has an empty directive and tolerates a blank promptContext', () => { const r = parseAgentSessionEvent({ ...base, action: 'created', agentSession: { id: 's-1', issueId: 'i-1' }, promptContext: ' ' }); expect(r).toEqual(expect.objectContaining({ directive: '', actorId: null, promptContext: null })); From 2ebff9cc2cb17aa5a92dfc1d5bd81f3befb1eec7 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 20:44:13 +0000 Subject: [PATCH 16/27] feat(linear): Approve for this task in the agent session Seen live: a repo rule gating the test command asked twice in one task, because a session approval covered that one call only. - A request that matched exactly one rule gets a third button, Approve for this task (value "approve for this task", also accepted typed). It approves with scope rule:, the scope bgagent approve --scope takes, so the agent does not ask again for that rule during the task. - The rule is read consistently from the approval request row, never from the reply. A request that matched several rules keeps Approve / Deny: the agent treats a rule approval as covering any later request that rule is among, so approving one of several would also pass requests the others raise. A whole-task answer there approves the one call and says so. - The setup guide names the button and the 30-minute default. --- .../handlers/shared/approval-notifications.ts | 4 ++ .../shared/linear-agent-session-handler.ts | 25 ++++++++-- .../shared/linear-session-approval.ts | 47 ++++++++++++++++--- .../linear-agent-session-handler.test.ts | 20 ++++++++ .../shared/linear-session-approval.test.ts | 22 +++++++++ docs/guides/LINEAR_SETUP_GUIDE.md | 2 +- .../content/docs/using/Linear-setup-guide.md | 2 +- 7 files changed, 109 insertions(+), 13 deletions(-) diff --git a/cdk/src/handlers/shared/approval-notifications.ts b/cdk/src/handlers/shared/approval-notifications.ts index 6e5401738..1bac7b5cd 100644 --- a/cdk/src/handlers/shared/approval-notifications.ts +++ b/cdk/src/handlers/shared/approval-notifications.ts @@ -49,6 +49,8 @@ export interface ApprovalNotification { readonly marker: string; /** When a pending request is denied unanswered (ISO), if it has a timeout. */ readonly deadline?: string; + /** The soft-deny rules a pending request matched (for an approve-for-this-task choice). */ + readonly ruleIds?: readonly string[]; } /** Where a notice goes. A Linear agent session answers with buttons, not a comment reply. */ @@ -246,6 +248,8 @@ export async function loadApprovalNotification( userId: task.user_id, marker, ...(deadline && { deadline }), + ...(status === 'PENDING' && Array.isArray(row.matching_rule_ids) + && { ruleIds: row.matching_rule_ids.filter((id: unknown): id is string => typeof id === 'string') }), }; } diff --git a/cdk/src/handlers/shared/linear-agent-session-handler.ts b/cdk/src/handlers/shared/linear-agent-session-handler.ts index d6c6c9449..9742e1fd8 100644 --- a/cdk/src/handlers/shared/linear-agent-session-handler.ts +++ b/cdk/src/handlers/shared/linear-agent-session-handler.ts @@ -38,7 +38,6 @@ import { type AgentSessionRequest, type LinearAgentSessionEvent, } from './linear-agent-session-event'; -import { parseLinearApprovalReply } from './linear-approval-thread'; import { lookupLinearPlatformUser, lookupLinearProjectMapping, @@ -50,6 +49,7 @@ import { import { resolveLinearOauthToken, type ResolvedLinearToken } from './linear-oauth-resolver'; import { NOTHING_TO_APPROVE_MESSAGE, + parseSessionApprovalAnswer, repeatedApprovalChoice, sessionDecisionNote, type SessionApprovalActivity, @@ -203,7 +203,7 @@ async function respondToAgentSession( } // A late "approve" / "deny" (after its request timed out, or in the wrong session) // is an answer to nothing. Taken as a prompt it would start new work. - if (parseLinearApprovalReply(request.directive)) { + if (parseSessionApprovalAnswer(request.directive)) { await emit({ type: 'response', body: NOTHING_TO_APPROVE_MESSAGE }); return; } @@ -445,7 +445,7 @@ async function steerRunningTask( await decideSessionApproval(request, task, openRequest, platformUserId, emit); return; } - if (parseLinearApprovalReply(request.directive)) { + if (parseSessionApprovalAnswer(request.directive)) { await reply(NOTHING_TO_APPROVE_MESSAGE); return; } @@ -509,7 +509,7 @@ async function decideSessionApproval( const activity = repeatedApprovalChoice(lead); await emit(activity.content, false, activity); }; - const answer = parseLinearApprovalReply(request.directive); + const answer = parseSessionApprovalAnswer(request.directive); if (!answer) { await again('That isn\'t an answer to the open approval request, so I haven\'t passed it to the agent.'); return; @@ -527,6 +527,7 @@ async function decideSessionApproval( const record = answer.decision === 'approve' ? (await import('../approve-task.js')).recordApprovalForUser : (await import('../deny-task.js')).recordDenialForUser; + const ruleScope = answer.wholeTask ? await singleRuleScope(task.task_id, requestId) : undefined; const result = await record({ userId: platformUserId, taskId: task.task_id, @@ -534,6 +535,7 @@ async function decideSessionApproval( body: JSON.stringify({ request_id: requestId, decision: answer.decision, + ...(ruleScope && { scope: ruleScope }), ...(answer.decision === 'deny' && answer.reason ? { reason: answer.reason } : {}), }), }); @@ -542,9 +544,22 @@ async function decideSessionApproval( task_id: task.task_id, request_id: requestId, decision: answer.decision, + scope: ruleScope ?? 'this_call', status_code: result.statusCode, }); - await emit({ type: 'thought', body: sessionDecisionNote(answer, result) }); + await emit({ type: 'thought', body: sessionDecisionNote(answer, result, ruleScope) }); +} + +/** + * ``rule:`` when the request matched exactly one rule, else undefined (approve + * this call only). Read consistently from the request row, never from the reply. + */ +async function singleRuleScope(taskId: string, requestId: string): Promise { + const { Item } = await ddb.send(new GetCommand({ + TableName: TASK_APPROVALS_TABLE_NAME, Key: { task_id: taskId, request_id: requestId }, ConsistentRead: true, + })); + const ids: unknown[] = Array.isArray(Item?.matching_rule_ids) ? Item.matching_rule_ids : []; + return ids.length === 1 && typeof ids[0] === 'string' ? `rule:${ids[0]}` : undefined; } /** The prior task as read from the base table (strongly consistent). */ diff --git a/cdk/src/handlers/shared/linear-session-approval.ts b/cdk/src/handlers/shared/linear-session-approval.ts index e49e11498..6ecadb324 100644 --- a/cdk/src/handlers/shared/linear-session-approval.ts +++ b/cdk/src/handlers/shared/linear-session-approval.ts @@ -32,7 +32,7 @@ import { approvalNotificationMarkdown, type ApprovalNotification } from './approval-notifications'; import type { AgentActivityContent } from './linear-agent-session'; -import type { LinearApprovalReply } from './linear-approval-thread'; +import { parseLinearApprovalReply, type LinearApprovalReply } from './linear-approval-thread'; /** The buttons. Their values are what the session sends back as the prompt, and what the reply parser reads. */ export const SESSION_APPROVAL_OPTIONS: ReadonlyArray<{ readonly label: string; readonly value: string }> = [ @@ -40,6 +40,22 @@ export const SESSION_APPROVAL_OPTIONS: ReadonlyArray<{ readonly label: string; r { label: 'Deny', value: 'deny' }, ]; +/** Shown only for a request that matched exactly one rule (see {@link sessionApprovalActivity}). */ +const APPROVE_FOR_TASK_OPTION = { label: 'Approve for this task', value: 'approve for this task' } as const; + +/** An answer from the session: approve once, approve the request's rule for the rest of the task, or deny. */ +export type SessionApprovalAnswer = LinearApprovalReply & { readonly wholeTask?: boolean }; + +/** + * A reply that answers an approval request, or null. ``approve for this task`` (the + * button's value, or typed) approves the request's rule for the rest of the task. + * @param text - the reply. + */ +export function parseSessionApprovalAnswer(text: string): SessionApprovalAnswer | null { + if (/^approve\s+for\s+(?:this|the)\s+(?:whole\s+)?task[.!]?$/i.test(text.trim())) return { decision: 'approve', wholeTask: true }; + return parseLinearApprovalReply(text); +} + /** One activity plus the options ``emitAgentActivity`` takes. */ export interface SessionApprovalActivity { readonly content: AgentActivityContent; @@ -92,9 +108,17 @@ export function waitingOnYouLine(deadline: string | undefined, now: Date = new D : '**Waiting on you.** The agent is paused until you answer.'; } -/** The buttons, as ``emitAgentActivity`` options. */ -function choice(body: string): SessionApprovalActivity { - return { content: { type: 'elicitation', body }, signal: 'select', signalMetadata: { options: SESSION_APPROVAL_OPTIONS } }; +/** + * The buttons, as ``emitAgentActivity`` options. "Approve for this task" is offered + * only when the request matched exactly one rule: the agent treats a rule approval + * as covering any later request that rule is among, so approving one of several + * matched rules would also wave through requests the other rules raise. + */ +function choice(body: string, ruleIds?: readonly string[]): SessionApprovalActivity { + const options = ruleIds?.length === 1 + ? [SESSION_APPROVAL_OPTIONS[0], APPROVE_FOR_TASK_OPTION, SESSION_APPROVAL_OPTIONS[1]] + : SESSION_APPROVAL_OPTIONS; + return { content: { type: 'elicitation', body }, signal: 'select', signalMetadata: { options } }; } /** @@ -108,7 +132,9 @@ export function sessionApprovalActivity( eventType: string, notification: ApprovalNotification, now: Date = new Date(), ): SessionApprovalActivity { const body = approvalNotificationMarkdown(notification); - if (eventType === 'approval_requested') return choice(`${body}\n\n${waitingOnYouLine(notification.deadline, now)}`); + if (eventType === 'approval_requested') { + return choice(`${body}\n\n${waitingOnYouLine(notification.deadline, now)}`, notification.ruleIds); + } return { content: { type: 'thought', body } }; } @@ -136,8 +162,17 @@ const HTTP_TOO_MANY = 429; * @param reply - the parsed answer. * @param result - the decision handler's result. */ -export function sessionDecisionNote(reply: LinearApprovalReply, result: DecisionResult): string { +export function sessionDecisionNote( + reply: SessionApprovalAnswer, result: DecisionResult, ruleScope?: string, +): string { if (result.statusCode >= HTTP_OK_MIN && result.statusCode < HTTP_OK_END) { + if (reply.wholeTask && ruleScope) { + return `Approved for the rest of this task: the agent won't ask again for \`${ruleScope}\`.`; + } + if (reply.wholeTask) { + return 'Approved this action only: it matched more than one rule, so I can\'t approve it for the whole task. ' + + 'The agent continues.'; + } return reply.decision === 'approve' ? 'Approved. The agent continues with this action.' : `Denied. The agent carries on without it${reply.reason ? ` (your reason: ${reply.reason})` : ''}.`; diff --git a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts index 5efad164e..6e4c316da 100644 --- a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts +++ b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts @@ -164,6 +164,7 @@ function ddbWith(opts: { linked?: boolean; mapping?: Record | n const key = (cmd.input as unknown as { Key: { task_id: string } }).Key.task_id; return { Item: taskRecords.get(key) }; } + if (cmd.input.TableName === 'Approvals') return approvalRow ? { Item: approvalRow } : {}; if (cmd.input.TableName === 'LinearDedup' && (cmd as unknown as { _type: string })._type === 'Get') { return sessionPointer ? { Item: { task_id: sessionPointer, ttl: Math.floor(Date.now() / 1000) + 600 } } : {}; } @@ -173,6 +174,8 @@ function ddbWith(opts: { linked?: boolean; mapping?: Record | n /** Task id the (strongly consistent) session → task pointer names, if any. */ let sessionPointer: string | null = null; +/** The approval request row the handler reads for a whole-task approval. */ +let approvalRow: Record | null = null; /** Commands sent to one table, by type. */ function sent(table: string, type: string): Array<{ input: Record }> { @@ -218,6 +221,7 @@ beforeEach(() => { jest.clearAllMocks(); taskRecords.clear(); sessionPointer = null; + approvalRow = null; resetSessionWorkspaceCacheForTests(); stopTaskComputeMock.mockResolvedValue(undefined); screenWithGuardrailMock.mockResolvedValue({ action: 'NONE' }); @@ -865,6 +869,22 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', expect(lastEmit()[2].type).toBe('elicitation'); }); + test('"Approve for this task" approves the request\'s one rule for the rest of the task', async () => { + waiting(); + approvalRow = { task_id: 't-1', request_id: 'req-1', matching_rule_ids: ['write_env_files'] }; + await handleAgentSessionEvent(prompted({ content: { body: 'approve for this task' } })); + expect(JSON.parse(recordApprovalMock.mock.calls[0][0].body)).toEqual({ request_id: 'req-1', decision: 'approve', scope: 'rule:write_env_files' }); + expect(String(lastEmit()[2].body)).toContain('won\'t ask again for `rule:write_env_files`'); + }); + + test('a whole-task answer to a request that matched several rules approves this action only', async () => { + waiting(); + approvalRow = { task_id: 't-1', request_id: 'req-1', matching_rule_ids: ['force_push_any', 'force_push_main'] }; + await handleAgentSessionEvent(prompted({ content: { body: 'approve for this task' } })); + expect(JSON.parse(recordApprovalMock.mock.calls[0][0].body)).toEqual({ request_id: 'req-1', decision: 'approve' }); + expect(String(lastEmit()[2].body)).toMatch(/^Approved this action only/); + }); + test('a late Approve after the task finished starts nothing', async () => { priorTask({ task_id: 't-1', status: 'COMPLETED', repo: 'acme/web', linear_workspace_id: 'org-1', session: 'session-1' }); await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); diff --git a/cdk/test/handlers/shared/linear-session-approval.test.ts b/cdk/test/handlers/shared/linear-session-approval.test.ts index 8d9057764..9e8dc43ba 100644 --- a/cdk/test/handlers/shared/linear-session-approval.test.ts +++ b/cdk/test/handlers/shared/linear-session-approval.test.ts @@ -20,6 +20,7 @@ import type { ApprovalNotification } from '../../../src/handlers/shared/approval-notifications'; import { formatDeadline, + parseSessionApprovalAnswer, repeatedApprovalChoice, SESSION_APPROVAL_OPTIONS, sessionApprovalActivity, @@ -84,3 +85,24 @@ test('the note after a decision says what happened', () => { expect(sessionDecisionNote({ decision: 'deny' }, { statusCode: 429 })).toContain('Too many'); expect(sessionDecisionNote({ decision: 'deny' }, { statusCode: 500 })).toContain('bgagent approve'); }); + +test('"Approve for this task" is offered only for a request that matched exactly one rule', () => { + const labels = (ruleIds?: string[]) => (sessionApprovalActivity('approval_requested', { ...notice(), ...(ruleIds && { ruleIds }) }, NOW) + .signalMetadata as { options: Array<{ label: string }> }).options.map((o) => o.label); + expect(labels(['write_env_files'])).toEqual(['Approve', 'Approve for this task', 'Deny']); + expect(labels(['force_push_any', 'force_push_main'])).toEqual(['Approve', 'Deny']); + expect(labels()).toEqual(['Approve', 'Deny']); +}); + +test('the whole-task answer parses from the button value or typed', () => { + expect(parseSessionApprovalAnswer('approve for this task')).toEqual({ decision: 'approve', wholeTask: true }); + expect(parseSessionApprovalAnswer('Approve for the whole task.')).toEqual({ decision: 'approve', wholeTask: true }); + expect(parseSessionApprovalAnswer('approve')).toEqual({ decision: 'approve' }); + expect(parseSessionApprovalAnswer('approve for this task and also rename the file')).toBeNull(); +}); + +test('the note says what a whole-task approval covered', () => { + expect(sessionDecisionNote({ decision: 'approve', wholeTask: true }, { statusCode: 202 }, 'rule:write_env_files')) + .toBe('Approved for the rest of this task: the agent won\'t ask again for `rule:write_env_files`.'); + expect(sessionDecisionNote({ decision: 'approve', wholeTask: true }, { statusCode: 202 })).toMatch(/^Approved this action only/); +}); diff --git a/docs/guides/LINEAR_SETUP_GUIDE.md b/docs/guides/LINEAR_SETUP_GUIDE.md index 68876cf59..964327911 100644 --- a/docs/guides/LINEAR_SETUP_GUIDE.md +++ b/docs/guides/LINEAR_SETUP_GUIDE.md @@ -251,7 +251,7 @@ If you do these the other way round, every mention in the meantime opens a sessi | — the agent opens a PR | Attaches the pull request to the session header and posts an **Opened pull request** action. | | — a long run is in progress | Posts a short-lived "Still working" thought at most every 10 minutes, so the session never goes stale (Linear's idle limit is 30 minutes). | | — the task finishes | Posts one final activity carrying the same outcome, cost, turns and duration as the comment channel: a *response* on success, an *elicitation* if the run stopped to ask you a question, an *error* on failure. Its last line says whether you need to do anything. Linear turns it into the thread comment. A task that ends with a pull request moves the issue to *In Review*. | -| — the agent hits an approval gate | Posts the request with **Approve** / **Deny** buttons and the time by which it is denied if nobody answers. Choose one, or reply `deny `. Only the task owner can decide; anyone else, or any other reply, gets the choice again. A decision made elsewhere (`bgagent approve`, a comment reply) or a timeout shows up as a note. | +| — the agent hits an approval gate | Posts the request with **Approve** / **Deny** buttons and the time by which it is denied if nobody answers (30 minutes by default; see `security.approvalTimeoutSeconds`). Choose one, or reply `deny `. When the request matched a single rule there is also **Approve for this task**, so the agent doesn't ask again for that rule during the task. Only the task owner can decide; anyone else, or any other reply, gets the choice again. A decision made elsewhere (`bgagent approve`, a comment reply) or a timeout shows up as a note. | | — you're at your concurrency limit | Posts a "Queued" thought in the session, and "Still queued (N min so far)" every 15 minutes. The task starts on its own when a slot frees up. | | Reply inside the session while the task runs | Your message goes to the running agent as a nudge (the same guardrail screening, 2,000-character cap and per-minute limit as `bgagent nudge`). The agent picks it up at its next step. Only the task's owner can steer it. | | Reply `approve` or `deny` when nothing is waiting | Says nothing is waiting and starts nothing, so a late answer after a timeout can't start new work. | diff --git a/docs/src/content/docs/using/Linear-setup-guide.md b/docs/src/content/docs/using/Linear-setup-guide.md index 4c00bff5c..9ef90e353 100644 --- a/docs/src/content/docs/using/Linear-setup-guide.md +++ b/docs/src/content/docs/using/Linear-setup-guide.md @@ -253,7 +253,7 @@ If you do these the other way round, every mention in the meantime opens a sessi | — the agent opens a PR | Attaches the pull request to the session header and posts an **Opened pull request** action. | | — a long run is in progress | Posts a short-lived "Still working" thought at most every 10 minutes, so the session never goes stale (Linear's idle limit is 30 minutes). | | — the task finishes | Posts one final activity carrying the same outcome, cost, turns and duration as the comment channel: a *response* on success, an *elicitation* if the run stopped to ask you a question, an *error* on failure. Its last line says whether you need to do anything. Linear turns it into the thread comment. A task that ends with a pull request moves the issue to *In Review*. | -| — the agent hits an approval gate | Posts the request with **Approve** / **Deny** buttons and the time by which it is denied if nobody answers. Choose one, or reply `deny `. Only the task owner can decide; anyone else, or any other reply, gets the choice again. A decision made elsewhere (`bgagent approve`, a comment reply) or a timeout shows up as a note. | +| — the agent hits an approval gate | Posts the request with **Approve** / **Deny** buttons and the time by which it is denied if nobody answers (30 minutes by default; see `security.approvalTimeoutSeconds`). Choose one, or reply `deny `. When the request matched a single rule there is also **Approve for this task**, so the agent doesn't ask again for that rule during the task. Only the task owner can decide; anyone else, or any other reply, gets the choice again. A decision made elsewhere (`bgagent approve`, a comment reply) or a timeout shows up as a note. | | — you're at your concurrency limit | Posts a "Queued" thought in the session, and "Still queued (N min so far)" every 15 minutes. The task starts on its own when a slot frees up. | | Reply inside the session while the task runs | Your message goes to the running agent as a nudge (the same guardrail screening, 2,000-character cap and per-minute limit as `bgagent nudge`). The agent picks it up at its next step. Only the task's owner can steer it. | | Reply `approve` or `deny` when nothing is waiting | Says nothing is waiting and starts nothing, so a late answer after a timeout can't start new work. | From 257c00f53e9a04d392988233976497a3b30719ab Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 00:58:35 +0000 Subject: [PATCH 17/27] fix(linear): read tool-input fields with one fixed pattern, not a regex built per key The SAST range scan flagged inputField: it built a RegExp from each key at call time. One literal pattern now matches every 'key': 'value' pair of the preview, and the caller's key order picks the value. --- .../shared/linear-session-progress.ts | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/cdk/src/handlers/shared/linear-session-progress.ts b/cdk/src/handlers/shared/linear-session-progress.ts index e92930a96..c595af597 100644 --- a/cdk/src/handlers/shared/linear-session-progress.ts +++ b/cdk/src/handlers/shared/linear-session-progress.ts @@ -91,19 +91,23 @@ function parseDetails(details: unknown): Record { } /** - * One field of a tool-input preview. The agent writes the input dict's Python repr - * (`{'file_path': '...'}`), cut at a fixed length, so the field's string value is read - * directly, in either quote style, rather than parsed. + * A `'key': 'value'` pair of a tool-input preview: the agent writes the input dict's + * Python repr (`{'file_path': '...'}`), cut at a fixed length. Key and value quote + * independently, because repr switches a value to double quotes when it holds a + * single quote. A match consumes its whole value, so text inside a value is never + * read as a key. */ +const INPUT_FIELD = /['"](\w+)['"]\s*:\s*(['"])((?:(?!\2)[^\\]|\\.)*)/g; + +/** The first non-empty string value among `keys`, in that order of preference. */ function inputField(preview: unknown, keys: readonly string[]): string | undefined { if (typeof preview !== 'string' || preview.length === 0) return undefined; - for (const k of keys) { - // Key and value quote independently: repr switches a value to double quotes when - // it contains a single quote. - const m = preview.match(new RegExp(`['"]${k}['"]\\s*:\\s*(['"])((?:(?!\\1)[^\\\\]|\\\\.)*)`)); - if (m?.[2]) return m[2].replace(/\\(['"])/g, '$1').replace(/\\n/g, ' '); + const values = new Map(); + for (const [, key, , value] of preview.matchAll(INPUT_FIELD)) { + if (value && !values.has(key)) values.set(key, value); } - return undefined; + const value = keys.map((k) => values.get(k)).find((v) => v !== undefined); + return value?.replace(/\\(['"])/g, '$1').replace(/\\n/g, ' '); } const WORKSPACE_PREFIX = /\/workspace\/[^/\s'"]+\/?/g; From d2eee27ffa4ea8876f748ccbaa4d2ee1bffafaab Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 01:12:07 +0000 Subject: [PATCH 18/27] fix(linear): a session prompt that starts with "deny" is work, not a stray answer With no approval request open, only a bare answer (approve, deny, approve for this task) is refused as an answer to nothing. "Deny anonymous access to /admin" as a new session's request, or "deny-list the tracker domains" to a running task, was refused instead of starting the task or reaching the agent. --- .../handlers/shared/linear-agent-session-handler.ts | 5 +++-- cdk/src/handlers/shared/linear-session-approval.ts | 11 +++++++++++ .../shared/linear-agent-session-handler.test.ts | 13 +++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/cdk/src/handlers/shared/linear-agent-session-handler.ts b/cdk/src/handlers/shared/linear-agent-session-handler.ts index 9742e1fd8..f1abc0e78 100644 --- a/cdk/src/handlers/shared/linear-agent-session-handler.ts +++ b/cdk/src/handlers/shared/linear-agent-session-handler.ts @@ -48,6 +48,7 @@ import { } from './linear-channel-metadata'; import { resolveLinearOauthToken, type ResolvedLinearToken } from './linear-oauth-resolver'; import { + isBareApprovalAnswer, NOTHING_TO_APPROVE_MESSAGE, parseSessionApprovalAnswer, repeatedApprovalChoice, @@ -203,7 +204,7 @@ async function respondToAgentSession( } // A late "approve" / "deny" (after its request timed out, or in the wrong session) // is an answer to nothing. Taken as a prompt it would start new work. - if (parseSessionApprovalAnswer(request.directive)) { + if (isBareApprovalAnswer(request.directive)) { await emit({ type: 'response', body: NOTHING_TO_APPROVE_MESSAGE }); return; } @@ -445,7 +446,7 @@ async function steerRunningTask( await decideSessionApproval(request, task, openRequest, platformUserId, emit); return; } - if (parseSessionApprovalAnswer(request.directive)) { + if (isBareApprovalAnswer(request.directive)) { await reply(NOTHING_TO_APPROVE_MESSAGE); return; } diff --git a/cdk/src/handlers/shared/linear-session-approval.ts b/cdk/src/handlers/shared/linear-session-approval.ts index 6ecadb324..d76e19d3e 100644 --- a/cdk/src/handlers/shared/linear-session-approval.ts +++ b/cdk/src/handlers/shared/linear-session-approval.ts @@ -56,6 +56,17 @@ export function parseSessionApprovalAnswer(text: string): SessionApprovalAnswer return parseLinearApprovalReply(text); } +/** + * An answer with nothing left to answer: a button's value, or approve / deny alone. + * ``deny `` is not one, because with no request open it reads as an instruction + * ("deny anonymous access to /admin"). + * @param text - the prompt. + */ +export function isBareApprovalAnswer(text: string): boolean { + const answer = parseSessionApprovalAnswer(text); + return answer !== null && !answer.reason; +} + /** One activity plus the options ``emitAgentActivity`` takes. */ export interface SessionApprovalActivity { readonly content: AgentActivityContent; diff --git a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts index 6e4c316da..ea98b4f0b 100644 --- a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts +++ b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts @@ -892,6 +892,19 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', expect(lastEmit()[2]).toEqual(expect.objectContaining({ type: 'response', body: expect.stringContaining('Nothing is waiting for your approval') })); }); + test('a new session whose request starts with "Deny" starts the task', async () => { + await handleAgentSessionEvent(created({ + agentSession: { id: 'session-1', issueId: 'issue-1', creatorId: 'linear-user-1', comment: { body: 'Deny anonymous access to /admin' } }, + })); + expect(createTaskCoreMock).toHaveBeenCalledTimes(1); + }); + + test('a follow-up that starts with "deny" while the task runs without a request is passed to the agent', async () => { + priorTask({ task_id: 't-1', status: 'RUNNING', user_id: 'platform-user-1', linear_workspace_id: 'org-1', session: 'session-1' }); + await handleAgentSessionEvent(prompted({ content: { body: 'deny-list the tracker domains too' } })); + expect(submitNudgeMock).toHaveBeenCalledWith(expect.objectContaining({ message: 'deny-list the tracker domains too' })); + }); + test('an Approve while the task runs without a request is not passed to the agent', async () => { priorTask({ task_id: 't-1', status: 'RUNNING', user_id: 'platform-user-1', linear_workspace_id: 'org-1', session: 'session-1' }); await handleAgentSessionEvent(prompted({ content: { body: 'deny' } })); From 1ac627ceb4cc8875f637a84fde5fc5b367f364ed Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 01:13:14 +0000 Subject: [PATCH 19/27] fix(cli): repo onboard keeps the Blueprint approval window bgagent repo onboard rewrites the whole RepoTable row and carries forward the Blueprint-only settings. approval_timeout_s was not among them, so re-onboarding a repo silently put its tasks back on the platform default window. --- cli/src/repo-lookup.ts | 1 + cli/src/repo-onboard.ts | 2 +- cli/test/commands/repo-onboard.test.ts | 7 +++++-- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/cli/src/repo-lookup.ts b/cli/src/repo-lookup.ts index bea54f324..8091ee096 100644 --- a/cli/src/repo-lookup.ts +++ b/cli/src/repo-lookup.ts @@ -44,6 +44,7 @@ export interface RepoConfigRow { readonly egress_allowlist?: string[]; readonly cedar_policies?: string[]; readonly approval_gate_cap?: number; + readonly approval_timeout_s?: number; } /** diff --git a/cli/src/repo-onboard.ts b/cli/src/repo-onboard.ts index 69747c6de..40d5a7dfd 100644 --- a/cli/src/repo-onboard.ts +++ b/cli/src/repo-onboard.ts @@ -121,7 +121,7 @@ export async function onboardRepo( } if (existing?.egress_allowlist?.length) item.egress_allowlist = existing.egress_allowlist; if (existing?.cedar_policies?.length) item.cedar_policies = existing.cedar_policies; - for (const key of ['approval_gate_cap', 'max_budget_usd', 'memory_token_budget'] as const) { + for (const key of ['approval_gate_cap', 'approval_timeout_s', 'max_budget_usd', 'memory_token_budget'] as const) { if (existing?.[key] !== undefined) item[key] = existing[key]; } diff --git a/cli/test/commands/repo-onboard.test.ts b/cli/test/commands/repo-onboard.test.ts index 5e960bd5e..591d140d3 100644 --- a/cli/test/commands/repo-onboard.test.ts +++ b/cli/test/commands/repo-onboard.test.ts @@ -200,6 +200,7 @@ describe('repo onboard/offboard', () => { egress_allowlist: ['example.com'], cedar_policies: ['policy'], approval_gate_cap: 10, + approval_timeout_s: 2700, max_budget_usd: 5, memory_token_budget: 4000, }); @@ -210,14 +211,16 @@ describe('repo onboard/offboard', () => { expect(put.input.Item?.onboarded_at).toBe('2025-01-01T00:00:00Z'); expect(put.input.Item?.cedar_policies).toEqual(['policy']); // Blueprint-only settings have no flag here: a re-onboard must not drop them. - expect(put.input.Item).toMatchObject({ approval_gate_cap: 10, max_budget_usd: 5, memory_token_budget: 4000 }); + expect(put.input.Item).toMatchObject({ + approval_gate_cap: 10, approval_timeout_s: 2700, max_budget_usd: 5, memory_token_budget: 4000, + }); }); test('onboardRepo writes no Blueprint-only setting the existing row does not have', async () => { await onboardRepo('us-east-1', 'RepoTable', 'acme/a'); const put = ddbSend.mock.calls[0][0] as PutCommand; - for (const key of ['approval_gate_cap', 'max_budget_usd', 'memory_token_budget']) { + for (const key of ['approval_gate_cap', 'approval_timeout_s', 'max_budget_usd', 'memory_token_budget']) { expect(put.input.Item).not.toHaveProperty(key); } }); From 27a8d0504be24fb08ad2c3f3997783530e5442ea Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 01:14:04 +0000 Subject: [PATCH 20/27] fix(cdk): a Blueprint redeploy without approvalTimeoutSeconds removes the old window The update path only SET approval_timeout_s when it was configured, so dropping security.approvalTimeoutSeconds from a Blueprint left the earlier value on the RepoTable row and its tasks kept that window. Only the Blueprint writes the field, so the update now REMOVEs it when unset. --- cdk/src/constructs/blueprint.ts | 9 +++++++-- cdk/test/constructs/blueprint.test.ts | 6 ++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/cdk/src/constructs/blueprint.ts b/cdk/src/constructs/blueprint.ts index c611fb043..6e3959e2b 100644 --- a/cdk/src/constructs/blueprint.ts +++ b/cdk/src/constructs/blueprint.ts @@ -570,14 +570,19 @@ export class Blueprint extends Construct { return empty; } + /** Asset fields now empty, and an approval window no longer set: only the Blueprint writes it. */ + private removedFields(): string[] { + return [...this.emptyAssetFields(), ...(this.approvalTimeoutSeconds === undefined ? ['approval_timeout_s'] : [])]; + } + private buildRemoveClause(): string { - const fields = this.emptyAssetFields(); + const fields = this.removedFields(); return fields.length > 0 ? ` REMOVE ${fields.map(f => `#${f}`).join(', ')}` : ''; } private buildRemoveNames(): Record { const names: Record = {}; - const fields = this.emptyAssetFields(); + const fields = this.removedFields(); for (const f of fields) names[`#${f}`] = f; return names; } diff --git a/cdk/test/constructs/blueprint.test.ts b/cdk/test/constructs/blueprint.test.ts index fdff87bd3..cb032bff7 100644 --- a/cdk/test/constructs/blueprint.test.ts +++ b/cdk/test/constructs/blueprint.test.ts @@ -578,6 +578,12 @@ describe('Blueprint construct', () => { expect(getCreateJoinParts(template).join('')).not.toContain('approval_timeout_s'); }); + test('a redeploy without approvalTimeoutSeconds removes the window an earlier deploy set', () => { + const { template } = createStack({ security: { approvalGateCap: 10 } }); + const removeClause = /REMOVE ([^"\\]*)/.exec(getUpdateJoinParts(template).join(''))?.[1] ?? ''; + expect(removeClause).toContain('#approval_timeout_s'); + }); + test.each([10, 3601, 90.5])('rejects approvalTimeoutSeconds %p at synth', (seconds) => { const app = new App(); const stack = new Stack(app, 'TestStack'); From 121d08352358015a7f2127134b1a2bab5c0a39e3 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 01:17:33 +0000 Subject: [PATCH 21/27] refactor(linear): drop duplicated PR-label parsing, dead guards and restating comments checklistMoveForEvent no longer parses the PR number itself: the dispatcher already labels every checklist write from the task's PR. progressActivityId builds its version-4 UUID like the approval comment id, without the variant table. The claim helpers drop a TASK_TABLE_NAME guard the dispatcher already needs, the checklist stage drops a coercion for a writer that never existed, and two doc comments that ended up above the wrong function are back on theirs. --- cdk/src/handlers/fanout-task-events.ts | 25 +++++-------------- cdk/src/handlers/shared/create-task-core.ts | 16 ++++++------ .../shared/linear-agent-session-event.ts | 14 +++++------ .../shared/linear-session-checklist.ts | 10 +++----- .../shared/linear-session-progress.ts | 11 +++----- .../shared/linear-session-checklist.test.ts | 2 +- 6 files changed, 27 insertions(+), 51 deletions(-) diff --git a/cdk/src/handlers/fanout-task-events.ts b/cdk/src/handlers/fanout-task-events.ts index 98ca124e8..58a81e5ab 100644 --- a/cdk/src/handlers/fanout-task-events.ts +++ b/cdk/src/handlers/fanout-task-events.ts @@ -235,8 +235,6 @@ export const CHANNEL_DEFAULTS: Record> // even earlier, at task-admission in the webhook processor (ADR-016 P4.5). linear: new Set([ ...TERMINAL_EVENT_TYPES, - // Approval request and outcome notices, rendered from the saved approval - // row with per-request delivery receipts (#1001). ...LINEAR_APPROVAL_EVENTS, 'pr_created', // Include task_timed_out so a Linear standalone iteration @@ -407,8 +405,6 @@ export function parseStreamRecord(record: DynamoDBRecord): FanOutEvent | null { * ``trajectory_uploaded``, ``trace_truncated``. Only ``pr_created`` * is currently in any channel's default filter (§6.2 Slack + GitHub). */ -// Approval milestones route by name so channels see them as their own event -// type. Slack's dispatcher still drops them at its NOTIFIABLE_EVENTS gate. const ROUTABLE_MILESTONES: ReadonlySet = new Set([ 'pr_created', ...LINEAR_APPROVAL_EVENTS, ...LINEAR_SESSION_PROGRESS_MILESTONES, ]); @@ -1269,8 +1265,6 @@ async function closeEndedApprovalThread( workspaceId: string, issueId: string, ): Promise { - // A task that ends while waiting (e.g. cancelled) leaves its reply thread - // open; start its retention so late replies find nothing to decide. if (approvalsTable && task.awaiting_approval_request_id && (TERMINAL_EVENT_TYPES as readonly string[]).includes(event.event_type)) { await closeLinearApprovalThread(ddb, approvalsTable, { @@ -1385,7 +1379,7 @@ async function dispatchToLinear(event: FanOutEvent): Promise { const effectiveType = effectiveEventType(event); if (isApprovalNotification(effectiveType)) { await dispatchLinearApprovalNotice(event, task, effectiveType, approvalsTable, workspaceId, issueId, registryTableName); - return; // An approval notice never settles the task's final status. + return; } await closeEndedApprovalThread(event, task, approvalsTable, workspaceId, issueId); @@ -1810,8 +1804,7 @@ async function advanceSessionChecklist( const kind = checklistKind(task.resolved_workflow?.id); if (!kind || task.linear_final_comment_event_id) return; const effective = effectiveEventType(event); - // The document client returns numbers as numbers; coerce in case an older writer stored a string. - const recorded = Number(task.linear_checklist_stage ?? 0); + const recorded = task.linear_checklist_stage ?? 0; let state: ChecklistState; let ending: ChecklistEnding | undefined; if (LINEAR_SESSION_TERMINAL_EVENTS.has(effective)) { @@ -1824,9 +1817,9 @@ async function advanceSessionChecklist( } } else { if (TERMINAL_STATUSES.includes(task.status)) return; - const move = checklistMoveForEvent(effective, task.pr_url); + const move = checklistMoveForEvent(effective); if (!move) return; - state = { ...move, pr: move.pr ?? prLabel(task.pr_url) }; + state = { ...move, pr: prLabel(task.pr_url) }; } const logCtx = { task_id: task.task_id, linear_agent_session_id: agentSessionId, event_type: effective }; try { @@ -1844,11 +1837,9 @@ async function advanceSessionChecklist( /** Record a checklist stage if it is past the recorded one; false when it is not (nothing to show). */ async function claimChecklistStage(taskId: string, stage: number): Promise { - const tableName = process.env.TASK_TABLE_NAME; - if (!tableName) return false; try { await ddb.send(new UpdateCommand({ - TableName: tableName, + TableName: process.env.TASK_TABLE_NAME, Key: { task_id: taskId }, UpdateExpression: 'SET linear_checklist_stage = :s', ConditionExpression: 'attribute_exists(task_id) AND (attribute_not_exists(linear_checklist_stage) OR linear_checklist_stage < :s)', @@ -1915,11 +1906,9 @@ async function emitLinearSessionProgress( /** Take one of the task's persistent progress slots; false once the cap is reached. */ async function claimProgressSlot(taskId: string): Promise { - const tableName = process.env.TASK_TABLE_NAME; - if (!tableName) return false; try { await ddb.send(new UpdateCommand({ - TableName: tableName, + TableName: process.env.TASK_TABLE_NAME, Key: { task_id: taskId }, UpdateExpression: 'ADD linear_session_progress_count :one', ConditionExpression: 'attribute_exists(task_id) AND (attribute_not_exists(linear_session_progress_count) OR linear_session_progress_count < :cap)', @@ -2750,8 +2739,6 @@ export const handler = async ( dropped++; continue; } - // Only the latest tool call of a task in this batch is shown: the session's - // "currently doing" line would replace the earlier ones at once anyway. if (supersededToolCalls.has(ev.event_id)) { dropped++; continue; diff --git a/cdk/src/handlers/shared/create-task-core.ts b/cdk/src/handlers/shared/create-task-core.ts index e3c932ce5..71d119fd4 100644 --- a/cdk/src/handlers/shared/create-task-core.ts +++ b/cdk/src/handlers/shared/create-task-core.ts @@ -200,7 +200,6 @@ export async function createTaskCore( // in the "Task created" log. A repo-less submission has no blueprint, so it // stays false. let capFromBlueprint = false; - // The blueprint's approval window, the default for this task unless the request sets its own. let blueprintApprovalTimeoutS: number | undefined; if (body.repo) { const { onboarded, config: repoConfig } = await lookupRepo(body.repo); @@ -948,16 +947,10 @@ export async function createTaskCore( return successResponse(201, toTaskDetail(taskRecord), requestId); } -/** - * Check one entry of initial_approvals (§7.3 step 4). - * @param entry - the entry as the request body holds it. - * @returns the parsed scope, or the message of the 400 that refuses the entry. - */ /** * The blueprint's ``approval_timeout_s``, or undefined when it has none. A value out - * of the ``[min, max]`` envelope (a hand-edited row; the construct validates at - * synth) is logged and ignored, so the task gets the platform default rather than - * being refused: a wrong waiting time is not a reason to stop work. + * of the ``[min, max]`` envelope (a hand-edited row) is logged and ignored, so the + * task gets the platform default rather than being refused. */ function blueprintApprovalTimeout( config: { readonly approval_timeout_s?: unknown } | null, repo: string, requestId: string, @@ -972,6 +965,11 @@ function blueprintApprovalTimeout( return undefined; } +/** + * Check one entry of initial_approvals (§7.3 step 4). + * @param entry - the entry as the request body holds it. + * @returns the parsed scope, or the message of the 400 that refuses the entry. + */ function checkInitialApproval(entry: unknown): { ok: true; scope: string } | { ok: false; message: string } { const parseResult = parseApprovalScope(String(entry)); if (!parseResult.ok) { diff --git a/cdk/src/handlers/shared/linear-agent-session-event.ts b/cdk/src/handlers/shared/linear-agent-session-event.ts index 85a8b1587..8e5702395 100644 --- a/cdk/src/handlers/shared/linear-agent-session-event.ts +++ b/cdk/src/handlers/shared/linear-agent-session-event.ts @@ -153,6 +153,12 @@ export const SESSION_STOP_CANCELLED_VIA = 'linear_session_stop'; */ const LEADING_PROFILE_MENTION = /^(?:\[[^\]\n]*\]\(\s*https:\/\/linear\.app\/[^\s)]+\/profiles\/[^\s)]+\s*\)|]+>?)[,:]?\s*/i; +/** + * The comment Linear itself writes when an issue is delegated to an agent: it opens + * the session's thread and carries no instruction. + */ +const DELEGATION_THREAD_PLACEHOLDER = /^This thread is for an agent session with \S+\.?$/i; + /** * The instruction in a mention comment, with the mention itself removed — a * bare mention is no instruction at all. Linear stores a real mention as the @@ -160,14 +166,6 @@ const LEADING_PROFILE_MENTION = /^(?:\[[^\]\n]*\]\(\s*https:\/\/linear\.app\/[^\ * goes through the comment trigger's parser so both channels read it the same * way. */ -/** - * The comment Linear itself writes when an issue is delegated to an agent: it opens - * the session's thread and carries no instruction. Taken as one, it led the task - * description and named every delegated task's branch - * (``…/this-thread-is-for-an-agent-session-with-…``). - */ -const DELEGATION_THREAD_PLACEHOLDER = /^This thread is for an agent session with \S+\.?$/i; - function mentionDirective(body: string | undefined): string { const trimmed = (body ?? '').trim().replace(LEADING_PROFILE_MENTION, '').trim(); if (DELEGATION_THREAD_PLACEHOLDER.test(trimmed)) return ''; diff --git a/cdk/src/handlers/shared/linear-session-checklist.ts b/cdk/src/handlers/shared/linear-session-checklist.ts index a48d4940b..93a3a5709 100644 --- a/cdk/src/handlers/shared/linear-session-checklist.ts +++ b/cdk/src/handlers/shared/linear-session-checklist.ts @@ -97,20 +97,16 @@ export function renderChecklist(kind: ChecklistKind, state: ChecklistState, endi } /** - * Where an event moves the checklist, or null when it does not. + * The stage an event moves the checklist to, or null when it does not. * @param effectiveType - the event type, or a milestone's name. - * @param prUrl - the task's pull request, for ``pr_created``. */ -export function checklistMoveForEvent(effectiveType: string, prUrl?: string): ChecklistState | null { +export function checklistMoveForEvent(effectiveType: string): Omit | null { switch (effectiveType) { case 'admission_queued': return { stage: CHECKLIST_STAGE.understand, note: 'queued for a free slot' }; case 'hydration_complete': return { stage: CHECKLIST_STAGE.setup }; case 'repo_setup_complete': return { stage: CHECKLIST_STAGE.code }; case 'agent_execution_complete': return { stage: CHECKLIST_STAGE.pr }; - case 'pr_created': { - const n = prUrl?.match(/\/pull\/(\d+)/)?.[1]; - return { stage: CHECKLIST_STAGE.review, ...(n && { pr: `#${n}` }) }; - } + case 'pr_created': return { stage: CHECKLIST_STAGE.review }; default: return null; } } diff --git a/cdk/src/handlers/shared/linear-session-progress.ts b/cdk/src/handlers/shared/linear-session-progress.ts index c595af597..e9a6ac29a 100644 --- a/cdk/src/handlers/shared/linear-session-progress.ts +++ b/cdk/src/handlers/shared/linear-session-progress.ts @@ -72,10 +72,8 @@ export const LINEAR_SESSION_PROGRESS_MILESTONES: readonly string[] = [ const THOUGHT_MAX = 600; const TOOL_PARAMETER_MAX = 120; const BRANCH_MAX = 80; -const UUID_VARIANTS = '89ab'; -const HEX = 16; -/** The first 32 hex digits of a digest, grouped as a UUID's fields (the version nibble dropped). */ -const UUID_LAYOUT = /^(.{8})(.{4}).(.{3})(.)(.{3})(.{12}).*$/; +/** A digest's hex digits as a UUID's fields, skipping the version and variant nibbles. */ +const UUID_FIELDS = /^(.{8})(.{4}).(.{3}).(.{3})(.{12})/; function clip(value: string, max: number): string { const flat = value.replace(/\s+/g, ' ').trim(); @@ -210,7 +208,6 @@ export function sessionProgressActivity( */ export function progressActivityId(seed: string): string { const hex = createHash('sha256').update(`linear-session-progress:${seed}`).digest('hex'); - // 8-4-4-4-12 hex digits, with version nibble 4 and an RFC 4122 variant nibble (8, 9, a or b). - return hex.replace(UUID_LAYOUT, (_all, a: string, b: string, c: string, variant: string, d: string, e: string) => - `${a}-${b}-4${c}-${UUID_VARIANTS[Number.parseInt(variant, HEX) % UUID_VARIANTS.length]}${d}-${e}`); + const [, a, b, c, d, e] = UUID_FIELDS.exec(hex)!; + return `${a}-${b}-4${c}-a${d}-${e}`; } diff --git a/cdk/test/handlers/shared/linear-session-checklist.test.ts b/cdk/test/handlers/shared/linear-session-checklist.test.ts index 08a233ec9..cca9dec4a 100644 --- a/cdk/test/handlers/shared/linear-session-checklist.test.ts +++ b/cdk/test/handlers/shared/linear-session-checklist.test.ts @@ -57,7 +57,7 @@ test('events move the checklist to their stage; others do not move it', () => { expect(checklistMoveForEvent('hydration_complete')).toEqual({ stage: CHECKLIST_STAGE.setup }); expect(checklistMoveForEvent('repo_setup_complete')).toEqual({ stage: CHECKLIST_STAGE.code }); expect(checklistMoveForEvent('agent_execution_complete')).toEqual({ stage: CHECKLIST_STAGE.pr }); - expect(checklistMoveForEvent('pr_created', 'https://github.com/acme/web/pull/42')).toEqual({ stage: CHECKLIST_STAGE.review, pr: '#42' }); + expect(checklistMoveForEvent('pr_created')).toEqual({ stage: CHECKLIST_STAGE.review }); expect(checklistMoveForEvent('agent_tool_call')).toBeNull(); }); From 76db21e3cbf5c484825157da3dc4725c075300c0 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 01:36:29 +0000 Subject: [PATCH 22/27] fix(linear): a session approval is read back from Linear before it is recorded Session approve / deny replies were decided from the webhook's fields alone. The comment path (#1001) reads each reply back from Linear because legacy worker credentials can read the OAuth bundle that holds the webhook signing key, so a worker could otherwise sign its own approval in the owner's name. The session path now does the same: fetchSessionPromptActivity reads the prompt activity by id and the decision is recorded only when it is a human's prompt (not an app, not the token's own identity) in this session, by the same person, with the same answer. A lookup failure throws, so the delivery retries instead of trusting the webhook. --- .../shared/linear-agent-session-handler.ts | 30 +++++++++- .../handlers/shared/linear-agent-session.ts | 56 +++++++++++++++++++ .../linear-agent-session-handler.test.ts | 52 +++++++++++++---- .../shared/linear-agent-session.test.ts | 33 +++++++++++ 4 files changed, 159 insertions(+), 12 deletions(-) diff --git a/cdk/src/handlers/shared/linear-agent-session-handler.ts b/cdk/src/handlers/shared/linear-agent-session-handler.ts index f1abc0e78..746529320 100644 --- a/cdk/src/handlers/shared/linear-agent-session-handler.ts +++ b/cdk/src/handlers/shared/linear-agent-session-handler.ts @@ -29,6 +29,7 @@ import { buildAgentSessionTaskDescription, emitAgentActivity, fetchAgentSessionIssue, + fetchSessionPromptActivity, type AgentActivityContent, type AgentSessionIssue, } from './linear-agent-session'; @@ -54,6 +55,7 @@ import { repeatedApprovalChoice, sessionDecisionNote, type SessionApprovalActivity, + type SessionApprovalAnswer, } from './linear-session-approval'; import { fetchIssueParentId } from './linear-subissue-fetch'; import { lookupTaskByLinearIssue, type LinearIssueTask } from './linear-task-by-issue'; @@ -199,7 +201,7 @@ async function respondToAgentSession( const priorTask = await findPriorTask(request); if (priorTask && !isTerminal(priorTask.status)) { - await steerRunningTask(request, priorTask, platformUserId, emit); + await steerRunningTask(request, priorTask, platformUserId, emit, resolved.accessToken); return; } // A late "approve" / "deny" (after its request timed out, or in the wrong session) @@ -438,12 +440,13 @@ async function steerRunningTask( task: PriorTask, platformUserId: string, emit: SessionEmit, + accessToken: string, ): Promise { const ownSession = isRunningTasksOwnSession(request, task); const reply = (body: string) => emit(ownSession ? { type: 'thought', body } : { type: 'response', body }); const openRequest = task.status === 'AWAITING_APPROVAL' ? task.awaiting_approval_request_id : undefined; if (ownSession && openRequest && request.directive) { - await decideSessionApproval(request, task, openRequest, platformUserId, emit); + await decideSessionApproval(request, task, openRequest, platformUserId, emit, accessToken); return; } if (isBareApprovalAnswer(request.directive)) { @@ -505,6 +508,7 @@ async function decideSessionApproval( requestId: string, platformUserId: string, emit: SessionEmit, + accessToken: string, ): Promise { const again = async (lead: string) => { const activity = repeatedApprovalChoice(lead); @@ -523,6 +527,13 @@ async function decideSessionApproval( await emit({ type: 'thought', body: 'Approvals can\'t be answered in Linear on this deployment. Use `bgagent approve` / `bgagent deny`.' }); return; } + if (!await promptConfirmed(request, answer, accessToken)) { + logger.warn('Agent-session approval reply not confirmed by Linear — no decision recorded', { + linear_agent_session_id: request.sessionId, task_id: task.task_id, request_id: requestId, + }); + await again('I couldn\'t confirm this answer with Linear, so nothing was decided.'); + return; + } // Loaded only when a session decides: other session deliveries do not need the // decision handlers' environment. const record = answer.decision === 'approve' @@ -551,6 +562,21 @@ async function decideSessionApproval( await emit({ type: 'thought', body: sessionDecisionNote(answer, result, ruleScope) }); } +/** + * True when Linear holds this delivery as a human's prompt in this session, from the + * same person, with the same answer. The decision is consent, so it is taken from + * Linear's copy, not the webhook's (see ``fetchSessionPromptActivity``). + */ +async function promptConfirmed( + request: AgentSessionRequest, answer: SessionApprovalAnswer, accessToken: string, +): Promise { + const prompt = await fetchSessionPromptActivity(accessToken, request.workspaceId, request.deliveryId); + const echoed = prompt ? parseSessionApprovalAnswer(prompt.body) : null; + return prompt?.sessionId === request.sessionId && prompt.authorId === request.actorId + && echoed?.decision === answer.decision && (echoed.reason ?? '') === (answer.reason ?? '') + && Boolean(echoed.wholeTask) === Boolean(answer.wholeTask); +} + /** * ``rule:`` when the request matched exactly one rule, else undefined (approve * this call only). Read consistently from the request row, never from the reply. diff --git a/cdk/src/handlers/shared/linear-agent-session.ts b/cdk/src/handlers/shared/linear-agent-session.ts index dccce5f16..d2c7ef5fd 100644 --- a/cdk/src/handlers/shared/linear-agent-session.ts +++ b/cdk/src/handlers/shared/linear-agent-session.ts @@ -157,6 +157,62 @@ export async function fetchAgentSessionIssue( }); } +/** A human's prompt in a session, as Linear records it. */ +export interface SessionPromptActivity { + readonly sessionId: string; + readonly authorId: string; + readonly body: string; +} + +const SESSION_PROMPT_QUERY = ` +query VerifySessionPrompt($id: String!) { + organization { id } + viewer { id } + agentActivity(id: $id) { + agentSession { id } + content { __typename ... on AgentActivityPromptContent { body } } + user { id app } + promptAuthor { id app } + } +}`; + +/** + * Read a session prompt back from Linear before acting on it as consent. Webhook + * authentication alone is not enough: legacy worker credentials can read the OAuth + * bundle that holds the webhook signing key (the comment path reads its replies back + * for the same reason, ``readLinearApprovalComment``). Null when the activity is not a + * human's prompt: missing, not a prompt, written by an app, or by this token's own + * identity. Throws when Linear cannot answer, so the delivery retries instead of + * falling back to the webhook's fields. + */ +export async function fetchSessionPromptActivity( + accessToken: string, + workspaceId: string, + activityId: string, +): Promise { + const result = await graphqlData(accessToken, SESSION_PROMPT_QUERY, { id: activityId }); + if (!result.ok) throw new Error('Linear session prompt verification unavailable'); + const data = result.value as { + organization?: { id?: string }; + viewer?: { id?: string }; + agentActivity?: { + agentSession?: { id?: string } | null; + content?: { __typename?: string; body?: string } | null; + user?: { id?: string; app?: boolean } | null; + promptAuthor?: { id?: string; app?: boolean } | null; + } | null; + }; + if (data.organization?.id !== workspaceId) throw new Error('Linear session prompt verification workspace mismatch'); + const viewerId = data.viewer?.id; + if (!viewerId) throw new Error('Linear session prompt verification identity unavailable'); + const activity = data.agentActivity; + const author = activity?.promptAuthor ?? activity?.user; + const sessionId = activity?.agentSession?.id; + if (activity?.content?.__typename !== 'AgentActivityPromptContent' || !sessionId + || !author?.id || author.app || author.id === viewerId) return null; + return { sessionId, authorId: author.id, body: activity.content.body ?? '' }; +} + /** Separator + heading that introduces Linear's `promptContext` in the description. */ const SESSION_CONTEXT_PREFIX = '\n\n## Linear session context\n\n'; const CONTEXT_TRUNCATION_NOTICE = '\n\n_(session context truncated)_'; diff --git a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts index ea98b4f0b..611982415 100644 --- a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts +++ b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts @@ -41,12 +41,14 @@ jest.mock('../../../src/handlers/shared/linear-oauth-resolver', () => ({ const emitAgentActivityMock = jest.fn(); const fetchAgentSessionIssueMock = jest.fn(); +const fetchSessionPromptActivityMock = jest.fn(); jest.mock('../../../src/handlers/shared/linear-agent-session', () => { const actual = jest.requireActual('../../../src/handlers/shared/linear-agent-session'); return { ...actual, emitAgentActivity: (...args: unknown[]) => emitAgentActivityMock(...args), fetchAgentSessionIssue: (...args: unknown[]) => fetchAgentSessionIssueMock(...args), + fetchSessionPromptActivity: (...args: unknown[]) => fetchSessionPromptActivityMock(...args), }; }); @@ -819,6 +821,12 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', }); const lastEmit = () => emitAgentActivityMock.mock.calls.at(-1)!; + /** Send a prompt that Linear holds as written: the same session, author and body. */ + const answer = async (body: string) => { + fetchSessionPromptActivityMock.mockResolvedValue({ sessionId: 'session-1', authorId: 'linear-user-1', body }); + await handleAgentSessionEvent(prompted({ content: { body } })); + }; + beforeEach(() => { recordApprovalMock.mockResolvedValue({ statusCode: 202 }); recordDenialMock.mockResolvedValue({ statusCode: 202 }); @@ -826,7 +834,7 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', test('the owner\'s Approve decides the open request through the API path, not as a nudge', async () => { waiting(); - await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); + await answer('approve'); expect(recordApprovalMock).toHaveBeenCalledWith({ userId: 'platform-user-1', taskId: 't-1', @@ -839,7 +847,7 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', test('a deny with a reason passes the reason on', async () => { waiting(); - await handleAgentSessionEvent(prompted({ content: { body: 'deny use the staging config' } })); + await answer('deny use the staging config'); expect(JSON.parse(recordDenialMock.mock.calls[0][0].body)).toEqual({ request_id: 'req-1', decision: 'deny', reason: 'use the staging config' }); expect(String(lastEmit()[2].body)).toContain('your reason: use the staging config'); }); @@ -847,13 +855,13 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', test('a request that was already answered or timed out changes nothing, and says so', async () => { waiting(); recordApprovalMock.mockResolvedValue({ statusCode: 409 }); - await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); + await answer('approve'); expect(String(lastEmit()[2].body)).toContain('already answered or timed out'); }); test('someone other than the owner gets the choice again, and nothing is decided', async () => { waiting('someone-else'); - await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); + await answer('approve'); expect(recordApprovalMock).not.toHaveBeenCalled(); const [, , content, options] = lastEmit(); expect(content.type).toBe('elicitation'); @@ -863,7 +871,7 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', test('anything else keeps the request open: the choice comes back, nothing is nudged', async () => { waiting(); - await handleAgentSessionEvent(prompted({ content: { body: 'what does this command do?' } })); + await answer('what does this command do?'); expect(recordApprovalMock).not.toHaveBeenCalled(); expect(submitNudgeMock).not.toHaveBeenCalled(); expect(lastEmit()[2].type).toBe('elicitation'); @@ -872,7 +880,7 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', test('"Approve for this task" approves the request\'s one rule for the rest of the task', async () => { waiting(); approvalRow = { task_id: 't-1', request_id: 'req-1', matching_rule_ids: ['write_env_files'] }; - await handleAgentSessionEvent(prompted({ content: { body: 'approve for this task' } })); + await answer('approve for this task'); expect(JSON.parse(recordApprovalMock.mock.calls[0][0].body)).toEqual({ request_id: 'req-1', decision: 'approve', scope: 'rule:write_env_files' }); expect(String(lastEmit()[2].body)).toContain('won\'t ask again for `rule:write_env_files`'); }); @@ -880,14 +888,14 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', test('a whole-task answer to a request that matched several rules approves this action only', async () => { waiting(); approvalRow = { task_id: 't-1', request_id: 'req-1', matching_rule_ids: ['force_push_any', 'force_push_main'] }; - await handleAgentSessionEvent(prompted({ content: { body: 'approve for this task' } })); + await answer('approve for this task'); expect(JSON.parse(recordApprovalMock.mock.calls[0][0].body)).toEqual({ request_id: 'req-1', decision: 'approve' }); expect(String(lastEmit()[2].body)).toMatch(/^Approved this action only/); }); test('a late Approve after the task finished starts nothing', async () => { priorTask({ task_id: 't-1', status: 'COMPLETED', repo: 'acme/web', linear_workspace_id: 'org-1', session: 'session-1' }); - await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); + await answer('approve'); expect(createTaskCoreMock).not.toHaveBeenCalled(); expect(lastEmit()[2]).toEqual(expect.objectContaining({ type: 'response', body: expect.stringContaining('Nothing is waiting for your approval') })); }); @@ -901,14 +909,38 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', test('a follow-up that starts with "deny" while the task runs without a request is passed to the agent', async () => { priorTask({ task_id: 't-1', status: 'RUNNING', user_id: 'platform-user-1', linear_workspace_id: 'org-1', session: 'session-1' }); - await handleAgentSessionEvent(prompted({ content: { body: 'deny-list the tracker domains too' } })); + await answer('deny-list the tracker domains too'); expect(submitNudgeMock).toHaveBeenCalledWith(expect.objectContaining({ message: 'deny-list the tracker domains too' })); }); test('an Approve while the task runs without a request is not passed to the agent', async () => { priorTask({ task_id: 't-1', status: 'RUNNING', user_id: 'platform-user-1', linear_workspace_id: 'org-1', session: 'session-1' }); - await handleAgentSessionEvent(prompted({ content: { body: 'deny' } })); + await answer('deny'); expect(submitNudgeMock).not.toHaveBeenCalled(); expect(lastEmit()[2]).toEqual(expect.objectContaining({ type: 'thought', body: expect.stringContaining('Nothing is waiting') })); }); + + test('a reply Linear does not hold as written decides nothing (a forged webhook)', async () => { + waiting(); + for (const held of [ + null, + { sessionId: 'session-1', authorId: 'someone-else', body: 'approve' }, + { sessionId: 'other-session', authorId: 'linear-user-1', body: 'approve' }, + { sessionId: 'session-1', authorId: 'linear-user-1', body: 'deny' }, + ]) { + recordApprovalMock.mockClear(); + fetchSessionPromptActivityMock.mockResolvedValue(held); + await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); + expect(recordApprovalMock).not.toHaveBeenCalled(); + expect(String(lastEmit()[2].body)).toMatch(/^I couldn't confirm this answer with Linear/); + } + expect(fetchSessionPromptActivityMock).toHaveBeenCalledWith('lin_tok', 'org-1', 'activity-9'); + }); + + test('when Linear cannot be asked, the delivery fails so it is retried, and nothing is decided', async () => { + waiting(); + fetchSessionPromptActivityMock.mockRejectedValue(new Error('Linear session prompt verification unavailable')); + await expect(handleAgentSessionEvent(prompted({ content: { body: 'approve' } }))).rejects.toThrow('verification unavailable'); + expect(recordApprovalMock).not.toHaveBeenCalled(); + }); }); diff --git a/cdk/test/handlers/shared/linear-agent-session.test.ts b/cdk/test/handlers/shared/linear-agent-session.test.ts index 5560dd7a9..47058a451 100644 --- a/cdk/test/handlers/shared/linear-agent-session.test.ts +++ b/cdk/test/handlers/shared/linear-agent-session.test.ts @@ -27,6 +27,7 @@ import { buildAgentSessionTaskDescription, emitAgentActivity, fetchAgentSessionIssue, + fetchSessionPromptActivity, } from '../../../src/handlers/shared/linear-agent-session'; import { isHandledAgentSessionAction, @@ -268,4 +269,36 @@ describe('GraphQL helpers', () => { expect(failed.ok).toBe(false); expect('error' in failed).toBe(true); }); + + describe('fetchSessionPromptActivity (consent is read from Linear, not the webhook)', () => { + const reply = (activity: unknown, org = 'org-1') => jsonResponse({ + data: { organization: { id: org }, viewer: { id: 'app-user' }, agentActivity: activity }, + }); + const prompt = (author: unknown, typename = 'AgentActivityPromptContent') => ({ + agentSession: { id: 's-1' }, content: { __typename: typename, body: 'approve' }, user: null, promptAuthor: author, + }); + + test('a human\'s prompt comes back with its session, author and body', async () => { + fetchMock.mockResolvedValueOnce(reply(prompt({ id: 'u-1', app: false }))); + await expect(fetchSessionPromptActivity('tok', 'org-1', 'a-1')).resolves.toEqual({ sessionId: 's-1', authorId: 'u-1', body: 'approve' }); + expect(sentBody(0).variables).toEqual({ id: 'a-1' }); + }); + + test.each([ + ['an app', prompt({ id: 'u-2', app: true })], + ['this token\'s own identity', prompt({ id: 'app-user', app: false })], + ['not a prompt', prompt({ id: 'u-1', app: false }, 'AgentActivityThoughtContent')], + ['missing', null], + ])('an activity by %s is not consent', async (_label, activity) => { + fetchMock.mockResolvedValueOnce(reply(activity)); + await expect(fetchSessionPromptActivity('tok', 'org-1', 'a-1')).resolves.toBeNull(); + }); + + test('another workspace, or Linear failing, throws so the delivery retries', async () => { + fetchMock.mockResolvedValueOnce(reply(prompt({ id: 'u-1', app: false }), 'org-2')); + await expect(fetchSessionPromptActivity('tok', 'org-1', 'a-1')).rejects.toThrow('workspace mismatch'); + fetchMock.mockResolvedValueOnce(jsonResponse({}, 500)); + await expect(fetchSessionPromptActivity('tok', 'org-1', 'a-1')).rejects.toThrow('unavailable'); + }); + }); }); From 27fceaf2be33e0d5f658b0d004648f977c6659e2 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 01:37:18 +0000 Subject: [PATCH 23/27] fix(admission): announce each queue heartbeat mark once, however runs are spaced The heartbeat fired when age % 900 < 60, which holds only when pickup runs are exactly 60 s apart: runs at 898 s and 961 s skipped the mark. Each mark (whole 15-minute periods queued) is now claimed with a conditional write of queue_heartbeat_mark on the still-QUEUED task, and only the run that claims it emits the event. --- cdk/src/handlers/reconcile-admission-queue.ts | 51 +++++++++++++++---- .../reconcile-admission-queue.test.ts | 43 +++++++++++++--- 2 files changed, 75 insertions(+), 19 deletions(-) diff --git a/cdk/src/handlers/reconcile-admission-queue.ts b/cdk/src/handlers/reconcile-admission-queue.ts index 6a23af582..efc61820b 100644 --- a/cdk/src/handlers/reconcile-admission-queue.ts +++ b/cdk/src/handlers/reconcile-admission-queue.ts @@ -356,28 +356,57 @@ async function expireQueuedTask(task: QueuedTask): Promise { /** How often a task still waiting in the queue re-announces itself. */ const QUEUE_HEARTBEAT_MINUTES = 15; const QUEUE_HEARTBEAT_SECONDS = QUEUE_HEARTBEAT_MINUTES * 60; -/** The pickup schedule's interval (the default; see AdmissionQueuePickup). */ -const PICKUP_INTERVAL_SECONDS = 60; /** - * True when a task queued for ``ageSeconds`` crossed another heartbeat mark in the - * last pickup interval, so each mark fires once on a 1-minute schedule. + * The heartbeat mark a task queued for ``ageSeconds`` has reached: 0 before the first + * 15 minutes, then 1, 2, ... A mark fires once, whenever the first pickup run past it + * claims it, so runs that drift or skip never miss one. * @param ageSeconds - how long the task has been queued. */ -export function isQueueHeartbeatDue(ageSeconds: number): boolean { - return ageSeconds >= QUEUE_HEARTBEAT_SECONDS && ageSeconds % QUEUE_HEARTBEAT_SECONDS < PICKUP_INTERVAL_SECONDS; +export function queueHeartbeatMark(ageSeconds: number): number { + return Math.floor(ageSeconds / QUEUE_HEARTBEAT_SECONDS); } /** - * Re-emit ``admission_queued`` (with ``waited_s``) for tasks that stay queued past a - * heartbeat mark (#1066). A Linear agent session shows it as "Still queued (N min so - * far)", and the activity keeps a long wait from turning the session stale. Best effort - * (``emitEvent`` logs and swallows a failed write). + * Record that ``mark`` was announced, if no run has yet. False when it already was, or + * the task left the queue in the meantime. + */ +async function claimQueueHeartbeat(taskId: string, mark: number): Promise { + try { + await ddb.send(new UpdateItemCommand({ + TableName: TASK_TABLE, + Key: { task_id: { S: taskId } }, + UpdateExpression: 'SET queue_heartbeat_mark = :mark', + ConditionExpression: '#s = :queued AND (attribute_not_exists(queue_heartbeat_mark) OR queue_heartbeat_mark < :mark)', + ExpressionAttributeNames: { '#s': 'status' }, + ExpressionAttributeValues: { ':mark': { N: String(mark) }, ':queued': { S: 'QUEUED' } }, + })); + return true; + } catch (err) { + if ((err as { name?: string }).name === 'ConditionalCheckFailedException') return false; + throw err; + } +} + +/** + * Re-emit ``admission_queued`` (with ``waited_s``) once per heartbeat mark for tasks + * still queued (#1066). A Linear agent session shows it as "Still queued (N min so + * far)", and the activity keeps a long wait from turning the session stale. Best + * effort: a failed claim is logged and the next run tries the mark again. * @param waiting - tasks this cycle leaves in the queue. */ async function emitQueueHeartbeats(waiting: readonly QueuedTask[]): Promise { for (const task of waiting) { - if (!isQueueHeartbeatDue(task.age_seconds)) continue; + const mark = queueHeartbeatMark(task.age_seconds); + if (mark < 1) continue; + try { + if (!await claimQueueHeartbeat(task.task_id, mark)) continue; + } catch (err) { + logger.warn('Queue heartbeat claim failed; the next run retries it', { + task_id: task.task_id, error: err instanceof Error ? err.message : String(err), + }); + continue; + } await emitEvent(task.task_id, 'admission_queued', { reason: { S: 'concurrency_limit' }, waited_s: { N: String(Math.floor(task.age_seconds)) }, diff --git a/cdk/test/handlers/reconcile-admission-queue.test.ts b/cdk/test/handlers/reconcile-admission-queue.test.ts index 60342286c..9f2209c78 100644 --- a/cdk/test/handlers/reconcile-admission-queue.test.ts +++ b/cdk/test/handlers/reconcile-admission-queue.test.ts @@ -47,7 +47,7 @@ process.env.MAX_CONCURRENT_TASKS_PER_USER = '3'; process.env.QUEUE_MAX_AGE_SECONDS = '86400'; process.env.TASK_RETENTION_DAYS = '90'; -import { handler, isQueueHeartbeatDue } from '../../src/handlers/reconcile-admission-queue'; +import { handler, queueHeartbeatMark } from '../../src/handlers/reconcile-admission-queue'; /** A QUEUED StatusIndex row as the DDB low-level client returns it. */ function queuedRow(opts: { @@ -483,13 +483,40 @@ describe('reconcile-admission-queue — #331 regression (fan-out burst)', () => }); describe('reconcile-admission-queue — queue heartbeat (#1066)', () => { - test('each 15-minute mark fires once on the 1-minute schedule', () => { - expect(isQueueHeartbeatDue(0)).toBe(false); - expect(isQueueHeartbeatDue(899)).toBe(false); - expect(isQueueHeartbeatDue(900)).toBe(true); - expect(isQueueHeartbeatDue(959)).toBe(true); - expect(isQueueHeartbeatDue(960)).toBe(false); - expect(isQueueHeartbeatDue(1800)).toBe(true); + test('the mark counts whole 15-minute periods queued', () => { + expect([0, 899, 900, 1799, 1800, 2700].map(queueHeartbeatMark)).toEqual([0, 0, 1, 1, 2, 3]); + }); + + /** A full queue for user u1 with one task queued for ``age`` seconds; ``claim`` scripts the mark's conditional write. */ + function fullQueue(age: number, claim: () => Promise = () => Promise.resolve({})): void { + mockDdbSend.mockImplementation((cmd: SentCommand) => { + if (cmd._type === 'Query') return Promise.resolve({ Items: [queuedRow({ task_id: 'LONG', user_id: 'u1', created_at: isoAge(age) })] }); + if (cmd._type === 'GetItem') return Promise.resolve({ Item: { active_count: { N: '3' } } }); + if (cmd._type === 'UpdateItem' && cmd.input.UpdateExpression === 'SET queue_heartbeat_mark = :mark') return claim(); + return Promise.resolve({}); + }); + } + const announced = () => sentDdbCommands('PutItem').map(c => c.input.Item).filter(i => i.event_type.S === 'admission_queued'); + + test('a mark is announced by the first run past it, even when runs drift past the minute after it', async () => { + fullQueue(961); + await handler(); + expect(announced()).toHaveLength(1); + const claim = sentDdbCommands('UpdateItem').find(c => c.input.UpdateExpression === 'SET queue_heartbeat_mark = :mark')!; + expect(claim.input.ExpressionAttributeValues[':mark']).toEqual({ N: '1' }); + expect(claim.input.ConditionExpression).toContain('#s = :queued'); + }); + + test('a mark already announced (the conditional write fails) is not announced again', async () => { + fullQueue(1000, () => Promise.reject(Object.assign(new Error('claimed'), { name: 'ConditionalCheckFailedException' }))); + await handler(); + expect(announced()).toEqual([]); + }); + + test('a claim that fails for another reason sends nothing and does not fail the run', async () => { + fullQueue(1000, () => Promise.reject(new Error('throttled'))); + await expect(handler()).resolves.toEqual(expect.objectContaining({ queued_seen: 1 })); + expect(announced()).toEqual([]); }); test('a task still waiting past a mark gets an admission_queued event with waited_s', async () => { From 4f5d7c4e7414ff345e73978660f9942bc4d6145c Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 02:06:27 +0000 Subject: [PATCH 24/27] fix(linear): an approval button decides only the request it was shown with The buttons carried only the decision, and the reply was applied to whichever request the task was awaiting. An older choice clicked late (the request answered elsewhere and a new one opened) would decide the new request, which the person never saw. Each button value now names its request ("approve request "), the handler rejects an answer whose request is no longer the open one and shows the current choice, and the Linear read-back compares the request too. Typed answers carry no id and apply to the open request. The repeated choice keeps Approve for this task when the request matched one rule. --- .../shared/linear-agent-session-handler.ts | 23 ++++--- .../shared/linear-session-approval.ts | 60 +++++++++++-------- .../linear-agent-session-handler.test.ts | 26 +++++--- .../shared/linear-session-approval.test.ts | 22 +++++-- 4 files changed, 86 insertions(+), 45 deletions(-) diff --git a/cdk/src/handlers/shared/linear-agent-session-handler.ts b/cdk/src/handlers/shared/linear-agent-session-handler.ts index 746529320..b95ec0056 100644 --- a/cdk/src/handlers/shared/linear-agent-session-handler.ts +++ b/cdk/src/handlers/shared/linear-agent-session-handler.ts @@ -511,7 +511,7 @@ async function decideSessionApproval( accessToken: string, ): Promise { const again = async (lead: string) => { - const activity = repeatedApprovalChoice(lead); + const activity = repeatedApprovalChoice(lead, requestId, await requestRuleIds(task.task_id, requestId)); await emit(activity.content, false, activity); }; const answer = parseSessionApprovalAnswer(request.directive); @@ -519,6 +519,12 @@ async function decideSessionApproval( await again('That isn\'t an answer to the open approval request, so I haven\'t passed it to the agent.'); return; } + // A button names the request it was shown with; an older choice clicked late must + // not decide the request that is open now. + if (answer.requestId && answer.requestId !== requestId) { + await again('That answer was for an earlier request, which is no longer open, so nothing was decided.'); + return; + } if (task.user_id !== platformUserId) { await again(`Only the task owner can decide this request. ${NOT_OWNER_MESSAGE}`); return; @@ -539,7 +545,8 @@ async function decideSessionApproval( const record = answer.decision === 'approve' ? (await import('../approve-task.js')).recordApprovalForUser : (await import('../deny-task.js')).recordDenialForUser; - const ruleScope = answer.wholeTask ? await singleRuleScope(task.task_id, requestId) : undefined; + const ruleIds = answer.wholeTask ? await requestRuleIds(task.task_id, requestId) : []; + const ruleScope = ruleIds.length === 1 ? `rule:${ruleIds[0]}` : undefined; const result = await record({ userId: platformUserId, taskId: task.task_id, @@ -574,19 +581,17 @@ async function promptConfirmed( const echoed = prompt ? parseSessionApprovalAnswer(prompt.body) : null; return prompt?.sessionId === request.sessionId && prompt.authorId === request.actorId && echoed?.decision === answer.decision && (echoed.reason ?? '') === (answer.reason ?? '') - && Boolean(echoed.wholeTask) === Boolean(answer.wholeTask); + && Boolean(echoed.wholeTask) === Boolean(answer.wholeTask) && echoed.requestId === answer.requestId; } -/** - * ``rule:`` when the request matched exactly one rule, else undefined (approve - * this call only). Read consistently from the request row, never from the reply. - */ -async function singleRuleScope(taskId: string, requestId: string): Promise { +/** The rules the request matched, read consistently from its row, never from the reply. */ +async function requestRuleIds(taskId: string, requestId: string): Promise { + if (!TASK_APPROVALS_TABLE_NAME) return []; const { Item } = await ddb.send(new GetCommand({ TableName: TASK_APPROVALS_TABLE_NAME, Key: { task_id: taskId, request_id: requestId }, ConsistentRead: true, })); const ids: unknown[] = Array.isArray(Item?.matching_rule_ids) ? Item.matching_rule_ids : []; - return ids.length === 1 && typeof ids[0] === 'string' ? `rule:${ids[0]}` : undefined; + return ids.filter((id): id is string => typeof id === 'string'); } /** The prior task as read from the base table (strongly consistent). */ diff --git a/cdk/src/handlers/shared/linear-session-approval.ts b/cdk/src/handlers/shared/linear-session-approval.ts index d76e19d3e..be4c992fa 100644 --- a/cdk/src/handlers/shared/linear-session-approval.ts +++ b/cdk/src/handlers/shared/linear-session-approval.ts @@ -34,25 +34,31 @@ import { approvalNotificationMarkdown, type ApprovalNotification } from './appro import type { AgentActivityContent } from './linear-agent-session'; import { parseLinearApprovalReply, type LinearApprovalReply } from './linear-approval-thread'; -/** The buttons. Their values are what the session sends back as the prompt, and what the reply parser reads. */ -export const SESSION_APPROVAL_OPTIONS: ReadonlyArray<{ readonly label: string; readonly value: string }> = [ - { label: 'Approve', value: 'approve' }, - { label: 'Deny', value: 'deny' }, -]; - -/** Shown only for a request that matched exactly one rule (see {@link sessionApprovalActivity}). */ -const APPROVE_FOR_TASK_OPTION = { label: 'Approve for this task', value: 'approve for this task' } as const; +/** + * An answer from the session: approve once, approve the request's rule for the rest + * of the task, or deny. ``requestId`` is set when the answer came from a button, + * which names the request it was shown with. + */ +export type SessionApprovalAnswer = LinearApprovalReply & { readonly wholeTask?: boolean; readonly requestId?: string }; -/** An answer from the session: approve once, approve the request's rule for the rest of the task, or deny. */ -export type SessionApprovalAnswer = LinearApprovalReply & { readonly wholeTask?: boolean }; +/** A button value names its request: ``approve request ``. Request ids are ULIDs. */ +const BUTTON_REQUEST = /^(approve|approve for this task|deny) request ([0-9A-HJKMNP-TV-Z]{26})$/i; +const WHOLE_TASK = /^approve\s+for\s+(?:this|the)\s+(?:whole\s+)?task[.!]?$/i; /** - * A reply that answers an approval request, or null. ``approve for this task`` (the - * button's value, or typed) approves the request's rule for the rest of the task. + * A reply that answers an approval request, or null: a button's value, or a typed + * ``approve``, ``approve for this task`` or ``deny [reason]``. * @param text - the reply. */ export function parseSessionApprovalAnswer(text: string): SessionApprovalAnswer | null { - if (/^approve\s+for\s+(?:this|the)\s+(?:whole\s+)?task[.!]?$/i.test(text.trim())) return { decision: 'approve', wholeTask: true }; + const trimmed = text.trim(); + const button = BUTTON_REQUEST.exec(trimmed); + if (button) { + const verb = button[1].toLowerCase(); + return verb === 'deny' ? { decision: 'deny', requestId: button[2] } + : { decision: 'approve', requestId: button[2], ...(verb !== 'approve' && { wholeTask: true }) }; + } + if (WHOLE_TASK.test(trimmed)) return { decision: 'approve', wholeTask: true }; return parseLinearApprovalReply(text); } @@ -120,15 +126,19 @@ export function waitingOnYouLine(deadline: string | undefined, now: Date = new D } /** - * The buttons, as ``emitAgentActivity`` options. "Approve for this task" is offered - * only when the request matched exactly one rule: the agent treats a rule approval - * as covering any later request that rule is among, so approving one of several - * matched rules would also wave through requests the other rules raise. + * The buttons for one request, as ``emitAgentActivity`` options. Each value names the + * request, so a click on an older choice cannot decide a later request. "Approve for + * this task" is offered only when the request matched exactly one rule: the agent + * treats a rule approval as covering any later request that rule is among, so + * approving one of several matched rules would also pass requests the others raise. */ -function choice(body: string, ruleIds?: readonly string[]): SessionApprovalActivity { - const options = ruleIds?.length === 1 - ? [SESSION_APPROVAL_OPTIONS[0], APPROVE_FOR_TASK_OPTION, SESSION_APPROVAL_OPTIONS[1]] - : SESSION_APPROVAL_OPTIONS; +function choice(body: string, requestId: string, ruleIds?: readonly string[]): SessionApprovalActivity { + const option = (label: string, verb: string) => ({ label, value: `${verb} request ${requestId}` }); + const options = [ + option('Approve', 'approve'), + ...(ruleIds?.length === 1 ? [option('Approve for this task', 'approve for this task')] : []), + option('Deny', 'deny'), + ]; return { content: { type: 'elicitation', body }, signal: 'select', signalMetadata: { options } }; } @@ -144,7 +154,7 @@ export function sessionApprovalActivity( ): SessionApprovalActivity { const body = approvalNotificationMarkdown(notification); if (eventType === 'approval_requested') { - return choice(`${body}\n\n${waitingOnYouLine(notification.deadline, now)}`, notification.ruleIds); + return choice(`${body}\n\n${waitingOnYouLine(notification.deadline, now)}`, notification.requestId, notification.ruleIds); } return { content: { type: 'thought', body } }; } @@ -154,9 +164,11 @@ export function sessionApprovalActivity( * request, so the request stays the session's last activity and Linear keeps * showing the session as waiting for input. * @param lead - why it is shown again. + * @param requestId - the open request. + * @param ruleIds - the rules it matched, when known. */ -export function repeatedApprovalChoice(lead: string): SessionApprovalActivity { - return choice(`${lead}\n\nChoose **Approve** or **Deny**, or reply deny with a reason.`); +export function repeatedApprovalChoice(lead: string, requestId: string, ruleIds?: readonly string[]): SessionApprovalActivity { + return choice(`${lead}\n\nChoose **Approve** or **Deny**, or reply deny with a reason.`, requestId, ruleIds); } /** What the decision handlers return. */ diff --git a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts index 611982415..d84a251ef 100644 --- a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts +++ b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts @@ -811,10 +811,11 @@ describe('channel_metadata builders', () => { }); describe('handleAgentSessionEvent — approval requests in the session (#1066)', () => { + const OPEN = '01M89PC2Y1YDH7SJEVVYR0VCAX'; const waiting = (user = 'platform-user-1') => priorTask({ task_id: 't-1', status: 'AWAITING_APPROVAL', - awaiting_approval_request_id: 'req-1', + awaiting_approval_request_id: OPEN, user_id: user, linear_workspace_id: 'org-1', session: 'session-1', @@ -839,7 +840,7 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', userId: 'platform-user-1', taskId: 't-1', decisionSource: JSON.stringify(['linear_session', 'org-1', 'activity-9']), - body: JSON.stringify({ request_id: 'req-1', decision: 'approve' }), + body: JSON.stringify({ request_id: OPEN, decision: 'approve' }), }); expect(submitNudgeMock).not.toHaveBeenCalled(); expect(lastEmit()[2]).toEqual({ type: 'thought', body: 'Approved. The agent continues with this action.' }); @@ -848,7 +849,7 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', test('a deny with a reason passes the reason on', async () => { waiting(); await answer('deny use the staging config'); - expect(JSON.parse(recordDenialMock.mock.calls[0][0].body)).toEqual({ request_id: 'req-1', decision: 'deny', reason: 'use the staging config' }); + expect(JSON.parse(recordDenialMock.mock.calls[0][0].body)).toEqual({ request_id: OPEN, decision: 'deny', reason: 'use the staging config' }); expect(String(lastEmit()[2].body)).toContain('your reason: use the staging config'); }); @@ -879,17 +880,17 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', test('"Approve for this task" approves the request\'s one rule for the rest of the task', async () => { waiting(); - approvalRow = { task_id: 't-1', request_id: 'req-1', matching_rule_ids: ['write_env_files'] }; + approvalRow = { task_id: 't-1', request_id: OPEN, matching_rule_ids: ['write_env_files'] }; await answer('approve for this task'); - expect(JSON.parse(recordApprovalMock.mock.calls[0][0].body)).toEqual({ request_id: 'req-1', decision: 'approve', scope: 'rule:write_env_files' }); + expect(JSON.parse(recordApprovalMock.mock.calls[0][0].body)).toEqual({ request_id: OPEN, decision: 'approve', scope: 'rule:write_env_files' }); expect(String(lastEmit()[2].body)).toContain('won\'t ask again for `rule:write_env_files`'); }); test('a whole-task answer to a request that matched several rules approves this action only', async () => { waiting(); - approvalRow = { task_id: 't-1', request_id: 'req-1', matching_rule_ids: ['force_push_any', 'force_push_main'] }; + approvalRow = { task_id: 't-1', request_id: OPEN, matching_rule_ids: ['force_push_any', 'force_push_main'] }; await answer('approve for this task'); - expect(JSON.parse(recordApprovalMock.mock.calls[0][0].body)).toEqual({ request_id: 'req-1', decision: 'approve' }); + expect(JSON.parse(recordApprovalMock.mock.calls[0][0].body)).toEqual({ request_id: OPEN, decision: 'approve' }); expect(String(lastEmit()[2].body)).toMatch(/^Approved this action only/); }); @@ -920,6 +921,17 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', expect(lastEmit()[2]).toEqual(expect.objectContaining({ type: 'thought', body: expect.stringContaining('Nothing is waiting') })); }); + test('a button from an earlier request decides nothing; the current request\'s button does', async () => { + waiting(); + await answer('approve request 01M89PAAAAAAAAAAAAAAAAAAAA'); + expect(recordApprovalMock).not.toHaveBeenCalled(); + expect(String(lastEmit()[2].body)).toMatch(/^That answer was for an earlier request/); + expect(lastEmit()[3]).toEqual(expect.objectContaining({ signal: 'select' })); + + await answer(`deny request ${OPEN}`); + expect(JSON.parse(recordDenialMock.mock.calls[0][0].body)).toEqual({ request_id: OPEN, decision: 'deny' }); + }); + test('a reply Linear does not hold as written decides nothing (a forged webhook)', async () => { waiting(); for (const held of [ diff --git a/cdk/test/handlers/shared/linear-session-approval.test.ts b/cdk/test/handlers/shared/linear-session-approval.test.ts index 9e8dc43ba..20dda4c64 100644 --- a/cdk/test/handlers/shared/linear-session-approval.test.ts +++ b/cdk/test/handlers/shared/linear-session-approval.test.ts @@ -22,18 +22,19 @@ import { formatDeadline, parseSessionApprovalAnswer, repeatedApprovalChoice, - SESSION_APPROVAL_OPTIONS, sessionApprovalActivity, sessionDecisionNote, waitingOnYouLine, } from '../../../src/handlers/shared/linear-session-approval'; const NOW = new Date('2026-11-25T21:10:00Z'); +const REQ = '01M89PC2Y1YDH7SJEVVYR0VCAX'; +const values = (a: { signalMetadata?: unknown }) => (a.signalMetadata as { options: Array<{ label: string; value: string }> }).options; const notice = (deadline?: string): ApprovalNotification => ({ title: 'Approval needed', text: 'Approval needed\nThe agent wants to run a shell command.', taskId: 't-1', - requestId: 'r-1', + requestId: REQ, userId: 'u-1', marker: 'notified_linear_session_approval_requested', ...(deadline && { deadline }), @@ -55,8 +56,11 @@ test('a pending request is a choice with Approve / Deny buttons and the waiting const a = sessionApprovalActivity('approval_requested', notice('2026-11-25T21:40:00Z'), NOW); expect(a.content.type).toBe('elicitation'); expect(a.signal).toBe('select'); - expect(a.signalMetadata).toEqual({ options: SESSION_APPROVAL_OPTIONS }); - expect(SESSION_APPROVAL_OPTIONS.map((o) => o.value)).toEqual(['approve', 'deny']); + // Each button names its request, so a late click on it cannot decide a later one. + expect(values(a)).toEqual([ + { label: 'Approve', value: `approve request ${REQ}` }, + { label: 'Deny', value: `deny request ${REQ}` }, + ]); const body = (a.content as { body: string }).body; expect(body).toContain('The agent wants to run a shell command.'); expect(body.endsWith('Reply by 21:40 UTC (in 30 min), or it is denied and the agent carries on without it.')).toBe(true); @@ -71,7 +75,8 @@ test('a decision, timeout or stranded wait is a note without buttons', () => { }); test('the repeated choice keeps the buttons', () => { - const a = repeatedApprovalChoice('Only the task owner can decide this request.'); + const a = repeatedApprovalChoice('Only the task owner can decide this request.', REQ, ['write_env_files']); + expect(values(a).map((o) => o.label)).toEqual(['Approve', 'Approve for this task', 'Deny']); expect(a.content).toEqual({ type: 'elicitation', body: expect.stringMatching(/^Only the task owner can decide this request\./) }); expect(a.signal).toBe('select'); }); @@ -106,3 +111,10 @@ test('the note says what a whole-task approval covered', () => { .toBe('Approved for the rest of this task: the agent won\'t ask again for `rule:write_env_files`.'); expect(sessionDecisionNote({ decision: 'approve', wholeTask: true }, { statusCode: 202 })).toMatch(/^Approved this action only/); }); + +test('a button value carries its request; typed answers do not', () => { + expect(parseSessionApprovalAnswer(`approve request ${REQ}`)).toEqual({ decision: 'approve', requestId: REQ }); + expect(parseSessionApprovalAnswer(`approve for this task request ${REQ}`)).toEqual({ decision: 'approve', requestId: REQ, wholeTask: true }); + expect(parseSessionApprovalAnswer(`deny request ${REQ}`)).toEqual({ decision: 'deny', requestId: REQ }); + expect(parseSessionApprovalAnswer('deny request a refund')).toEqual({ decision: 'deny', reason: 'request a refund' }); +}); From 10183e47369542edd3bc5527065a768946c6d3a7 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 02:07:17 +0000 Subject: [PATCH 25/27] fix(linear): a finished session task moves its issue only to a state named In Review transitionIssueState falls back to the team's first started state when the preferred name is missing, so on a team without In Review an issue moved back to Backlog would be pushed to In Progress when the PR opened. A new requirePreferredName option makes the move happen only to a state with that name; the session's In Review move uses it. --- cdk/src/handlers/fanout-task-events.ts | 2 +- cdk/src/handlers/shared/linear-feedback.ts | 14 +++++++++++--- .../fanout-linear-session-progress.test.ts | 2 +- cdk/test/handlers/shared/linear-feedback.test.ts | 7 +++++++ 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/cdk/src/handlers/fanout-task-events.ts b/cdk/src/handlers/fanout-task-events.ts index 58a81e5ab..690617a79 100644 --- a/cdk/src/handlers/fanout-task-events.ts +++ b/cdk/src/handlers/fanout-task-events.ts @@ -1860,7 +1860,7 @@ async function moveSessionIssueToReview(task: TaskRecord, ctx: LinearFeedbackCon const issueId = task.channel_metadata?.linear_issue_id; if (!issueId) return; try { - await transitionIssueState(ctx, issueId, 'started', ['In Review']); + await transitionIssueState(ctx, issueId, 'started', ['In Review'], false, true); } catch (err) { logger.warn('[fanout/linear-session] could not move the issue to In Review (best effort)', { task_id: task.task_id, error: err instanceof Error ? err.message : String(err), diff --git a/cdk/src/handlers/shared/linear-feedback.ts b/cdk/src/handlers/shared/linear-feedback.ts index e1b6e7b7f..ae84b0259 100644 --- a/cdk/src/handlers/shared/linear-feedback.ts +++ b/cdk/src/handlers/shared/linear-feedback.ts @@ -911,6 +911,7 @@ function pickState( states: readonly TeamState[], type: string, preferredNames: readonly string[], + requirePreferredName: boolean, ): TeamState | null { const ofType = states.filter((s) => s.type === type); if (ofType.length === 0) return null; @@ -918,6 +919,7 @@ function pickState( const hit = ofType.find((s) => s.name.toLowerCase() === name.toLowerCase()); if (hit) return hit; } + if (requirePreferredName) return null; return [...ofType].sort((a, b) => a.position - b.position)[0]; } @@ -950,6 +952,12 @@ export async function transitionIssueState( * still ALWAYS blocked — this only relaxes the same-type position tiebreak. */ allowSameTypeRegression = false, + /** + * Move only to a state named in ``preferredNames``. Without it a team that lacks + * the name gets its first state of ``targetType``, which for "In Review" is "In + * Progress": the wrong move for a caller that means review specifically. + */ + requirePreferredName = false, ): Promise { const token = await resolveToken(ctx); if (!token) return false; @@ -964,7 +972,7 @@ export async function transitionIssueState( return false; } - const target = pickState(states, targetType, preferredNames); + const target = pickState(states, targetType, preferredNames, requirePreferredName); if (!target) { logger.warn('Linear state transition: no state of target type', { issue_id: issueId, target_type: targetType }); return false; @@ -1059,8 +1067,8 @@ export async function revertIssueToNotStarted( // Prefer an unstarted "Todo" (the natural "not started, waiting" state); fall // back to backlog. Within a type, prefer the named state, else lowest position. - const target = pickState(states, 'unstarted', ['Todo', 'To Do']) - ?? pickState(states, 'backlog', ['Backlog', 'Triage']); + const target = pickState(states, 'unstarted', ['Todo', 'To Do'], false) + ?? pickState(states, 'backlog', ['Backlog', 'Triage'], false); if (!target) { logger.info('Revert-to-not-started: no unstarted/backlog state on the team — leaving it', { issue_id: issueId }); return false; diff --git a/cdk/test/handlers/fanout-linear-session-progress.test.ts b/cdk/test/handlers/fanout-linear-session-progress.test.ts index ec19377e7..e54cb64e4 100644 --- a/cdk/test/handlers/fanout-linear-session-progress.test.ts +++ b/cdk/test/handlers/fanout-linear-session-progress.test.ts @@ -238,7 +238,7 @@ test('a task that ends with a pull request completes the checklist, says what is const final = mockEmitAgentActivity.mock.calls.at(-1)?.[2] as { type: string; body: string }; expect(final.type).toBe('response'); expect(final.body).toMatch(/_Your turn: review the pull request\. Reply here if it needs changes\._$/); - expect(mockTransitionIssueState).toHaveBeenCalledWith(expect.anything(), 'issue-1', 'started', ['In Review']); + expect(mockTransitionIssueState).toHaveBeenCalledWith(expect.anything(), 'issue-1', 'started', ['In Review'], false, true); }); test('a failed task cancels what was left, offers a retry, and leaves the issue where it is', async () => { diff --git a/cdk/test/handlers/shared/linear-feedback.test.ts b/cdk/test/handlers/shared/linear-feedback.test.ts index 4e22e88d4..571a6228c 100644 --- a/cdk/test/handlers/shared/linear-feedback.test.ts +++ b/cdk/test/handlers/shared/linear-feedback.test.ts @@ -575,6 +575,13 @@ describe('linear-feedback', () => { expect(JSON.parse(fetchMock.mock.calls[1][1].body).variables.stateId).toBe('s-inreview'); }); + test('a strict name: a team without "In Review" gets no move, not its first started state', async () => { + const noReview = TEAM_STATES.filter((st) => st.id !== 's-inreview'); + fetchMock.mockResolvedValueOnce(jsonResponse({ data: { issue: { state: cur('s-backlog'), team: { states: { nodes: noReview } } } } })); + expect(await transitionIssueState(CTX, ISSUE_ID, 'started', ['In Review'], false, true)).toBe(false); + expect(fetchMock).toHaveBeenCalledTimes(1); // the query only, no issueUpdate + }); + test('already in target state → no mutation, returns false', async () => { fetchMock.mockResolvedValueOnce(statesResp(cur('s-inreview'))); const ok = await transitionIssueState(CTX, ISSUE_ID, 'started', ['In Review']); From 366465128dab5747c3c5dcc4dd1873691b75f979 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 02:56:26 +0000 Subject: [PATCH 26/27] fix(linear): a session answer decides only the request open when it was written Buttons named their request, but a typed approve or deny still resolved against whichever request the task was awaiting when the delivery was processed. The processor is invoked asynchronously and retried, and the Linear read-back throws on a lookup failure so it retries; a retry that ran after the request closed and another opened would decide the newer one. The read-back now returns the prompt's createdAt, and an answer written before the open request was created decides nothing. A retried activity therefore cannot decide a later request, and against the same request the decision path already answers 409. --- .../shared/linear-agent-session-handler.ts | 45 +++++++++++++------ .../handlers/shared/linear-agent-session.ts | 6 ++- .../linear-agent-session-handler.test.ts | 37 ++++++++++----- .../shared/linear-agent-session.test.ts | 10 ++++- 4 files changed, 71 insertions(+), 27 deletions(-) diff --git a/cdk/src/handlers/shared/linear-agent-session-handler.ts b/cdk/src/handlers/shared/linear-agent-session-handler.ts index b95ec0056..be9a16888 100644 --- a/cdk/src/handlers/shared/linear-agent-session-handler.ts +++ b/cdk/src/handlers/shared/linear-agent-session-handler.ts @@ -30,6 +30,7 @@ import { emitAgentActivity, fetchAgentSessionIssue, fetchSessionPromptActivity, + type SessionPromptActivity, type AgentActivityContent, type AgentSessionIssue, } from './linear-agent-session'; @@ -511,7 +512,7 @@ async function decideSessionApproval( accessToken: string, ): Promise { const again = async (lead: string) => { - const activity = repeatedApprovalChoice(lead, requestId, await requestRuleIds(task.task_id, requestId)); + const activity = repeatedApprovalChoice(lead, requestId, (await readOpenRequest(task.task_id, requestId)).ruleIds); await emit(activity.content, false, activity); }; const answer = parseSessionApprovalAnswer(request.directive); @@ -533,19 +534,28 @@ async function decideSessionApproval( await emit({ type: 'thought', body: 'Approvals can\'t be answered in Linear on this deployment. Use `bgagent approve` / `bgagent deny`.' }); return; } - if (!await promptConfirmed(request, answer, accessToken)) { + const prompt = await confirmedPrompt(request, answer, accessToken); + if (!prompt) { logger.warn('Agent-session approval reply not confirmed by Linear — no decision recorded', { linear_agent_session_id: request.sessionId, task_id: task.task_id, request_id: requestId, }); await again('I couldn\'t confirm this answer with Linear, so nothing was decided.'); return; } + // An answer belongs to the request that was open when it was written. A delivery + // retried after that request closed and another opened (an async retry, a + // read-back that failed and retried) must not decide the newer one. + const open = await readOpenRequest(task.task_id, requestId); + if (open.openedAtMs === undefined || !(Date.parse(prompt.createdAt) >= open.openedAtMs)) { + await again('That answer was written before this request opened, so nothing was decided.'); + return; + } // Loaded only when a session decides: other session deliveries do not need the // decision handlers' environment. const record = answer.decision === 'approve' ? (await import('../approve-task.js')).recordApprovalForUser : (await import('../deny-task.js')).recordDenialForUser; - const ruleIds = answer.wholeTask ? await requestRuleIds(task.task_id, requestId) : []; + const ruleIds = answer.wholeTask ? open.ruleIds : []; const ruleScope = ruleIds.length === 1 ? `rule:${ruleIds[0]}` : undefined; const result = await record({ userId: platformUserId, @@ -570,28 +580,37 @@ async function decideSessionApproval( } /** - * True when Linear holds this delivery as a human's prompt in this session, from the - * same person, with the same answer. The decision is consent, so it is taken from - * Linear's copy, not the webhook's (see ``fetchSessionPromptActivity``). + * Linear's copy of this delivery when it is a human's prompt in this session, from + * the same person, with the same answer; else null. The decision is consent, so it + * is taken from Linear's copy, not the webhook's (see ``fetchSessionPromptActivity``). */ -async function promptConfirmed( +async function confirmedPrompt( request: AgentSessionRequest, answer: SessionApprovalAnswer, accessToken: string, -): Promise { +): Promise { const prompt = await fetchSessionPromptActivity(accessToken, request.workspaceId, request.deliveryId); const echoed = prompt ? parseSessionApprovalAnswer(prompt.body) : null; - return prompt?.sessionId === request.sessionId && prompt.authorId === request.actorId + const same = prompt?.sessionId === request.sessionId && prompt.authorId === request.actorId && echoed?.decision === answer.decision && (echoed.reason ?? '') === (answer.reason ?? '') && Boolean(echoed.wholeTask) === Boolean(answer.wholeTask) && echoed.requestId === answer.requestId; + return same ? prompt : null; } -/** The rules the request matched, read consistently from its row, never from the reply. */ -async function requestRuleIds(taskId: string, requestId: string): Promise { - if (!TASK_APPROVALS_TABLE_NAME) return []; +/** + * The open request's matched rules and when it opened, read consistently from its + * row, never from the reply. ``openedAtMs`` is undefined when the row has no + * readable ``created_at``, which the caller treats as not decidable. + */ +async function readOpenRequest(taskId: string, requestId: string): Promise<{ ruleIds: string[]; openedAtMs?: number }> { + if (!TASK_APPROVALS_TABLE_NAME) return { ruleIds: [] }; const { Item } = await ddb.send(new GetCommand({ TableName: TASK_APPROVALS_TABLE_NAME, Key: { task_id: taskId, request_id: requestId }, ConsistentRead: true, })); const ids: unknown[] = Array.isArray(Item?.matching_rule_ids) ? Item.matching_rule_ids : []; - return ids.filter((id): id is string => typeof id === 'string'); + const openedAtMs = typeof Item?.created_at === 'string' ? Date.parse(Item.created_at) : NaN; + return { + ruleIds: ids.filter((id): id is string => typeof id === 'string'), + ...(Number.isFinite(openedAtMs) && { openedAtMs }), + }; } /** The prior task as read from the base table (strongly consistent). */ diff --git a/cdk/src/handlers/shared/linear-agent-session.ts b/cdk/src/handlers/shared/linear-agent-session.ts index d2c7ef5fd..84faf6063 100644 --- a/cdk/src/handlers/shared/linear-agent-session.ts +++ b/cdk/src/handlers/shared/linear-agent-session.ts @@ -162,6 +162,8 @@ export interface SessionPromptActivity { readonly sessionId: string; readonly authorId: string; readonly body: string; + /** When the person wrote it (ISO), as Linear records it. */ + readonly createdAt: string; } const SESSION_PROMPT_QUERY = ` @@ -169,6 +171,7 @@ query VerifySessionPrompt($id: String!) { organization { id } viewer { id } agentActivity(id: $id) { + createdAt agentSession { id } content { __typename ... on AgentActivityPromptContent { body } } user { id app } @@ -196,6 +199,7 @@ export async function fetchSessionPromptActivity( organization?: { id?: string }; viewer?: { id?: string }; agentActivity?: { + createdAt?: string; agentSession?: { id?: string } | null; content?: { __typename?: string; body?: string } | null; user?: { id?: string; app?: boolean } | null; @@ -210,7 +214,7 @@ export async function fetchSessionPromptActivity( const sessionId = activity?.agentSession?.id; if (activity?.content?.__typename !== 'AgentActivityPromptContent' || !sessionId || !author?.id || author.app || author.id === viewerId) return null; - return { sessionId, authorId: author.id, body: activity.content.body ?? '' }; + return { sessionId, authorId: author.id, body: activity.content.body ?? '', createdAt: activity.createdAt ?? '' }; } /** Separator + heading that introduces Linear's `promptContext` in the description. */ diff --git a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts index d84a251ef..6d57c1118 100644 --- a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts +++ b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts @@ -812,19 +812,24 @@ describe('channel_metadata builders', () => { describe('handleAgentSessionEvent — approval requests in the session (#1066)', () => { const OPEN = '01M89PC2Y1YDH7SJEVVYR0VCAX'; - const waiting = (user = 'platform-user-1') => priorTask({ - task_id: 't-1', - status: 'AWAITING_APPROVAL', - awaiting_approval_request_id: OPEN, - user_id: user, - linear_workspace_id: 'org-1', - session: 'session-1', - }); + const OPENED = '2026-11-26T10:00:00Z'; + const WRITTEN = '2026-11-26T10:05:00.000Z'; + const waiting = (user = 'platform-user-1') => { + approvalRow = { task_id: 't-1', request_id: OPEN, created_at: OPENED, matching_rule_ids: [] }; + priorTask({ + task_id: 't-1', + status: 'AWAITING_APPROVAL', + awaiting_approval_request_id: OPEN, + user_id: user, + linear_workspace_id: 'org-1', + session: 'session-1', + }); + }; const lastEmit = () => emitAgentActivityMock.mock.calls.at(-1)!; /** Send a prompt that Linear holds as written: the same session, author and body. */ const answer = async (body: string) => { - fetchSessionPromptActivityMock.mockResolvedValue({ sessionId: 'session-1', authorId: 'linear-user-1', body }); + fetchSessionPromptActivityMock.mockResolvedValue({ sessionId: 'session-1', authorId: 'linear-user-1', body, createdAt: WRITTEN }); await handleAgentSessionEvent(prompted({ content: { body } })); }; @@ -880,7 +885,7 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', test('"Approve for this task" approves the request\'s one rule for the rest of the task', async () => { waiting(); - approvalRow = { task_id: 't-1', request_id: OPEN, matching_rule_ids: ['write_env_files'] }; + approvalRow = { ...approvalRow, matching_rule_ids: ['write_env_files'] }; await answer('approve for this task'); expect(JSON.parse(recordApprovalMock.mock.calls[0][0].body)).toEqual({ request_id: OPEN, decision: 'approve', scope: 'rule:write_env_files' }); expect(String(lastEmit()[2].body)).toContain('won\'t ask again for `rule:write_env_files`'); @@ -888,7 +893,7 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', test('a whole-task answer to a request that matched several rules approves this action only', async () => { waiting(); - approvalRow = { task_id: 't-1', request_id: OPEN, matching_rule_ids: ['force_push_any', 'force_push_main'] }; + approvalRow = { ...approvalRow, matching_rule_ids: ['force_push_any', 'force_push_main'] }; await answer('approve for this task'); expect(JSON.parse(recordApprovalMock.mock.calls[0][0].body)).toEqual({ request_id: OPEN, decision: 'approve' }); expect(String(lastEmit()[2].body)).toMatch(/^Approved this action only/); @@ -955,4 +960,14 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', await expect(handleAgentSessionEvent(prompted({ content: { body: 'approve' } }))).rejects.toThrow('verification unavailable'); expect(recordApprovalMock).not.toHaveBeenCalled(); }); + + test('an answer written before the open request was created decides nothing (a delayed retry)', async () => { + waiting(); + fetchSessionPromptActivityMock.mockResolvedValue({ + sessionId: 'session-1', authorId: 'linear-user-1', body: 'approve', createdAt: '2026-11-26T09:58:00.000Z', + }); + await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); + expect(recordApprovalMock).not.toHaveBeenCalled(); + expect(String(lastEmit()[2].body)).toMatch(/^That answer was written before this request opened/); + }); }); diff --git a/cdk/test/handlers/shared/linear-agent-session.test.ts b/cdk/test/handlers/shared/linear-agent-session.test.ts index 47058a451..9e41ea2c5 100644 --- a/cdk/test/handlers/shared/linear-agent-session.test.ts +++ b/cdk/test/handlers/shared/linear-agent-session.test.ts @@ -275,12 +275,18 @@ describe('GraphQL helpers', () => { data: { organization: { id: org }, viewer: { id: 'app-user' }, agentActivity: activity }, }); const prompt = (author: unknown, typename = 'AgentActivityPromptContent') => ({ - agentSession: { id: 's-1' }, content: { __typename: typename, body: 'approve' }, user: null, promptAuthor: author, + createdAt: '2026-11-26T10:05:00.000Z', + agentSession: { id: 's-1' }, + content: { __typename: typename, body: 'approve' }, + user: null, + promptAuthor: author, }); test('a human\'s prompt comes back with its session, author and body', async () => { fetchMock.mockResolvedValueOnce(reply(prompt({ id: 'u-1', app: false }))); - await expect(fetchSessionPromptActivity('tok', 'org-1', 'a-1')).resolves.toEqual({ sessionId: 's-1', authorId: 'u-1', body: 'approve' }); + await expect(fetchSessionPromptActivity('tok', 'org-1', 'a-1')).resolves.toEqual({ + sessionId: 's-1', authorId: 'u-1', body: 'approve', createdAt: '2026-11-26T10:05:00.000Z', + }); expect(sentBody(0).variables).toEqual({ id: 'a-1' }); }); From 183eecdadcb961fc3322eaf4a6256317f55982d5 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 03:09:03 +0000 Subject: [PATCH 27/27] fix(linear): a session answer counts only if Linear recorded it after the request's choice The previous check compared the prompt with the approval row's created_at. That timestamp is written by the worker (untrusted under the approval writer's threat model), rounded to whole seconds, and stamped before the choice appears in the session, so a typed reply meant for a closed request could still decide the next one. Both times now come from Linear: the prompt's createdAt and the createdAt of the request's own choice activity, whose id derives from the request (sessionApprovalNoticeId, shared with the fan-out that posts it). An answer recorded before that choice, or when the choice was never posted in this session, decides nothing. A one-time claim on the activity id is not added: a retried activity can no longer decide a later request, the same request already answers 409, and a claim that lands before a transient decision failure would lose the person's answer. --- cdk/src/handlers/fanout-task-events.ts | 4 +-- .../shared/linear-agent-session-handler.ts | 32 +++++++++---------- .../handlers/shared/linear-agent-session.ts | 27 ++++++++++++++++ .../shared/linear-session-approval.ts | 12 +++++++ .../linear-agent-session-handler.test.ts | 21 ++++++++++-- .../shared/linear-agent-session.test.ts | 12 +++++++ 6 files changed, 86 insertions(+), 22 deletions(-) diff --git a/cdk/src/handlers/fanout-task-events.ts b/cdk/src/handlers/fanout-task-events.ts index 690617a79..0051aada0 100644 --- a/cdk/src/handlers/fanout-task-events.ts +++ b/cdk/src/handlers/fanout-task-events.ts @@ -86,7 +86,7 @@ import { type LinearFeedbackContext, type LinearPostResult, } from './shared/linear-feedback'; -import { sessionApprovalActivity } from './shared/linear-session-approval'; +import { sessionApprovalActivity, sessionApprovalNoticeId } from './shared/linear-session-approval'; import { checklistKind, checklistMoveForEvent, @@ -1758,7 +1758,7 @@ async function dispatchSessionApproval( if (!token) return; const activity = sessionApprovalActivity(effective, notification); const result = await emitAgentActivity(token, agentSessionId, activity.content, { - id: progressActivityId(`${notification.marker}#${notification.requestId}`), + id: sessionApprovalNoticeId(effective, notification.requestId), ...(activity.signal && { signal: activity.signal, signalMetadata: activity.signalMetadata }), }); if (!result.ok) { diff --git a/cdk/src/handlers/shared/linear-agent-session-handler.ts b/cdk/src/handlers/shared/linear-agent-session-handler.ts index be9a16888..87b5eac37 100644 --- a/cdk/src/handlers/shared/linear-agent-session-handler.ts +++ b/cdk/src/handlers/shared/linear-agent-session-handler.ts @@ -29,6 +29,7 @@ import { buildAgentSessionTaskDescription, emitAgentActivity, fetchAgentSessionIssue, + fetchSessionActivityShown, fetchSessionPromptActivity, type SessionPromptActivity, type AgentActivityContent, @@ -54,6 +55,7 @@ import { NOTHING_TO_APPROVE_MESSAGE, parseSessionApprovalAnswer, repeatedApprovalChoice, + sessionApprovalNoticeId, sessionDecisionNote, type SessionApprovalActivity, type SessionApprovalAnswer, @@ -542,14 +544,18 @@ async function decideSessionApproval( await again('I couldn\'t confirm this answer with Linear, so nothing was decided.'); return; } - // An answer belongs to the request that was open when it was written. A delivery - // retried after that request closed and another opened (an async retry, a - // read-back that failed and retried) must not decide the newer one. - const open = await readOpenRequest(task.task_id, requestId); - if (open.openedAtMs === undefined || !(Date.parse(prompt.createdAt) >= open.openedAtMs)) { - await again('That answer was written before this request opened, so nothing was decided.'); + // An answer belongs to the request whose choice was showing when it was written. + // Both times are Linear's: the worker's own clock, and Lambda retry timing, play no + // part. A delivery retried after its request closed and another opened, or written + // before the new choice was posted, decides nothing. + const shown = await fetchSessionActivityShown( + accessToken, request.workspaceId, sessionApprovalNoticeId('approval_requested', requestId), + ); + if (shown?.sessionId !== request.sessionId || !(Date.parse(prompt.createdAt) > Date.parse(shown.createdAt))) { + await again('That answer was written before this request was shown here, so nothing was decided.'); return; } + const open = await readOpenRequest(task.task_id, requestId); // Loaded only when a session decides: other session deliveries do not need the // decision handlers' environment. const record = answer.decision === 'approve' @@ -595,22 +601,14 @@ async function confirmedPrompt( return same ? prompt : null; } -/** - * The open request's matched rules and when it opened, read consistently from its - * row, never from the reply. ``openedAtMs`` is undefined when the row has no - * readable ``created_at``, which the caller treats as not decidable. - */ -async function readOpenRequest(taskId: string, requestId: string): Promise<{ ruleIds: string[]; openedAtMs?: number }> { +/** The rules the open request matched, read consistently from its row, never from the reply. */ +async function readOpenRequest(taskId: string, requestId: string): Promise<{ ruleIds: string[] }> { if (!TASK_APPROVALS_TABLE_NAME) return { ruleIds: [] }; const { Item } = await ddb.send(new GetCommand({ TableName: TASK_APPROVALS_TABLE_NAME, Key: { task_id: taskId, request_id: requestId }, ConsistentRead: true, })); const ids: unknown[] = Array.isArray(Item?.matching_rule_ids) ? Item.matching_rule_ids : []; - const openedAtMs = typeof Item?.created_at === 'string' ? Date.parse(Item.created_at) : NaN; - return { - ruleIds: ids.filter((id): id is string => typeof id === 'string'), - ...(Number.isFinite(openedAtMs) && { openedAtMs }), - }; + return { ruleIds: ids.filter((id): id is string => typeof id === 'string') }; } /** The prior task as read from the base table (strongly consistent). */ diff --git a/cdk/src/handlers/shared/linear-agent-session.ts b/cdk/src/handlers/shared/linear-agent-session.ts index 84faf6063..6f5de8c0c 100644 --- a/cdk/src/handlers/shared/linear-agent-session.ts +++ b/cdk/src/handlers/shared/linear-agent-session.ts @@ -217,6 +217,33 @@ export async function fetchSessionPromptActivity( return { sessionId, authorId: author.id, body: activity.content.body ?? '', createdAt: activity.createdAt ?? '' }; } +const SESSION_ACTIVITY_QUERY = ` +query SessionActivityShown($id: String!) { + organization { id } + agentActivity(id: $id) { createdAt agentSession { id } } +}`; + +/** + * When Linear recorded one of this app's activities, and in which session; null when + * it does not exist. Throws when Linear cannot answer, so the caller retries. + */ +export async function fetchSessionActivityShown( + accessToken: string, + workspaceId: string, + activityId: string, +): Promise<{ readonly sessionId: string; readonly createdAt: string } | null> { + const result = await graphqlData(accessToken, SESSION_ACTIVITY_QUERY, { id: activityId }); + if (!result.ok) throw new Error('Linear session activity lookup unavailable'); + const data = result.value as { + organization?: { id?: string }; + agentActivity?: { createdAt?: string; agentSession?: { id?: string } | null } | null; + }; + if (data.organization?.id !== workspaceId) throw new Error('Linear session activity lookup workspace mismatch'); + const sessionId = data.agentActivity?.agentSession?.id; + const createdAt = data.agentActivity?.createdAt; + return sessionId && createdAt ? { sessionId, createdAt } : null; +} + /** Separator + heading that introduces Linear's `promptContext` in the description. */ const SESSION_CONTEXT_PREFIX = '\n\n## Linear session context\n\n'; const CONTEXT_TRUNCATION_NOTICE = '\n\n_(session context truncated)_'; diff --git a/cdk/src/handlers/shared/linear-session-approval.ts b/cdk/src/handlers/shared/linear-session-approval.ts index be4c992fa..f1cefac1d 100644 --- a/cdk/src/handlers/shared/linear-session-approval.ts +++ b/cdk/src/handlers/shared/linear-session-approval.ts @@ -33,6 +33,7 @@ import { approvalNotificationMarkdown, type ApprovalNotification } from './approval-notifications'; import type { AgentActivityContent } from './linear-agent-session'; import { parseLinearApprovalReply, type LinearApprovalReply } from './linear-approval-thread'; +import { progressActivityId } from './linear-session-progress'; /** * An answer from the session: approve once, approve the request's rule for the rest @@ -73,6 +74,17 @@ export function isBareApprovalAnswer(text: string): boolean { return answer !== null && !answer.reason; } +/** + * The session activity id of an approval notice: derived from the event and the + * request, so a retried notice is the same activity and the reply handler can read + * back when a request's choice was shown. + * @param eventType - the approval event (``approval_requested`` for the choice). + * @param requestId - the request. + */ +export function sessionApprovalNoticeId(eventType: string, requestId: string): string { + return progressActivityId(`notified_linear_session_${eventType}#${requestId}`); +} + /** One activity plus the options ``emitAgentActivity`` takes. */ export interface SessionApprovalActivity { readonly content: AgentActivityContent; diff --git a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts index 6d57c1118..c49699524 100644 --- a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts +++ b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts @@ -42,6 +42,7 @@ jest.mock('../../../src/handlers/shared/linear-oauth-resolver', () => ({ const emitAgentActivityMock = jest.fn(); const fetchAgentSessionIssueMock = jest.fn(); const fetchSessionPromptActivityMock = jest.fn(); +const fetchSessionActivityShownMock = jest.fn(); jest.mock('../../../src/handlers/shared/linear-agent-session', () => { const actual = jest.requireActual('../../../src/handlers/shared/linear-agent-session'); return { @@ -49,6 +50,7 @@ jest.mock('../../../src/handlers/shared/linear-agent-session', () => { emitAgentActivity: (...args: unknown[]) => emitAgentActivityMock(...args), fetchAgentSessionIssue: (...args: unknown[]) => fetchAgentSessionIssueMock(...args), fetchSessionPromptActivity: (...args: unknown[]) => fetchSessionPromptActivityMock(...args), + fetchSessionActivityShown: (...args: unknown[]) => fetchSessionActivityShownMock(...args), }; }); @@ -834,6 +836,8 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', }; beforeEach(() => { + // Linear recorded the open request's choice at 10:01; answers are written at 10:05. + fetchSessionActivityShownMock.mockResolvedValue({ sessionId: 'session-1', createdAt: '2026-11-26T10:01:00.000Z' }); recordApprovalMock.mockResolvedValue({ statusCode: 202 }); recordDenialMock.mockResolvedValue({ statusCode: 202 }); }); @@ -961,13 +965,24 @@ describe('handleAgentSessionEvent — approval requests in the session (#1066)', expect(recordApprovalMock).not.toHaveBeenCalled(); }); - test('an answer written before the open request was created decides nothing (a delayed retry)', async () => { + test('an answer Linear recorded before the open request\'s choice decides nothing (a delayed retry)', async () => { waiting(); fetchSessionPromptActivityMock.mockResolvedValue({ - sessionId: 'session-1', authorId: 'linear-user-1', body: 'approve', createdAt: '2026-11-26T09:58:00.000Z', + sessionId: 'session-1', authorId: 'linear-user-1', body: 'approve', createdAt: '2026-11-26T10:00:59.999Z', }); await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); expect(recordApprovalMock).not.toHaveBeenCalled(); - expect(String(lastEmit()[2].body)).toMatch(/^That answer was written before this request opened/); + expect(String(lastEmit()[2].body)).toMatch(/^That answer was written before this request was shown here/); + expect(fetchSessionActivityShownMock).toHaveBeenCalledWith('lin_tok', 'org-1', expect.stringMatching(/^[0-9a-f-]{36}$/)); + }); + + test.each([ + ['not posted yet', null], + ['posted in another session', { sessionId: 'other-session', createdAt: '2026-11-26T10:01:00.000Z' }], + ])('a choice %s cannot be answered here', async (_label, shown) => { + waiting(); + fetchSessionActivityShownMock.mockResolvedValue(shown); + await answer('approve'); + expect(recordApprovalMock).not.toHaveBeenCalled(); }); }); diff --git a/cdk/test/handlers/shared/linear-agent-session.test.ts b/cdk/test/handlers/shared/linear-agent-session.test.ts index 9e41ea2c5..b10afafe7 100644 --- a/cdk/test/handlers/shared/linear-agent-session.test.ts +++ b/cdk/test/handlers/shared/linear-agent-session.test.ts @@ -27,6 +27,7 @@ import { buildAgentSessionTaskDescription, emitAgentActivity, fetchAgentSessionIssue, + fetchSessionActivityShown, fetchSessionPromptActivity, } from '../../../src/handlers/shared/linear-agent-session'; import { @@ -300,6 +301,17 @@ describe('GraphQL helpers', () => { await expect(fetchSessionPromptActivity('tok', 'org-1', 'a-1')).resolves.toBeNull(); }); + test('fetchSessionActivityShown reads when Linear recorded an activity, and in which session', async () => { + fetchMock.mockResolvedValueOnce(jsonResponse({ + data: { organization: { id: 'org-1' }, agentActivity: { createdAt: '2026-11-26T10:01:00.000Z', agentSession: { id: 's-1' } } }, + })); + await expect(fetchSessionActivityShown('tok', 'org-1', 'n-1')).resolves.toEqual({ sessionId: 's-1', createdAt: '2026-11-26T10:01:00.000Z' }); + fetchMock.mockResolvedValueOnce(jsonResponse({ data: { organization: { id: 'org-1' }, agentActivity: null } })); + await expect(fetchSessionActivityShown('tok', 'org-1', 'n-1')).resolves.toBeNull(); + fetchMock.mockResolvedValueOnce(jsonResponse({}, 500)); + await expect(fetchSessionActivityShown('tok', 'org-1', 'n-1')).rejects.toThrow('unavailable'); + }); + test('another workspace, or Linear failing, throws so the delivery retries', async () => { fetchMock.mockResolvedValueOnce(reply(prompt({ id: 'u-1', app: false }), 'org-2')); await expect(fetchSessionPromptActivity('tok', 'org-1', 'a-1')).rejects.toThrow('workspace mismatch');