Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions cdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,9 @@
"tsconfig": "tsconfig.jest.json"
}
]
},
"moduleNameMapper": {
"^(\\.{1,2}/.*)\\.js$": "$1"
}
}
}
11 changes: 11 additions & 0 deletions cdk/src/constructs/fanout-consumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down
12 changes: 12 additions & 0 deletions cdk/src/constructs/linear-integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
}
Expand Down
26 changes: 22 additions & 4 deletions cdk/src/handlers/approve-task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<APIGatewayProxyResult> {
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<APIGatewayProxyResult> {
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);
}
Expand Down Expand Up @@ -168,7 +183,8 @@ export async function handler(event: APIGatewayProxyEvent): Promise<APIGatewayPr
TableName: TASK_APPROVALS_TABLE_NAME,
Key: { task_id: taskId, request_id },
UpdateExpression:
'SET #status = :approved, decided_at = :now, #scope = :scope',
'SET #status = :approved, decided_at = :now, #scope = :scope'
+ (input.decisionSource ? ', decision_source = :source' : ''),
ConditionExpression:
'attribute_exists(request_id) AND #status = :pending AND user_id = :caller',
ExpressionAttributeNames: {
Expand All @@ -181,6 +197,7 @@ export async function handler(event: APIGatewayProxyEvent): Promise<APIGatewayPr
':now': nowIso,
':scope': scope,
':caller': callerUserId,
...(input.decisionSource ? { ':source': input.decisionSource } : {}),
},
},
},
Expand Down Expand Up @@ -228,6 +245,7 @@ export async function handler(event: APIGatewayProxyEvent): Promise<APIGatewayPr
scope,
decided_at: nowIso,
caller_user_id: callerUserId,
...(input.decisionSource ? { decision_source: input.decisionSource } : {}),
} satisfies ApprovalDecisionRecordedEvent,
},
}));
Expand Down
26 changes: 22 additions & 4 deletions cdk/src/handlers/deny-task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,24 +63,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<APIGatewayProxyResult> {
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<APIGatewayProxyResult> {
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);
}
Expand Down Expand Up @@ -149,7 +164,8 @@ export async function handler(event: APIGatewayProxyEvent): Promise<APIGatewayPr
TableName: TASK_APPROVALS_TABLE_NAME,
Key: { task_id: taskId, request_id },
UpdateExpression:
'SET #status = :denied, decided_at = :now, deny_reason = :reason',
'SET #status = :denied, decided_at = :now, deny_reason = :reason'
+ (input.decisionSource ? ', decision_source = :source' : ''),
ConditionExpression:
'attribute_exists(request_id) AND #status = :pending AND user_id = :caller',
ExpressionAttributeNames: { '#status': 'status' },
Expand All @@ -159,6 +175,7 @@ export async function handler(event: APIGatewayProxyEvent): Promise<APIGatewayPr
':now': nowIso,
':reason': sanitizedReason,
':caller': callerUserId,
...(input.decisionSource ? { ':source': input.decisionSource } : {}),
},
},
},
Expand Down Expand Up @@ -202,6 +219,7 @@ export async function handler(event: APIGatewayProxyEvent): Promise<APIGatewayPr
reason: sanitizedReason,
decided_at: nowIso,
caller_user_id: callerUserId,
...(input.decisionSource ? { decision_source: input.decisionSource } : {}),
} satisfies ApprovalDecisionRecordedEvent,
},
}));
Expand Down
94 changes: 92 additions & 2 deletions cdk/src/handlers/fanout-task-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ import type {
DynamoDBRecord,
DynamoDBStreamEvent,
} from 'aws-lambda';
import {
approvalNotificationMarkdown, isApprovalNotification, loadApprovalNotification, markApprovalNotificationDelivered,
APPROVAL_NOTIFICATION_EVENTS as LINEAR_APPROVAL_EVENTS,
} from './shared/approval-notifications';
import { clearTokenCache, resolveGitHubToken } from './shared/context-hydration';
import { classifyError } from './shared/error-classifier';
import { renderFailureReply } from './shared/failure-reply';
Expand All @@ -62,7 +66,8 @@ import {
renderJiraFinishedPointer,
type JiraFinishedPointerKind,
} from './shared/jira-status-comment';
import { EMOJI_FAILURE, EMOJI_NEEDS_INPUT, EMOJI_SUCCESS, postIssueComment, swapCommentReaction, upsertThreadedReply } from './shared/linear-feedback';
import { closeLinearApprovalThread, type LinearApprovalThread, saveLinearApprovalThread } from './shared/linear-approval-thread';
import { EMOJI_FAILURE, EMOJI_NEEDS_INPUT, EMOJI_SUCCESS, postIdentifiedComment, postIssueComment, swapCommentReaction, upsertThreadedReply } from './shared/linear-feedback';
import { logger } from './shared/logger';
import { coerceNumericOrNull } from './shared/numeric';
import { loadRepoConfig } from './shared/repo-config';
Expand Down Expand Up @@ -191,6 +196,9 @@ export const CHANNEL_DEFAULTS: Record<NotificationChannel, ReadonlySet<string>>
// even earlier, at task-admission in the webhook processor (ADR-016 P4.5).
linear: new Set<string>([
...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
Expand Down Expand Up @@ -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<string> = 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<string> = new Set(['pr_created', ...LINEAR_APPROVAL_EVENTS]);

/**
* Unwrap ``agent_milestone`` events to their milestone name for
Expand Down Expand Up @@ -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<void> {
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<void> {
// 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
Expand Down Expand Up @@ -1177,6 +1259,14 @@ async function dispatchToLinear(event: FanOutEvent): Promise<void> {
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.
Expand Down
14 changes: 14 additions & 0 deletions cdk/src/handlers/linear-webhook-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -1956,6 +1957,17 @@ function commentTargetBelongsToWorkspace(
}

async function handleCommentTrigger(payload: LinearCommentEvent): Promise<void> {
// 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;
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading