diff --git a/cdk/package.json b/cdk/package.json index d4299da66..8c5cf91e3 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 f232897e3..b74b6607d 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 @@ -214,6 +221,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 64b6c3e94..1c0dfee1d 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; @@ -245,6 +252,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; } @@ -396,6 +406,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 9d14c8167..337f9e251 100644 --- a/cdk/src/handlers/approve-task.ts +++ b/cdk/src/handlers/approve-task.ts @@ -65,24 +65,39 @@ const AUDIT_EVENT_RETENTION_DAYS = Number(process.env.TASK_RETENTION_DAYS ?? '90 * @returns API Gateway proxy result. */ export async function handler(event: APIGatewayProxyEvent): Promise { + return recordApprovalForUser({ userId: extractUserId(event), taskId: event.pathParameters?.task_id, body: event.body }); +} + +/** + * 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; +}): Promise { 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); } @@ -168,7 +183,8 @@ export async function handler(event: APIGatewayProxyEvent): Promise { + return recordDenialForUser({ userId: extractUserId(event), taskId: event.pathParameters?.task_id, body: event.body }); +} + +/** + * 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; +}): Promise { 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); } @@ -149,7 +164,8 @@ export async function handler(event: APIGatewayProxyEvent): Promise> // 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 @@ -354,7 +362,9 @@ 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']); +// 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]); /** * Unwrap ``agent_milestone`` events to their milestone name for @@ -1104,6 +1114,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 @@ -1177,6 +1259,14 @@ async function dispatchToLinear(event: FanOutEvent): Promise { return; } + const approvalsTable = process.env.TASK_APPROVALS_TABLE_NAME; + 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. + } + 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 // 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 d9a9f9962..e82a59aa2 100644 --- a/cdk/src/handlers/linear-webhook-processor.ts +++ b/cdk/src/handlers/linear-webhook-processor.ts @@ -26,6 +26,7 @@ import type { ScreeningConfig } from './shared/attachment-screening'; import { buildClarifyResumeDescription, isClarifyHold } from './shared/clarify-resume'; import { createTaskCore } from './shared/create-task-core'; import { renderMaturingReply } from './shared/iteration-reply'; +import { handleLinearApprovalReply } from './shared/linear-approval-reply'; import { cleanupPreScreenedAttachments, downloadScreenAndStoreLinearAttachments, LinearAttachmentError } from './shared/linear-attachments'; import { readStartClaim, releaseStartClaim } from './shared/linear-console'; import { @@ -1956,6 +1957,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; @@ -3435,6 +3447,8 @@ async function lookupPlatformUser(workspaceId: string, userId: string): Promise< const result = await ddb.send(new GetCommand({ TableName: USER_MAPPING_TABLE, Key: { linear_identity: key }, + // Approval replies authorize decisions 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/approval-notifications.ts b/cdk/src/handlers/shared/approval-notifications.ts new file mode 100644 index 000000000..0c08a75f5 --- /dev/null +++ b/cdk/src/handlers/shared/approval-notifications.ts @@ -0,0 +1,257 @@ +/** + * 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; +} + +/** 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, + 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, lines } = renderApproval(status, row, task, requestId, channel); + 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-feedback.ts b/cdk/src/handlers/shared/linear-feedback.ts index 83de57b4d..6b88cc06c 100644 --- a/cdk/src/handlers/shared/linear-feedback.ts +++ b/cdk/src/handlers/shared/linear-feedback.ts @@ -408,6 +408,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 a8cfbef5c..f94bb6f73 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -1510,6 +1510,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 @@ -1887,6 +1888,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 9a7b15149..400917b6f 100644 --- a/cdk/test/constructs/fanout-consumer.test.ts +++ b/cdk/test/constructs/fanout-consumer.test.ts @@ -267,4 +267,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 9638d24e1..7f179870b 100644 --- a/cdk/test/constructs/linear-integration.test.ts +++ b/cdk/test/constructs/linear-integration.test.ts @@ -404,3 +404,68 @@ describe('revoked-authorization recording (#812)', () => { expect(JSON.stringify(registryStatements.map((s) => s.Action))).toContain('dynamodb:UpdateItem'); }); }); + +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 fc0fe01ba..03cea8012 100644 --- a/cdk/test/handlers/approve-task.test.ts +++ b/cdk/test/handlers/approve-task.test.ts @@ -56,7 +56,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 { @@ -235,3 +235,41 @@ describe('approve-task โ€” error classification', () => { expect(res.statusCode).toBe(202); }); }); + +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 29382e3aa..0b633b95f 100644 --- a/cdk/test/handlers/deny-task.test.ts +++ b/cdk/test/handlers/deny-task.test.ts @@ -48,7 +48,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 @@ -204,3 +204,41 @@ describe('deny-task โ€” error classification', () => { expect(body.data.request_id).toBe('01KREQ'); }); }); + +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 78125b2bf..b2f09c925 100644 --- a/cdk/test/handlers/fanout-task-events.test.ts +++ b/cdk/test/handlers/fanout-task-events.test.ts @@ -109,7 +109,9 @@ const mockReplyToComment: jest.Mock = jest.fn().mockResolvedValue('reply-id'); // 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, @@ -179,6 +181,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'; @@ -400,6 +403,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', @@ -1499,6 +1506,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/contracts/coverage-thresholds.json b/contracts/coverage-thresholds.json index 3cc1433a1..3283f10c5 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", diff --git a/docs/guides/LINEAR_SETUP_GUIDE.md b/docs/guides/LINEAR_SETUP_GUIDE.md index 28b78fb50..4a0d3ae1d 100644 --- a/docs/guides/LINEAR_SETUP_GUIDE.md +++ b/docs/guides/LINEAR_SETUP_GUIDE.md @@ -153,6 +153,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 0750b2854..f2335cf27 100644 --- a/docs/src/content/docs/using/Linear-setup-guide.md +++ b/docs/src/content/docs/using/Linear-setup-guide.md @@ -155,6 +155,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 |