diff --git a/agent/policies/soft_deny.cedar b/agent/policies/soft_deny.cedar index 6bfd286e2..45ba9865b 100644 --- a/agent/policies/soft_deny.cedar +++ b/agent/policies/soft_deny.cedar @@ -24,7 +24,9 @@ permit (principal, action, resource); // `security.cedarPolicies.disable: [rule_id]`. They may NOT disable any // rule in hard_deny.cedar (blueprint loader rejects those at task start). -// Gate any git --force / -f push. 300s default approval window, medium severity. +// Gate any git --force / -f push. Medium severity. Each built-in rule allows the +// platform maximum (3600s), so the task's window decides (default 1800s, per repo +// via security.approvalTimeoutSeconds, per task via approval_timeout_s). // Covers both long-form (--force) and short-form (-f) variants, including // the bare `git push -f` invocation with no branch argument, and the flag // after the remote and branch (`git push origin feature --force`). After @@ -37,7 +39,7 @@ permit (principal, action, resource); // other option that begins with `-f`. @tier("soft") @rule_id("force_push_any") -@approval_timeout_s("300") +@approval_timeout_s("3600") @severity("medium") @category("destructive") forbid (principal, action == Agent::Action::"execute_bash", resource) @@ -61,7 +63,7 @@ when { context.command like "*git push --force*" // merging picks min(300, 600)=300s and max(medium, high)=high. @tier("soft") @rule_id("force_push_main") -@approval_timeout_s("600") +@approval_timeout_s("3600") @severity("high") @category("destructive") forbid (principal, action == Agent::Action::"execute_bash", resource) @@ -74,7 +76,7 @@ when { context.command like "*git push --force origin main*" // agent bypasses PR workflow by pushing directly. @tier("soft") @rule_id("push_to_protected_branch") -@approval_timeout_s("300") +@approval_timeout_s("3600") @severity("medium") @category("destructive") forbid (principal, action == Agent::Action::"execute_bash", resource) @@ -86,7 +88,7 @@ when { context.command like "*git push origin main*" // Writes to `.env` files typically contain secrets. 600s window, high severity. @tier("soft") @rule_id("write_env_files") -@approval_timeout_s("600") +@approval_timeout_s("3600") @severity("high") @category("filesystem") forbid (principal, action == Agent::Action::"write_file", resource) @@ -96,7 +98,7 @@ when { context.file_path like "*.env" }; // service-account JSON, etc. 300s window, high severity. @tier("soft") @rule_id("write_credentials") -@approval_timeout_s("300") +@approval_timeout_s("3600") @severity("high") @category("auth") forbid (principal, action == Agent::Action::"write_file", resource) diff --git a/agent/src/output_scanner.py b/agent/src/output_scanner.py index 9230fff84..08e6e8fd8 100644 --- a/agent/src/output_scanner.py +++ b/agent/src/output_scanner.py @@ -94,6 +94,8 @@ class ScanResult: ), # Slack tokens (xoxb-, xoxp-, ...) ("SLACK_TOKEN", re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}\b")), + # Linear personal API keys (lin_api_) and OAuth access tokens (lin_oauth_). + ("LINEAR_TOKEN", re.compile(r"\blin_(?:api|oauth)_[A-Za-z0-9]{16,}")), # Generic Bearer / token patterns (min 20-char token to avoid false positives # on natural English like "bearer of good news") ("BEARER_TOKEN", re.compile(r"Bearer\s+[a-zA-Z0-9\-._~+/]{20,}=*", re.IGNORECASE)), diff --git a/agent/tests/test_blueprint_cedar_routing.py b/agent/tests/test_blueprint_cedar_routing.py index f63990007..f84c8fad5 100644 --- a/agent/tests/test_blueprint_cedar_routing.py +++ b/agent/tests/test_blueprint_cedar_routing.py @@ -61,7 +61,7 @@ def test_guide_hard_rule_matches_the_prod_directory(guide_policies, tool, path, assert "block_prod_writes" in decision.reason -@pytest.mark.parametrize(("task_timeout", "expected"), [(None, 300), (600, 600), (3600, 900)]) +@pytest.mark.parametrize(("task_timeout", "expected"), [(None, 900), (600, 600), (3600, 900)]) def test_guide_soft_rule_uses_shorter_approval_window(guide_policies, task_timeout, expected): engine = engine_for(guide_policies, timeout_s=task_timeout) decision = engine.evaluate_tool_use("Bash", {"command": "terraform apply"}) diff --git a/agent/tests/test_policy_three_outcome.py b/agent/tests/test_policy_three_outcome.py index 0b5d80cba..1b72bf63e 100644 --- a/agent/tests/test_policy_three_outcome.py +++ b/agent/tests/test_policy_three_outcome.py @@ -439,19 +439,20 @@ def test_soft_deny_force_push_returns_require_approval(self): d = engine.evaluate_tool_use("Bash", {"command": "git push --force origin feature"}) assert d.outcome == Outcome.REQUIRE_APPROVAL assert "force_push_any" in d.matching_rule_ids - assert d.timeout_s == 300 + # The rule allows 3600s; the task default (1800s) decides. + assert d.timeout_s == 1800 assert d.severity == "medium" def test_soft_deny_multi_match_merges_annotations(self): - # force_push_any (300s, medium) + force_push_main (600s, high) both - # match "git push --force origin main". Merge picks min(300, 600)=300s + # force_push_any (3600s, medium) + force_push_main (3600s, high) both + # match "git push --force origin main". Merge picks min(3600, 3600, 1800)=1800s # and max(medium, high)=high. ยง6.3. engine = PolicyEngine(task_type="new_task", repo="owner/repo") d = engine.evaluate_tool_use("Bash", {"command": "git push --force origin main"}) assert d.outcome == Outcome.REQUIRE_APPROVAL assert "force_push_any" in d.matching_rule_ids assert "force_push_main" in d.matching_rule_ids - assert d.timeout_s == 300 # min across rules + task default + assert d.timeout_s == 1800 # min across rules (3600) + task default (1800) assert d.severity == "high" # max across rules def test_default_allow_on_no_match(self): diff --git a/cdk/package.json b/cdk/package.json index 3e873e127..47d326336 100644 --- a/cdk/package.json +++ b/cdk/package.json @@ -140,6 +140,9 @@ "tsconfig": "tsconfig.jest.json" } ] + }, + "moduleNameMapper": { + "^(\\.{1,2}/.*)\\.js$": "$1" } } } diff --git a/cdk/src/constructs/blueprint.ts b/cdk/src/constructs/blueprint.ts index bcc6f5dfc..6e3959e2b 100644 --- a/cdk/src/constructs/blueprint.ts +++ b/cdk/src/constructs/blueprint.ts @@ -46,6 +46,8 @@ const DOMAIN_PATTERN = /^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9 */ const APPROVAL_GATE_CAP_MIN = sharedConstants.approval_gate_cap.min; const APPROVAL_GATE_CAP_MAX = sharedConstants.approval_gate_cap.max; +const APPROVAL_TIMEOUT_S_MIN = sharedConstants.approval_timeout_s.min; +const APPROVAL_TIMEOUT_S_MAX = sharedConstants.approval_timeout_s.max; /** * Bounds on a per-repo cost budget (#748). Same JSON the task-submit path @@ -209,6 +211,18 @@ export interface BlueprintProps { * back to the platform default of 50 defined in the handler layer. */ readonly approvalGateCap?: number; + + /** + * How long, in seconds, a person has to answer an approval request on this + * repo's tasks before it is denied. Captured at task-submit time onto the + * TaskRecord; a task submitted with its own ``approval_timeout_s`` keeps + * that. A rule's own ``@approval_timeout_s`` still caps it for that rule. + * + * Must be an integer in the platform's ``approval_timeout_s`` range + * (``contracts/constants.json``: 30 to 3600). When omitted, the platform + * default applies. + */ + readonly approvalTimeoutSeconds?: number; }; /** @@ -277,6 +291,9 @@ export class Blueprint extends Construct { */ public readonly approvalGateCap?: number; + /** Default approval window in seconds from security.approvalTimeoutSeconds, if set. */ + public readonly approvalTimeoutSeconds?: number; + /** * Per-repo cost budget in USD from the agent.maxBudgetUsd prop (#748), * exposed for inspection. Undefined when the blueprint did not configure @@ -306,7 +323,7 @@ export class Blueprint extends Construct { this.egressAllowlist = [...(props.networking?.egressAllowlist ?? [])]; this.cedarPolicies = [...(props.security?.cedarPolicies ?? [])]; - this.approvalGateCap = props.security?.approvalGateCap; + ({ approvalGateCap: this.approvalGateCap, approvalTimeoutSeconds: this.approvalTimeoutSeconds } = approvalSettings(props)); const { maxBudgetUsd, memoryTokenBudget } = props.agent ?? {}; this.maxBudgetUsd = maxBudgetUsd; this.memoryTokenBudget = memoryTokenBudget; @@ -331,6 +348,7 @@ export class Blueprint extends Construct { this.node.addValidation(new RepoFormatValidation(props.repo)); this.node.addValidation(new DomainFormatValidation(this.egressAllowlist)); this.node.addValidation(new ApprovalGateCapValidation(this.approvalGateCap)); + this.node.addValidation(new ApprovalTimeoutValidation(this.approvalTimeoutSeconds)); this.node.addValidation(new MaxBudgetUsdValidation(this.maxBudgetUsd)); this.node.addValidation(new MemoryTokenBudgetValidation(this.memoryTokenBudget)); this.node.addValidation(new RegistryRefValidation('assets.mcpServers', this.mcpServerRefs, 'mcp_server')); @@ -396,6 +414,9 @@ export class Blueprint extends Construct { if (this.approvalGateCap !== undefined) { item.approval_gate_cap = { N: String(this.approvalGateCap) }; } + if (this.approvalTimeoutSeconds !== undefined) { + item.approval_timeout_s = { N: String(this.approvalTimeoutSeconds) }; + } if (this.mcpServerRefs.length > 0) { item.mcp_servers = { L: this.mcpServerRefs.map(r => ({ S: r })) }; } @@ -482,6 +503,7 @@ export class Blueprint extends Construct { if (this.egressAllowlist.length > 0) fields.push(', #egress_allowlist = :egress_allowlist'); if (this.cedarPolicies.length > 0) fields.push(', #cedar_policies = :cedar_policies'); if (this.approvalGateCap !== undefined) fields.push(', #approval_gate_cap = :approval_gate_cap'); + if (this.approvalTimeoutSeconds !== undefined) fields.push(', #approval_timeout_s = :approval_timeout_s'); // Registry asset refs (#246) โ€” must mirror onCreate's item, else a redeploy // of an already-onboarded repo silently drops asset-ref changes. if (this.mcpServerRefs.length > 0) fields.push(', #mcp_servers = :mcp_servers'); @@ -506,6 +528,7 @@ export class Blueprint extends Construct { if (this.egressAllowlist.length > 0) names['#egress_allowlist'] = 'egress_allowlist'; if (this.cedarPolicies.length > 0) names['#cedar_policies'] = 'cedar_policies'; if (this.approvalGateCap !== undefined) names['#approval_gate_cap'] = 'approval_gate_cap'; + if (this.approvalTimeoutSeconds !== undefined) names['#approval_timeout_s'] = 'approval_timeout_s'; if (this.mcpServerRefs.length > 0) names['#mcp_servers'] = 'mcp_servers'; if (this.cedarPolicyModuleRefs.length > 0) names['#cedar_policy_modules'] = 'cedar_policy_modules'; if (this.skillRefs.length > 0) names['#skills'] = 'skills'; @@ -528,6 +551,7 @@ export class Blueprint extends Construct { if (this.egressAllowlist.length > 0) values[':egress_allowlist'] = { L: this.egressAllowlist.map(d => ({ S: d })) }; if (this.cedarPolicies.length > 0) values[':cedar_policies'] = { L: this.cedarPolicies.map(p => ({ S: p })) }; if (this.approvalGateCap !== undefined) values[':approval_gate_cap'] = { N: String(this.approvalGateCap) }; + if (this.approvalTimeoutSeconds !== undefined) values[':approval_timeout_s'] = { N: String(this.approvalTimeoutSeconds) }; if (this.mcpServerRefs.length > 0) values[':mcp_servers'] = { L: this.mcpServerRefs.map(r => ({ S: r })) }; if (this.cedarPolicyModuleRefs.length > 0) values[':cedar_policy_modules'] = { L: this.cedarPolicyModuleRefs.map(r => ({ S: r })) }; if (this.skillRefs.length > 0) values[':skills'] = { L: this.skillRefs.map(r => ({ S: r })) }; @@ -546,14 +570,19 @@ export class Blueprint extends Construct { return empty; } + /** Asset fields now empty, and an approval window no longer set: only the Blueprint writes it. */ + private removedFields(): string[] { + return [...this.emptyAssetFields(), ...(this.approvalTimeoutSeconds === undefined ? ['approval_timeout_s'] : [])]; + } + private buildRemoveClause(): string { - const fields = this.emptyAssetFields(); + const fields = this.removedFields(); return fields.length > 0 ? ` REMOVE ${fields.map(f => `#${f}`).join(', ')}` : ''; } private buildRemoveNames(): Record { const names: Record = {}; - const fields = this.emptyAssetFields(); + const fields = this.removedFields(); for (const f of fields) names[`#${f}`] = f; return names; } @@ -617,6 +646,31 @@ class ApprovalGateCapValidation implements IValidation { } } +/** The blueprint's approval settings (read here to keep the constructor under the complexity ceiling). */ +function approvalSettings(props: BlueprintProps): { approvalGateCap?: number; approvalTimeoutSeconds?: number } { + const security = props.security ?? {}; + return { approvalGateCap: security.approvalGateCap, approvalTimeoutSeconds: security.approvalTimeoutSeconds }; +} + +/** Validates ``security.approvalTimeoutSeconds`` against the platform's ``approval_timeout_s`` range. */ +class ApprovalTimeoutValidation implements IValidation { + constructor(private readonly seconds: number | undefined) {} + + public validate(): string[] { + if (this.seconds === undefined) return []; + if (!Number.isInteger(this.seconds)) { + return [`Invalid security.approvalTimeoutSeconds: ${this.seconds}. Must be an integer.`]; + } + if (this.seconds < APPROVAL_TIMEOUT_S_MIN || this.seconds > APPROVAL_TIMEOUT_S_MAX) { + return [ + `Invalid security.approvalTimeoutSeconds: ${this.seconds}. ` + + `Must be between ${APPROVAL_TIMEOUT_S_MIN} and ${APPROVAL_TIMEOUT_S_MAX}.`, + ]; + } + return []; + } +} + /** * #748 โ€” validates the per-repo cost budget is a finite number inside * ``[MAX_BUDGET_USD_MIN, MAX_BUDGET_USD_MAX]``. Bounds come from diff --git a/cdk/src/constructs/concurrency-reconciler.ts b/cdk/src/constructs/concurrency-reconciler.ts index c0fed93dd..4e66bba6d 100644 --- a/cdk/src/constructs/concurrency-reconciler.ts +++ b/cdk/src/constructs/concurrency-reconciler.ts @@ -22,7 +22,7 @@ import { Duration } from 'aws-cdk-lib'; import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; import * as events from 'aws-cdk-lib/aws-events'; import * as targets from 'aws-cdk-lib/aws-events-targets'; -import { Runtime, Architecture } from 'aws-cdk-lib/aws-lambda'; +import { Runtime, Architecture, type IFunction } from 'aws-cdk-lib/aws-lambda'; import * as lambda from 'aws-cdk-lib/aws-lambda-nodejs'; import { NagSuppressions } from 'cdk-nag'; import { Construct } from 'constructs'; @@ -92,6 +92,7 @@ export class ConcurrencyReconciler extends Construct { props.userConcurrencyTable.grantReadWriteData(this.fn); const schedule = props.schedule ?? Duration.minutes(DEFAULT_SCHEDULE_MINUTES); + this.fn.addEnvironment('RECONCILER_TICK_MINUTES', String(schedule.toMinutes())); const rule = new events.Rule(this, 'ReconcilerSchedule', { schedule: events.Schedule.rate(schedule), }); @@ -108,4 +109,20 @@ export class ConcurrencyReconciler extends Construct { }, ], true); } + + /** + * Have this reconciler invoke the Linear webhook processor's grant health probe + * (#1004) on one tick every 12 h. + * + * Revocation detection (#812) only runs when a Linear event needs a token, so an + * idle workspace or a dead webhook never re-detects a dead grant, and an unused + * refresh token simply expires. The probe refreshes expiring tokens and sends a + * rejected grant down the existing latch-and-announce path. It rides this + * schedule by async invoke because the root stack has no resource budget for a + * rule of its own: this adds only an IAM statement and two env vars. + */ + public triggerLinearGrantProbe(processor: IFunction): void { + this.fn.addEnvironment('LINEAR_GRANT_PROBE_FUNCTION_ARN', processor.functionArn); + processor.grantInvoke(this.fn); + } } diff --git a/cdk/src/constructs/fanout-consumer.ts b/cdk/src/constructs/fanout-consumer.ts index 9c9f821d7..d2909e895 100644 --- a/cdk/src/constructs/fanout-consumer.ts +++ b/cdk/src/constructs/fanout-consumer.ts @@ -63,6 +63,13 @@ export interface FanOutConsumerProps { */ readonly taskTable?: dynamodb.ITable; + /** + * Approval state for channel approval notices (#1001): the dispatcher renders + * from the saved row, records per-request delivery receipts and the Linear + * reply-thread mapping. + */ + readonly taskApprovalsTable?: dynamodb.ITable; + /** * RepoTable โ€” GitHub dispatcher reads per-repo * `github_token_secret_arn` overrides. Optional: if omitted, falls @@ -224,6 +231,10 @@ export class FanOutConsumer extends Construct { props.taskTable.grantReadWriteData(this.fn); this.fn.addEnvironment('TASK_TABLE_NAME', props.taskTable.tableName); } + if (props.taskApprovalsTable) { + props.taskApprovalsTable.grant(this.fn, 'dynamodb:GetItem', 'dynamodb:UpdateItem'); + this.fn.addEnvironment('TASK_APPROVALS_TABLE_NAME', props.taskApprovalsTable.tableName); + } if (props.repoTable) { props.repoTable.grantReadData(this.fn); this.fn.addEnvironment('REPO_TABLE_NAME', props.repoTable.tableName); diff --git a/cdk/src/constructs/linear-integration.ts b/cdk/src/constructs/linear-integration.ts index dac4a36d3..80441f0b1 100644 --- a/cdk/src/constructs/linear-integration.ts +++ b/cdk/src/constructs/linear-integration.ts @@ -78,6 +78,13 @@ export interface LinearIntegrationProps { /** The DynamoDB task events table. */ readonly taskEventsTable: dynamodb.ITable; + /** + * Enables task-owner approve/deny decisions from replies to Linear approval + * notices (#1001). The processor reads the reply thread mapping and records + * the decision through the same handler path as the API. + */ + readonly taskApprovalsTable?: dynamodb.ITable; + /** Monthly user/team budget configuration and spend table. */ readonly budgetTable?: dynamodb.ITable; @@ -301,6 +308,9 @@ export class LinearIntegration extends Construct { TASK_EVENTS_TABLE_NAME: props.taskEventsTable.tableName, TASK_RETENTION_DAYS: String(props.taskRetentionDays ?? DEFAULT_TASK_RETENTION_DAYS), }; + if (props.taskApprovalsTable) { + createTaskEnv.TASK_APPROVALS_TABLE_NAME = props.taskApprovalsTable.tableName; + } if (props.repoTable) { createTaskEnv.REPO_TABLE_NAME = props.repoTable.tableName; } @@ -455,6 +465,8 @@ export class LinearIntegration extends Construct { } props.taskTable.grantReadWriteData(webhookProcessorFn); props.taskEventsTable.grantReadWriteData(webhookProcessorFn); + // Approval replies: thread mapping, rate-limit counter and the decision. + props.taskApprovalsTable?.grantReadWriteData(webhookProcessorFn); if (props.repoTable) { props.repoTable.grantReadData(webhookProcessorFn); } diff --git a/cdk/src/handlers/approve-task.ts b/cdk/src/handlers/approve-task.ts index 5cb0c3938..9349a75fc 100644 --- a/cdk/src/handlers/approve-task.ts +++ b/cdk/src/handlers/approve-task.ts @@ -68,25 +68,50 @@ const AUDIT_EVENT_RETENTION_DAYS = Number(process.env.TASK_RETENTION_DAYS ?? '90 export async function handler( event: APIGatewayProxyEvent, context?: Pick, ): Promise { - const invocationStartedMs = Date.now(); + return recordApprovalForUser({ + userId: extractUserId(event), + taskId: event.pathParameters?.task_id, + body: event.body, + invocationStartedMs: Date.now(), + context, + }); +} + +/** + * Shared decision path for the API and Linear approval replies. Callers must + * authenticate and map the platform user first; this applies the same + * validation, rate limit, owner and state checks as the API. + * ``decisionSource`` records where a non-API decision came from. + */ +export async function recordApprovalForUser(input: { + userId: string | null; + taskId?: string; + body?: string | null; + decisionSource?: string; + /** API invocation start and Lambda context bound the post-commit MicroVM wake. */ + invocationStartedMs?: number; + context?: Pick; +}): Promise { + const invocationStartedMs = input.invocationStartedMs ?? Date.now(); + const context = input.context; const requestId = ulid(); try { // 1. Auth - const callerUserId = extractUserId(event); + const callerUserId = input.userId; if (!callerUserId) { return errorResponse(401, ErrorCode.UNAUTHORIZED, 'Missing or invalid authentication.', requestId); } // 2. Path + body - const taskId = event.pathParameters?.task_id; + const taskId = input.taskId; if (!taskId) { return errorResponse(400, ErrorCode.VALIDATION_ERROR, 'Missing task_id path parameter.', requestId); } let parsed: ApprovalRequest | null = null; try { - parsed = event.body ? JSON.parse(event.body) as ApprovalRequest : null; + parsed = input.body ? JSON.parse(input.body) as ApprovalRequest : null; } catch { return errorResponse(400, ErrorCode.VALIDATION_ERROR, 'Request body must be valid JSON.', requestId); } @@ -172,7 +197,8 @@ export async function handler( TableName: TASK_APPROVALS_TABLE_NAME, Key: { task_id: taskId, request_id }, UpdateExpression: - 'SET #status = :approved, decided_at = :now, #scope = :scope', + 'SET #status = :approved, decided_at = :now, #scope = :scope' + + (input.decisionSource ? ', decision_source = :source' : ''), ConditionExpression: 'attribute_exists(request_id) AND #status = :pending AND user_id = :caller ' + 'AND (attribute_not_exists(deadline_epoch) OR deadline_epoch > :epoch)', @@ -187,6 +213,7 @@ export async function handler( ':scope': scope, ':caller': callerUserId, ':epoch': nowEpoch, + ...(input.decisionSource ? { ':source': input.decisionSource } : {}), }, }, }, @@ -224,7 +251,7 @@ export async function handler( callerUserId, requestId: request_id, decision: 'APPROVED', - auditMetadata: { scope: scope }, + auditMetadata: { ...(input.decisionSource ? { decision_source: input.decisionSource } : {}), scope: scope }, decidedAt: nowIso, nowEpoch, retentionDays: AUDIT_EVENT_RETENTION_DAYS, diff --git a/cdk/src/handlers/deny-task.ts b/cdk/src/handlers/deny-task.ts index 0c8f048ec..9e8b831b3 100644 --- a/cdk/src/handlers/deny-task.ts +++ b/cdk/src/handlers/deny-task.ts @@ -66,25 +66,50 @@ const AUDIT_EVENT_RETENTION_DAYS = Number(process.env.TASK_RETENTION_DAYS ?? '90 export async function handler( event: APIGatewayProxyEvent, context?: Pick, ): Promise { - const invocationStartedMs = Date.now(); + return recordDenialForUser({ + userId: extractUserId(event), + taskId: event.pathParameters?.task_id, + body: event.body, + invocationStartedMs: Date.now(), + context, + }); +} + +/** + * Shared decision path for the API and Linear approval replies. Callers must + * authenticate and map the platform user first; this applies the same + * validation, rate limit, owner and state checks as the API. + * ``decisionSource`` records where a non-API decision came from. + */ +export async function recordDenialForUser(input: { + userId: string | null; + taskId?: string; + body?: string | null; + decisionSource?: string; + /** API invocation start and Lambda context bound the post-commit MicroVM wake. */ + invocationStartedMs?: number; + context?: Pick; +}): Promise { + const invocationStartedMs = input.invocationStartedMs ?? Date.now(); + const context = input.context; const requestId = ulid(); try { // 1. Auth - const callerUserId = extractUserId(event); + const callerUserId = input.userId; if (!callerUserId) { return errorResponse(401, ErrorCode.UNAUTHORIZED, 'Missing or invalid authentication.', requestId); } // 2. Path + body - const taskId = event.pathParameters?.task_id; + const taskId = input.taskId; if (!taskId) { return errorResponse(400, ErrorCode.VALIDATION_ERROR, 'Missing task_id path parameter.', requestId); } let parsed: DenyRequest | null = null; try { - parsed = event.body ? JSON.parse(event.body) as DenyRequest : null; + parsed = input.body ? JSON.parse(input.body) as DenyRequest : null; } catch { return errorResponse(400, ErrorCode.VALIDATION_ERROR, 'Request body must be valid JSON.', requestId); } @@ -163,7 +188,8 @@ export async function handler( TableName: TASK_APPROVALS_TABLE_NAME, Key: { task_id: taskId, request_id }, UpdateExpression: - 'SET #status = :denied, decided_at = :now, deny_reason = :reason', + 'SET #status = :denied, decided_at = :now, deny_reason = :reason' + + (input.decisionSource ? ', decision_source = :source' : ''), ConditionExpression: 'attribute_exists(request_id) AND #status = :pending AND user_id = :caller ' + 'AND (attribute_not_exists(deadline_epoch) OR deadline_epoch > :epoch)', @@ -175,6 +201,7 @@ export async function handler( ':reason': sanitizedReason, ':caller': callerUserId, ':epoch': nowEpoch, + ...(input.decisionSource ? { ':source': input.decisionSource } : {}), }, }, }, @@ -211,7 +238,7 @@ export async function handler( callerUserId, requestId: request_id, decision: 'DENIED', - auditMetadata: { reason: sanitizedReason }, + auditMetadata: { ...(input.decisionSource ? { decision_source: input.decisionSource } : {}), reason: sanitizedReason }, decidedAt: nowIso, nowEpoch, retentionDays: AUDIT_EVENT_RETENTION_DAYS, diff --git a/cdk/src/handlers/fanout-task-events.ts b/cdk/src/handlers/fanout-task-events.ts index 05ad1c409..0051aada0 100644 --- a/cdk/src/handlers/fanout-task-events.ts +++ b/cdk/src/handlers/fanout-task-events.ts @@ -46,6 +46,10 @@ import type { DynamoDBStreamEvent, } from 'aws-lambda'; import { TaskStatus, TERMINAL_STATUSES } from '../constructs/task-status'; +import { + approvalNotificationMarkdown, isApprovalNotification, loadApprovalNotification, markApprovalNotificationDelivered, + APPROVAL_NOTIFICATION_EVENTS as LINEAR_APPROVAL_EVENTS, +} from './shared/approval-notifications'; import { clearTokenCache, resolveGitHubToken } from './shared/context-hydration'; import { classifyError } from './shared/error-classifier'; import { renderFailureReply } from './shared/failure-reply'; @@ -66,19 +70,39 @@ import { renderJiraFinishedPointer, type JiraFinishedPointerKind, } from './shared/jira-status-comment'; -import { addAgentSessionExternalUrl, emitAgentActivity, type AgentActivityContent } from './shared/linear-agent-session'; +import { addAgentSessionExternalUrl, emitAgentActivity, setAgentSessionPlan, type AgentActivityContent } from './shared/linear-agent-session'; import { isLinearAgentSessionsEnabled, SESSION_STOP_CANCELLED_VIA } from './shared/linear-agent-session-event'; +import { closeLinearApprovalThread, type LinearApprovalThread, saveLinearApprovalThread } from './shared/linear-approval-thread'; import { EMOJI_FAILURE, EMOJI_NEEDS_INPUT, EMOJI_SUCCESS, + postIdentifiedComment, postIssueComment, resolveToken, swapCommentReaction, + transitionIssueState, upsertThreadedReply, type LinearFeedbackContext, type LinearPostResult, } from './shared/linear-feedback'; +import { sessionApprovalActivity, sessionApprovalNoticeId } from './shared/linear-session-approval'; +import { + checklistKind, + checklistMoveForEvent, + closingLine, + renderChecklist, + type ChecklistEnding, + type ChecklistState, + type SessionOutcome, +} from './shared/linear-session-checklist'; +import { + LINEAR_SESSION_PROGRESS_EVENTS, + LINEAR_SESSION_PROGRESS_MILESTONES, + progressActivityId, + sessionProgressActivity, + type SessionProgressActivity, +} from './shared/linear-session-progress'; import { logger } from './shared/logger'; import { coerceNumericOrNull } from './shared/numeric'; import { loadRepoConfig } from './shared/repo-config'; @@ -211,6 +235,7 @@ export const CHANNEL_DEFAULTS: Record> // even earlier, at task-admission in the webhook processor (ADR-016 P4.5). linear: new Set([ ...TERMINAL_EVENT_TYPES, + ...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 @@ -219,9 +244,10 @@ export const CHANNEL_DEFAULTS: Record> 'task_timed_out', // Agent-session channel (ADR-018 Phase 2): per-turn events drive the throttled // keep-alive activity that stops a long run's Linear session going `stale` - // (30 min idle). Subscribed only with the flag on, so a default deployment - // does not pay a task read per agent turn. - ...(isLinearAgentSessionsEnabled() ? [LINEAR_SESSION_HEARTBEAT_EVENT] : []), + // (30 min idle), and these plus tool calls, queueing, context and milestones are + // streamed into the session as progress (#1066). Subscribed only with the flag + // on, so a default deployment does not pay a task read per agent turn. + ...(isLinearAgentSessionsEnabled() ? [...LINEAR_SESSION_PROGRESS_EVENTS] : []), ]), // Jira posts a single deterministic final-status comment on terminal // events โ€” the Jira analogue of the Linear default above. @@ -379,7 +405,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']); +const ROUTABLE_MILESTONES: ReadonlySet = new Set([ + 'pr_created', ...LINEAR_APPROVAL_EVENTS, ...LINEAR_SESSION_PROGRESS_MILESTONES, +]); /** * Unwrap ``agent_milestone`` events to their milestone name for @@ -1179,6 +1207,76 @@ 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 { + 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 @@ -1223,17 +1321,17 @@ async function dispatchToLinear(event: FanOutEvent): Promise { return; } - // Per-turn events reach this dispatcher for EVERY task once the session flag - // is on. Decide from memory before paying a task read: a task known not to - // be a session task never heartbeats, and a session task inside its - // keep-alive window has nothing to post yet. - const isHeartbeat = event.event_type === LINEAR_SESSION_HEARTBEAT_EVENT; - if (isHeartbeat && heartbeatCanSkipTaskRead(event.task_id)) return; + // Session-progress events (per-turn, tool calls, โ€ฆ) reach this dispatcher for + // EVERY task once the session flag is on. Decide from memory before paying a + // task read: a task known not to be a session task has nothing to show, and a + // session task's text-less turn inside its keep-alive window has nothing to post. + const progressOnly = LINEAR_SESSION_PROGRESS_EVENTS.has(effectiveEventType(event)); + if (progressOnly && progressCanSkipTaskRead(event)) return; const task = await loadTaskForComment(event.task_id); // Only a row that was actually read says what kind of task this is: a miss // (not replicated yet, a transient read) must not switch its keep-alive off. - if (isHeartbeat && task) rememberHeartbeatTask(event.task_id, task); + if (progressOnly && task) rememberHeartbeatTask(event.task_id, task); if (!task) { logger.warn('[fanout/linear] task not found โ€” skipping comment', { event: 'fanout.linear.task_missing', @@ -1273,8 +1371,17 @@ async function dispatchToLinear(event: FanOutEvent): Promise { }); return; } - // The per-turn heartbeat only matters to session tasks. - if (event.event_type === LINEAR_SESSION_HEARTBEAT_EVENT) return; + // Session progress only matters to session tasks. (The comment path below would + // otherwise read any `agent_milestone` as the PR milestone.) + if (progressOnly) return; + + 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; + } + 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 @@ -1452,6 +1559,20 @@ interface HeartbeatTaskMemo { const HEARTBEAT_MEMO_MAX_ENTRIES = 2000; const heartbeatMemo = new Map(); +/** + * True when a session-progress event can be dropped without reading the task: the + * task is known not to be a session task, or this is a turn with no text (a bare + * keep-alive) inside the session's keep-alive window. + */ +function progressCanSkipTaskRead(event: FanOutEvent): boolean { + const memo = heartbeatMemo.get(event.task_id); + if (!memo) return false; + if (!memo.sessionTask) return true; + return event.event_type === LINEAR_SESSION_HEARTBEAT_EVENT + && sessionProgressActivity(event.event_type, event.metadata) === null + && heartbeatCanSkipTaskRead(event.task_id); +} + function heartbeatCanSkipTaskRead(taskId: string): boolean { const memo = heartbeatMemo.get(taskId); if (!memo) return false; @@ -1507,6 +1628,20 @@ async function dispatchToLinearAgentSession( ctx: LinearFeedbackContext, ): Promise { const effective = effectiveEventType(event); + if (isApprovalNotification(effective)) { + await dispatchSessionApproval(event, task, agentSessionId, ctx); + return; + } + await advanceSessionChecklist(event, task, agentSessionId, ctx); + if (LINEAR_SESSION_PROGRESS_EVENTS.has(effective)) { + const progress = sessionProgressActivity(effective, event.metadata); + if (progress) { + await emitLinearSessionProgress(event, task, agentSessionId, ctx, progress); + return; + } + // A turn without text is still the keep-alive below. + if (effective !== LINEAR_SESSION_HEARTBEAT_EVENT) return; + } const isTerminalEvent = LINEAR_SESSION_TERMINAL_EVENTS.has(effective); if (effective !== 'pr_created' && effective !== LINEAR_SESSION_HEARTBEAT_EVENT && !isTerminalEvent) return; const logCtx = { task_id: task.task_id, linear_agent_session_id: agentSessionId, event_type: effective }; @@ -1566,7 +1701,10 @@ async function dispatchToLinearAgentSession( if (result.ok) await saveLinearPrCommentState(task.task_id, event.event_id); } else { result = await emitAgentActivity(token, agentSessionId, linearSessionTerminalActivity(task, event)); - if (result.ok) await saveLinearCommentState(task.task_id, event.event_id); + if (result.ok) { + await saveLinearCommentState(task.task_id, event.event_id); + if (sessionOutcome(task, event) === 'pr') await moveSessionIssueToReview(task, ctx); + } } if (result.ok) { @@ -1585,10 +1723,225 @@ async function dispatchToLinearAgentSession( } } +/** + * An approval notice in the task's session (#1066): a pending request is a choice with + * Approve / Deny buttons, anything after it a note. Same loader as the comment channel, + * so a delayed "please approve" for a request that is no longer open is never shown. + * Retried through the batch like the comment channel's notice; the activity id is + * derived from the notice, so a retry is the same activity. + */ +async function dispatchSessionApproval( + event: FanOutEvent, + task: TaskRecord, + agentSessionId: string, + ctx: LinearFeedbackContext, +): Promise { + const effective = effectiveEventType(event); + const logCtx = { task_id: task.task_id, linear_agent_session_id: agentSessionId, event_type: effective }; + const approvalsTable = process.env.TASK_APPROVALS_TABLE_NAME; + if (!approvalsTable) { + logger.warn('[fanout/linear-session] approval notice skipped: TASK_APPROVALS_TABLE_NAME unset', logCtx); + return; + } + // After the final response a new activity would reopen the session. + if (task.linear_final_comment_event_id) return; + // A decision made in the session already has its reply there. + if (effective === 'approval_decision_recorded' + && String(event.metadata?.decision_source ?? '').startsWith('["linear_session"')) return; + const liveTask = (await ddb.send(new GetCommand({ + TableName: process.env.TASK_TABLE_NAME, Key: { task_id: task.task_id }, ConsistentRead: true, + }))).Item as TaskRecord | undefined; + if (!liveTask) return; + const notification = await loadApprovalNotification(ddb, liveTask, effective, event.metadata ?? {}, 'linear_session'); + if (!notification) return; + const token = await resolveToken(ctx); + if (!token) return; + const activity = sessionApprovalActivity(effective, notification); + const result = await emitAgentActivity(token, agentSessionId, activity.content, { + id: sessionApprovalNoticeId(effective, notification.requestId), + ...(activity.signal && { signal: activity.signal, signalMetadata: activity.signalMetadata }), + }); + if (!result.ok) { + logger.warn('[fanout/linear-session] approval notice failed', { ...logCtx, retryable: result.retryable }); + if (result.retryable) throw new Error(`[fanout/linear-session] transient approval notice failure for task ${task.task_id}`); + return; + } + await markApprovalNotificationDelivered(ddb, notification); + logger.info('[fanout/linear-session] approval notice dispatched', { ...logCtx, request_id: notification.requestId }); +} + +/** + * How a finished task reads in its session: a pull request to review (also one shipped + * by a run that then stopped early), a question back, no change, a stop, or a failure. + */ +function sessionOutcome(task: TaskRecord, event: FanOutEvent): SessionOutcome { + if (event.event_type === 'task_completed') { + if (task.pr_url) return 'pr'; + // Same shape as the elicitation: no PR and no code change means the run asked a question. + return task.code_changed === false ? 'question' : 'no_change'; + } + if (event.event_type === 'task_cancelled') return 'cancelled'; + return task.pr_url ? 'pr' : 'failed'; +} + +/** ``#12`` from a pull request URL. */ +function prLabel(prUrl: string | undefined): string | undefined { + const n = prUrl?.match(/\/pull\/(\d+)/)?.[1]; + return n ? `#${n}` : undefined; +} + +/** + * Move the session's checklist (#1066). In-flight events move it forward only, with a + * conditional write on ``linear_checklist_stage``; the terminal event completes it, or + * cancels what was left. Best effort: the checklist is a view, never worth a batch retry. + */ +async function advanceSessionChecklist( + event: FanOutEvent, + task: TaskRecord, + agentSessionId: string, + ctx: LinearFeedbackContext, +): Promise { + const kind = checklistKind(task.resolved_workflow?.id); + if (!kind || task.linear_final_comment_event_id) return; + const effective = effectiveEventType(event); + const recorded = task.linear_checklist_stage ?? 0; + let state: ChecklistState; + let ending: ChecklistEnding | undefined; + if (LINEAR_SESSION_TERMINAL_EVENTS.has(effective)) { + const outcome = sessionOutcome(task, event); + if (outcome === 'question') { + state = { stage: recorded, note: 'waiting on your answer' }; + } else { + state = { stage: recorded, pr: prLabel(task.pr_url) }; + ending = outcome === 'pr' && event.event_type === 'task_completed' ? 'done' : 'stopped'; + } + } else { + if (TERMINAL_STATUSES.includes(task.status)) return; + const move = checklistMoveForEvent(effective); + if (!move) return; + state = { ...move, pr: prLabel(task.pr_url) }; + } + const logCtx = { task_id: task.task_id, linear_agent_session_id: agentSessionId, event_type: effective }; + try { + if (!ending && state.note !== 'waiting on your answer' && !(await claimChecklistStage(task.task_id, state.stage))) return; + const token = await resolveToken(ctx); + if (!token) return; + const result = await setAgentSessionPlan(token, agentSessionId, renderChecklist(kind, state, ending)); + if (!result.ok) logger.warn('[fanout/linear-session] checklist not updated', { ...logCtx, retryable: result.retryable }); + } catch (err) { + logger.warn('[fanout/linear-session] checklist update failed (best effort)', { + ...logCtx, error: err instanceof Error ? err.message : String(err), + }); + } +} + +/** Record a checklist stage if it is past the recorded one; false when it is not (nothing to show). */ +async function claimChecklistStage(taskId: string, stage: number): Promise { + try { + await ddb.send(new UpdateCommand({ + TableName: process.env.TASK_TABLE_NAME, + Key: { task_id: taskId }, + UpdateExpression: 'SET linear_checklist_stage = :s', + ConditionExpression: 'attribute_exists(task_id) AND (attribute_not_exists(linear_checklist_stage) OR linear_checklist_stage < :s)', + ExpressionAttributeValues: { ':s': stage }, + })); + return true; + } catch (err) { + if ((err as { name?: string }).name === 'ConditionalCheckFailedException') return false; + throw err; + } +} + +/** + * A session task that ends with a pull request moves its issue to "In Review" (a + * ``started`` state, so a person's later move to Done is never undone). Best effort. + */ +async function moveSessionIssueToReview(task: TaskRecord, ctx: LinearFeedbackContext): Promise { + const issueId = task.channel_metadata?.linear_issue_id; + if (!issueId) return; + try { + await transitionIssueState(ctx, issueId, 'started', ['In Review'], false, true); + } catch (err) { + logger.warn('[fanout/linear-session] could not move the issue to In Review (best effort)', { + task_id: task.task_id, error: err instanceof Error ? err.message : String(err), + }); + } +} + +/** Persistent progress activities per session task; ephemeral ones replace each other and are not counted. */ +const LINEAR_SESSION_PROGRESS_CAP = 30; + +/** + * Emit one progress activity into the task's session (#1066). Best effort: a failure is + * logged and never retried through the batch, since the next event supersedes it. Never + * posts after the session's final activity or into a finished task, because an activity + * after the closing `response` would reopen the session. Persistent activities are capped + * per task by a conditional counter on the task row; the activity id is derived from the + * event id, so a re-run record emits the same activity. + */ +async function emitLinearSessionProgress( + event: FanOutEvent, + task: TaskRecord, + agentSessionId: string, + ctx: LinearFeedbackContext, + progress: SessionProgressActivity, +): Promise { + if (task.linear_final_comment_event_id || TERMINAL_STATUSES.includes(task.status)) return; + const logCtx = { task_id: task.task_id, linear_agent_session_id: agentSessionId, event_type: effectiveEventType(event) }; + try { + if (!progress.ephemeral && !(await claimProgressSlot(task.task_id))) return; + const token = await resolveToken(ctx); + if (!token) return; + const result = await emitAgentActivity(token, agentSessionId, progress.content, { + ephemeral: progress.ephemeral, + id: progressActivityId(event.event_id), + }); + if (!result.ok) logger.warn('[fanout/linear-session] progress activity not emitted', { ...logCtx, retryable: result.retryable }); + } catch (err) { + logger.warn('[fanout/linear-session] progress activity failed (best effort)', { + ...logCtx, error: err instanceof Error ? err.message : String(err), + }); + } +} + +/** Take one of the task's persistent progress slots; false once the cap is reached. */ +async function claimProgressSlot(taskId: string): Promise { + try { + await ddb.send(new UpdateCommand({ + TableName: process.env.TASK_TABLE_NAME, + Key: { task_id: taskId }, + UpdateExpression: 'ADD linear_session_progress_count :one', + ConditionExpression: 'attribute_exists(task_id) AND (attribute_not_exists(linear_session_progress_count) OR linear_session_progress_count < :cap)', + ExpressionAttributeValues: { ':one': 1, ':cap': LINEAR_SESSION_PROGRESS_CAP }, + })); + return true; + } catch (err) { + if ((err as { name?: string }).name === 'ConditionalCheckFailedException') return false; + throw err; + } +} + +/** + * Event ids of tool calls that a later tool call of the same task in this batch + * supersedes. Only the newest one is shown (it is an ephemeral "currently doing" line, + * replaced by the next activity anyway), which keeps a busy agent's Linear calls down. + */ +export function supersededToolCallIds(records: DynamoDBStreamEvent['Records']): Set { + const latest = new Map(); + const all: Array<{ taskId: string; eventId: string }> = []; + for (const record of records) { + const ev = parseStreamRecord(record); + if (!ev || ev.event_type !== 'agent_tool_call') continue; + all.push({ taskId: ev.task_id, eventId: ev.event_id }); + latest.set(ev.task_id, ev.event_id); + } + return new Set(all.filter((c) => latest.get(c.taskId) !== c.eventId).map((c) => c.eventId)); +} + /** The session's final activity for a terminal event. */ export function linearSessionTerminalActivity(task: TaskRecord, event: FanOutEvent): AgentActivityContent { const args = linearFinalStatusArgs(task, event); - const body = renderLinearFinalStatusComment(args); + const body = `${renderLinearFinalStatusComment(args)}\n\n${closingLine(sessionOutcome(task, event))}`; if (event.event_type === 'task_completed') { return args.needsInput ? { type: 'elicitation', body } : { type: 'response', body }; } @@ -2360,6 +2713,10 @@ export const handler = async ( event: DynamoDBStreamEvent, ): Promise => { const perTaskCounts = new Map(); + // Session-progress events have their own per-task budget, so a burst of them can + // never push a task's PR or terminal event out of the batch. + const perTaskProgressCounts = new Map(); + const supersededToolCalls = supersededToolCallIds(event.Records); const batchItemFailures: DynamoDBBatchItemFailure[] = []; let processed = 0; let dispatched = 0; @@ -2382,8 +2739,13 @@ export const handler = async ( dropped++; continue; } + if (supersededToolCalls.has(ev.event_id)) { + dropped++; + continue; + } - const seen = perTaskCounts.get(ev.task_id) ?? 0; + const counts = LINEAR_SESSION_PROGRESS_EVENTS.has(effectiveEventType(ev)) ? perTaskProgressCounts : perTaskCounts; + const seen = counts.get(ev.task_id) ?? 0; if (seen >= MAX_EVENTS_PER_TASK_PER_INVOCATION) { logger.warn('[fanout] per-task cap hit โ€” dropping event', { event: 'fanout.rate_limit.hit', @@ -2396,7 +2758,7 @@ export const handler = async ( dropped++; continue; } - perTaskCounts.set(ev.task_id, seen + 1); + counts.set(ev.task_id, seen + 1); const outcome = await routeEvent(ev, overrides); if (outcome.dispatched.length > 0) dispatched++; diff --git a/cdk/src/handlers/linear-webhook-processor.ts b/cdk/src/handlers/linear-webhook-processor.ts index 6c69ea6ee..aa0ad767a 100644 --- a/cdk/src/handlers/linear-webhook-processor.ts +++ b/cdk/src/handlers/linear-webhook-processor.ts @@ -29,6 +29,7 @@ import { createTaskCore } from './shared/create-task-core'; import { renderMaturingReply } from './shared/iteration-reply'; import { AGENT_SESSION_EVENT_TYPE, isLinearAgentSessionsEnabled, type LinearAgentSessionEvent } from './shared/linear-agent-session-event'; import { handleAgentSessionEvent } from './shared/linear-agent-session-handler'; +import { handleLinearApprovalReply } from './shared/linear-approval-reply'; import { cleanupPreScreenedAttachments, downloadScreenAndStoreLinearAttachments, LinearAttachmentError } from './shared/linear-attachments'; import { lookupLinearPlatformUser, @@ -42,6 +43,7 @@ import { fetchRecentComments, type RenderedComment, } from './shared/linear-feedback'; +import { type GRANT_HEALTH_PROBE_EVENT, isGrantHealthProbe, probeLinearGrants } from './shared/linear-grant-health'; import { probeLinearIssueContext, renderIssueContextHint, @@ -730,8 +732,42 @@ type BuilderResolvedToken = { vaultUserId?: string; }; +/** + * Grant health probe (#1004), invoked twice a day by the concurrency reconciler. Runs + * in this Lambda because it already holds + * the token-refresh grants, the registry write for the revocation latch and the + * OperationalAlerts publish, so a dead grant reuses the #812 announce path. + */ +async function runGrantHealthProbe(): Promise { + if (!WORKSPACE_REGISTRY_TABLE) { + logger.error('Linear grant health probe skipped: LINEAR_WORKSPACE_REGISTRY_TABLE_NAME not set'); + return; + } + const table = WORKSPACE_REGISTRY_TABLE; + const report = await probeLinearGrants(ddb, table, id => resolveLinearOauthToken(id, table)); + const fields = { + checked: report.checked, + healthy: report.healthy, + unhealthy: report.unhealthy, + revoked: report.revoked, + }; + if (report.unhealthy.length > 0) { + logger.warn('Linear grant health probe: some workspaces have no usable token โ€” run `bgagent linear setup `', fields); + } else { + logger.info('Linear grant health probe', fields); + } +} + +export async function handler(event: ProcessorEvent | typeof GRANT_HEALTH_PROBE_EVENT): Promise { + if (isGrantHealthProbe(event)) { + await runGrantHealthProbe(); + return; + } + await processWebhookEvent(event); +} + // eslint-disable-next-line complexity -- predates the ceiling (118, down from 120 when it landed); must not grow -export async function handler(event: ProcessorEvent): Promise { +async function processWebhookEvent(event: ProcessorEvent): Promise { if (!event.raw_body) { logger.error('Linear webhook processor invoked without raw_body'); return; @@ -2010,7 +2046,25 @@ function commentTargetBelongsToWorkspace( return false; } +/** + * A reply to an approval notice is a decision, not a task request. It is handled + * only for the exact thread ABCA created, and only for the owner. True when handled. + */ +async function handledAsApprovalReply(payload: LinearCommentEvent): Promise { + const approvalsTable = process.env.TASK_APPROVALS_TABLE_NAME; + if (!approvalsTable || !WORKSPACE_REGISTRY_TABLE) return false; + return handleLinearApprovalReply(payload, { + ddb, + approvalsTable, + taskTable: process.env.TASK_TABLE_NAME!, + registryTable: WORKSPACE_REGISTRY_TABLE, + lookupUser: lookupPlatformUser, + }); +} + async function handleCommentTrigger(payload: LinearCommentEvent): Promise { + if (await handledAsApprovalReply(payload)) return; + // Orchestration must be enabled + a workspace token resolvable. if (!ORCHESTRATION_TABLE || !WORKSPACE_REGISTRY_TABLE) { return; diff --git a/cdk/src/handlers/reconcile-admission-queue.ts b/cdk/src/handlers/reconcile-admission-queue.ts index 0b08c48bf..efc61820b 100644 --- a/cdk/src/handlers/reconcile-admission-queue.ts +++ b/cdk/src/handlers/reconcile-admission-queue.ts @@ -353,6 +353,67 @@ async function expireQueuedTask(task: QueuedTask): Promise { return true; } +/** How often a task still waiting in the queue re-announces itself. */ +const QUEUE_HEARTBEAT_MINUTES = 15; +const QUEUE_HEARTBEAT_SECONDS = QUEUE_HEARTBEAT_MINUTES * 60; + +/** + * The heartbeat mark a task queued for ``ageSeconds`` has reached: 0 before the first + * 15 minutes, then 1, 2, ... A mark fires once, whenever the first pickup run past it + * claims it, so runs that drift or skip never miss one. + * @param ageSeconds - how long the task has been queued. + */ +export function queueHeartbeatMark(ageSeconds: number): number { + return Math.floor(ageSeconds / QUEUE_HEARTBEAT_SECONDS); +} + +/** + * Record that ``mark`` was announced, if no run has yet. False when it already was, or + * the task left the queue in the meantime. + */ +async function claimQueueHeartbeat(taskId: string, mark: number): Promise { + try { + await ddb.send(new UpdateItemCommand({ + TableName: TASK_TABLE, + Key: { task_id: { S: taskId } }, + UpdateExpression: 'SET queue_heartbeat_mark = :mark', + ConditionExpression: '#s = :queued AND (attribute_not_exists(queue_heartbeat_mark) OR queue_heartbeat_mark < :mark)', + ExpressionAttributeNames: { '#s': 'status' }, + ExpressionAttributeValues: { ':mark': { N: String(mark) }, ':queued': { S: 'QUEUED' } }, + })); + return true; + } catch (err) { + if ((err as { name?: string }).name === 'ConditionalCheckFailedException') return false; + throw err; + } +} + +/** + * Re-emit ``admission_queued`` (with ``waited_s``) once per heartbeat mark for tasks + * still queued (#1066). A Linear agent session shows it as "Still queued (N min so + * far)", and the activity keeps a long wait from turning the session stale. Best + * effort: a failed claim is logged and the next run tries the mark again. + * @param waiting - tasks this cycle leaves in the queue. + */ +async function emitQueueHeartbeats(waiting: readonly QueuedTask[]): Promise { + for (const task of waiting) { + const mark = queueHeartbeatMark(task.age_seconds); + if (mark < 1) continue; + try { + if (!await claimQueueHeartbeat(task.task_id, mark)) continue; + } catch (err) { + logger.warn('Queue heartbeat claim failed; the next run retries it', { + task_id: task.task_id, error: err instanceof Error ? err.message : String(err), + }); + continue; + } + await emitEvent(task.task_id, 'admission_queued', { + reason: { S: 'concurrency_limit' }, + waited_s: { N: String(Math.floor(task.age_seconds)) }, + }); + } +} + export async function handler(): Promise { const now = new Date(); const summary: PickupSummary = { @@ -428,6 +489,7 @@ export async function handler(): Promise { if (available <= 0) { summary.skipped_no_capacity += live.length; + await emitQueueHeartbeats(live); continue; } @@ -459,6 +521,7 @@ export async function handler(): Promise { } } summary.skipped_no_capacity += Math.max(0, live.length - available); + await emitQueueHeartbeats(live.slice(available)); } // Escalate to ERROR when the cycle made no forward progress despite a diff --git a/cdk/src/handlers/reconcile-concurrency.ts b/cdk/src/handlers/reconcile-concurrency.ts index 008f0e8a2..55307f2d2 100644 --- a/cdk/src/handlers/reconcile-concurrency.ts +++ b/cdk/src/handlers/reconcile-concurrency.ts @@ -18,6 +18,8 @@ */ import { DynamoDBClient, ScanCommand, QueryCommand, UpdateItemCommand } from '@aws-sdk/client-dynamodb'; +import { InvocationType, InvokeCommand, LambdaClient } from '@aws-sdk/client-lambda'; +import { GRANT_HEALTH_PROBE_EVENT, isProbeTick } from './shared/linear-grant-health'; import { logger } from './shared/logger'; import { makeClient } from './shared/ua'; @@ -60,8 +62,37 @@ async function countActiveTasks(userId: string): Promise { * Scheduled handler: scan the concurrency table and reconcile each user's * active_count against actual active tasks in the task table. */ +const LINEAR_GRANT_PROBE_FUNCTION_ARN = process.env.LINEAR_GRANT_PROBE_FUNCTION_ARN; +const RECONCILER_TICK_MINUTES = Number(process.env.RECONCILER_TICK_MINUTES); +const lambdaClient = LINEAR_GRANT_PROBE_FUNCTION_ARN ? makeClient(LambdaClient) : undefined; + +/** + * Kick the Linear grant health probe (#1004) on one tick per 12 h. Fire-and-forget + * (async invoke) and best-effort: a probe problem must never affect reconciliation. + */ +export async function triggerLinearGrantProbe(nowMs: number = Date.now()): Promise { + if (!lambdaClient || !LINEAR_GRANT_PROBE_FUNCTION_ARN || !isProbeTick(nowMs, RECONCILER_TICK_MINUTES)) { + return false; + } + try { + await lambdaClient.send(new InvokeCommand({ + FunctionName: LINEAR_GRANT_PROBE_FUNCTION_ARN, + InvocationType: InvocationType.Event, + Payload: Buffer.from(JSON.stringify(GRANT_HEALTH_PROBE_EVENT)), + })); + logger.info('Triggered the Linear grant health probe'); + return true; + } catch (err) { + logger.warn('Could not trigger the Linear grant health probe', { + error: err instanceof Error ? err.message : String(err), + }); + return false; + } +} + export async function handler(): Promise { logger.info('Concurrency reconciler started'); + await triggerLinearGrantProbe(); let corrected = 0; let scanned = 0; let errors = 0; diff --git a/cdk/src/handlers/shared/approval-decision.ts b/cdk/src/handlers/shared/approval-decision.ts index 0f5487272..21996e22e 100644 --- a/cdk/src/handlers/shared/approval-decision.ts +++ b/cdk/src/handlers/shared/approval-decision.ts @@ -35,7 +35,7 @@ export interface DecisionPostCommitInput { readonly requestId: string; readonly decision: 'APPROVED' | 'DENIED'; /** Decision-specific audit fields (approve: `scope`; deny: `reason`). */ - readonly auditMetadata: Pick; + readonly auditMetadata: Pick & { readonly decision_source?: string }; readonly decidedAt: string; readonly nowEpoch: number; readonly retentionDays: number; diff --git a/cdk/src/handlers/shared/approval-notifications.ts b/cdk/src/handlers/shared/approval-notifications.ts new file mode 100644 index 000000000..1bac7b5cd --- /dev/null +++ b/cdk/src/handlers/shared/approval-notifications.ts @@ -0,0 +1,282 @@ +/** + * 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 { TaskStatus, TERMINAL_STATUSES } from '../../constructs/task-status'; +import { scanDenyReason } from './deny-reason-scanner'; +import { logger } from './logger'; +import type { TaskRecord } from './types'; + +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; + /** When a pending request is denied unanswered (ISO), if it has a timeout. */ + readonly deadline?: string; + /** The soft-deny rules a pending request matched (for an approve-for-this-task choice). */ + readonly ruleIds?: readonly string[]; +} + +/** Where a notice goes. A Linear agent session answers with buttons, not a comment reply. */ +export type ApprovalChannel = 'slack' | 'linear' | 'linear_session'; + +function text(value: unknown, max = 500): string { + if (typeof value !== 'string') return ''; + // Redact before truncation so cutting a token cannot hide its recognizable shape. + const clean = scanDenyReason(value) + // eslint-disable-next-line no-control-regex -- strips terminal escape sequences from untrusted text + .replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '') + // eslint-disable-next-line no-control-regex -- strips control and bidi characters from untrusted text + .replace(/[\u0000-\u0008\u000b-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, ''); + return clean.length > max ? `${clean.slice(0, max)}โ€ฆ [shortened]` : clean; +} + +/** 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: ApprovalChannel, +): 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.'); + } else if (channel === 'linear_session') { + lines.push('', 'Choose Approve or Deny below, or reply deny with a reason (for example "deny use the staging config").', + 'Only the task owner can decide.'); + } + lines.push('', 'Technical details / CLI alternative', + `Task: ${task.task_id}`, `Request: ${requestId}`, + `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: ApprovalChannel, +): { 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: ApprovalChannel, +): 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); + const deadlineMs = Date.parse(String(row.created_at)) + Number(row.timeout_s) * 1000; + const deadline = status === 'PENDING' && Number.isFinite(deadlineMs) && Number(row.timeout_s) > 0 + ? new Date(deadlineMs).toISOString() : undefined; + return { + title, + text: lines.join('\n'), + taskId: task.task_id, + requestId, + userId: task.user_id, + marker, + ...(deadline && { deadline }), + ...(status === 'PENDING' && Array.isArray(row.matching_rule_ids) + && { ruleIds: row.matching_rule_ids.filter((id: unknown): id is string => typeof id === 'string') }), + }; +} + +/** 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/builtin-policies.ts b/cdk/src/handlers/shared/builtin-policies.ts index 0418f482c..cd019395c 100644 --- a/cdk/src/handlers/shared/builtin-policies.ts +++ b/cdk/src/handlers/shared/builtin-policies.ts @@ -135,7 +135,9 @@ permit (principal, action, resource); // \`security.cedarPolicies.disable: [rule_id]\`. They may NOT disable any // rule in hard_deny.cedar (blueprint loader rejects those at task start). -// Gate any git --force / -f push. 300s default approval window, medium severity. +// Gate any git --force / -f push. Medium severity. Each built-in rule allows the +// platform maximum (3600s), so the task's window decides (default 1800s, per repo +// via security.approvalTimeoutSeconds, per task via approval_timeout_s). // Covers both long-form (--force) and short-form (-f) variants, including // the bare \`git push -f\` invocation with no branch argument, and the flag // after the remote and branch (\`git push origin feature --force\`). After @@ -148,7 +150,7 @@ permit (principal, action, resource); // other option that begins with \`-f\`. @tier("soft") @rule_id("force_push_any") -@approval_timeout_s("300") +@approval_timeout_s("3600") @severity("medium") @category("destructive") forbid (principal, action == Agent::Action::"execute_bash", resource) @@ -172,7 +174,7 @@ when { context.command like "*git push --force*" // merging picks min(300, 600)=300s and max(medium, high)=high. @tier("soft") @rule_id("force_push_main") -@approval_timeout_s("600") +@approval_timeout_s("3600") @severity("high") @category("destructive") forbid (principal, action == Agent::Action::"execute_bash", resource) @@ -185,7 +187,7 @@ when { context.command like "*git push --force origin main*" // agent bypasses PR workflow by pushing directly. @tier("soft") @rule_id("push_to_protected_branch") -@approval_timeout_s("300") +@approval_timeout_s("3600") @severity("medium") @category("destructive") forbid (principal, action == Agent::Action::"execute_bash", resource) @@ -197,7 +199,7 @@ when { context.command like "*git push origin main*" // Writes to \`.env\` files typically contain secrets. 600s window, high severity. @tier("soft") @rule_id("write_env_files") -@approval_timeout_s("600") +@approval_timeout_s("3600") @severity("high") @category("filesystem") forbid (principal, action == Agent::Action::"write_file", resource) @@ -207,7 +209,7 @@ when { context.file_path like "*.env" }; // service-account JSON, etc. 300s window, high severity. @tier("soft") @rule_id("write_credentials") -@approval_timeout_s("300") +@approval_timeout_s("3600") @severity("high") @category("auth") forbid (principal, action == Agent::Action::"write_file", resource) diff --git a/cdk/src/handlers/shared/create-task-core.ts b/cdk/src/handlers/shared/create-task-core.ts index 3bd419e0b..71d119fd4 100644 --- a/cdk/src/handlers/shared/create-task-core.ts +++ b/cdk/src/handlers/shared/create-task-core.ts @@ -200,11 +200,13 @@ export async function createTaskCore( // in the "Task created" log. A repo-less submission has no blueprint, so it // stays false. let capFromBlueprint = false; + let blueprintApprovalTimeoutS: number | undefined; if (body.repo) { const { onboarded, config: repoConfig } = await lookupRepo(body.repo); if (!onboarded) { return errorResponse(422, ErrorCode.REPO_NOT_ONBOARDED, `Repository '${body.repo}' is not onboarded. Register it with a Blueprint before submitting tasks.`, requestId); } + blueprintApprovalTimeoutS = blueprintApprovalTimeout(repoConfig, body.repo, requestId); const blueprintCap = repoConfig?.approval_gate_cap; if (blueprintCap !== undefined) { if (typeof blueprintCap !== 'number' || !Number.isInteger(blueprintCap)) { @@ -331,7 +333,7 @@ export async function createTaskCore( // maxLifetime-based ceiling clip is applied at orchestrator // invocation time; at submit time we only enforce the `[floor, cap]` // envelope. - let approvalTimeoutS: number | undefined; + let approvalTimeoutS: number | undefined = blueprintApprovalTimeoutS; if (body.approval_timeout_s !== undefined) { if (typeof body.approval_timeout_s !== 'number' || !Number.isInteger(body.approval_timeout_s)) { @@ -945,6 +947,24 @@ export async function createTaskCore( return successResponse(201, toTaskDetail(taskRecord), requestId); } +/** + * The blueprint's ``approval_timeout_s``, or undefined when it has none. A value out + * of the ``[min, max]`` envelope (a hand-edited row) is logged and ignored, so the + * task gets the platform default rather than being refused. + */ +function blueprintApprovalTimeout( + config: { readonly approval_timeout_s?: unknown } | null, repo: string, requestId: string, +): number | undefined { + const value = config?.approval_timeout_s; + if (value === undefined) return undefined; + if (typeof value === 'number' && Number.isInteger(value) + && value >= APPROVAL_TIMEOUT_S_MIN && value <= APPROVAL_TIMEOUT_S_MAX) return value; + logger.error('Blueprint misconfiguration โ€” approval_timeout_s ignored', { + repo, blueprint_approval_timeout_s: value, min: APPROVAL_TIMEOUT_S_MIN, max: APPROVAL_TIMEOUT_S_MAX, request_id: requestId, + }); + return undefined; +} + /** * Check one entry of initial_approvals (ยง7.3 step 4). * @param entry - the entry as the request body holds it. diff --git a/cdk/src/handlers/shared/deny-reason-scanner.ts b/cdk/src/handlers/shared/deny-reason-scanner.ts index 334d59a54..38d124f1c 100644 --- a/cdk/src/handlers/shared/deny-reason-scanner.ts +++ b/cdk/src/handlers/shared/deny-reason-scanner.ts @@ -100,6 +100,11 @@ const PATTERNS: readonly SecretPattern[] = [ name: 'SLACK_TOKEN', regex: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, }, + { + name: 'LINEAR_TOKEN', + // Linear personal API keys (`lin_api_`) and OAuth access tokens (`lin_oauth_`). + regex: /\blin_(?:api|oauth)_[A-Za-z0-9]{16,}/g, + }, { name: 'GENERIC_BEARER', regex: /\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/gi, @@ -190,3 +195,20 @@ export function scanDenyReason(text: string): string { */ export const DENY_REASON_SECRET_NAMES: readonly string[] = PATTERNS.map((p) => p.name); + +/** + * {@link scanDenyReason} over every string in a JSON-shaped value. Applied to the + * variables of every outbound Linear GraphQL call and to GitHub comment bodies, so + * agent-originated text the platform relays (answers, error messages, event + * details) cannot carry a credential out, whatever path it took. + * @param value - a JSON-shaped value. + * @returns the same shape with known secrets replaced. + */ +export function redactValue(value: T): T { + if (typeof value === 'string') return scanDenyReason(value) as T; + if (Array.isArray(value)) return value.map((v: unknown) => redactValue(v)) as T; + if (value !== null && typeof value === 'object') { + return Object.fromEntries(Object.entries(value as Record).map(([k, v]) => [k, redactValue(v)])) as T; + } + return value; +} diff --git a/cdk/src/handlers/shared/github-comment.ts b/cdk/src/handlers/shared/github-comment.ts index 25eeb38b8..34832e67d 100644 --- a/cdk/src/handlers/shared/github-comment.ts +++ b/cdk/src/handlers/shared/github-comment.ts @@ -46,6 +46,7 @@ * codebase pattern (``preflight.ts``, ``context-hydration.ts``). */ +import { scanDenyReason } from './deny-reason-scanner'; import { logger } from './logger'; import { coerceNumericOrNull } from './numeric'; @@ -187,7 +188,7 @@ async function patchExistingComment(params: { 'User-Agent': USER_AGENT, 'Content-Type': 'application/json', }, - body: JSON.stringify({ body }), + body: JSON.stringify({ body: scanDenyReason(body) }), signal: AbortSignal.timeout(GITHUB_TIMEOUT_MS), }); } catch (err) { @@ -226,7 +227,7 @@ async function createComment(params: { 'User-Agent': USER_AGENT, 'Content-Type': 'application/json', }, - body: JSON.stringify({ body }), + body: JSON.stringify({ body: scanDenyReason(body) }), signal: AbortSignal.timeout(GITHUB_TIMEOUT_MS), }); } catch (err) { diff --git a/cdk/src/handlers/shared/linear-agent-session-event.ts b/cdk/src/handlers/shared/linear-agent-session-event.ts index 449b11d8b..8e5702395 100644 --- a/cdk/src/handlers/shared/linear-agent-session-event.ts +++ b/cdk/src/handlers/shared/linear-agent-session-event.ts @@ -153,6 +153,12 @@ export const SESSION_STOP_CANCELLED_VIA = 'linear_session_stop'; */ const LEADING_PROFILE_MENTION = /^(?:\[[^\]\n]*\]\(\s*https:\/\/linear\.app\/[^\s)]+\/profiles\/[^\s)]+\s*\)|]+>?)[,:]?\s*/i; +/** + * The comment Linear itself writes when an issue is delegated to an agent: it opens + * the session's thread and carries no instruction. + */ +const DELEGATION_THREAD_PLACEHOLDER = /^This thread is for an agent session with \S+\.?$/i; + /** * The instruction in a mention comment, with the mention itself removed โ€” a * bare mention is no instruction at all. Linear stores a real mention as the @@ -162,6 +168,7 @@ const LEADING_PROFILE_MENTION = /^(?:\[[^\]\n]*\]\(\s*https:\/\/linear\.app\/[^\ */ function mentionDirective(body: string | undefined): string { const trimmed = (body ?? '').trim().replace(LEADING_PROFILE_MENTION, '').trim(); + if (DELEGATION_THREAD_PLACEHOLDER.test(trimmed)) return ''; const trigger = parseCommentTrigger(trimmed); return trigger.triggered ? trigger.instruction : trimmed; } diff --git a/cdk/src/handlers/shared/linear-agent-session-handler.ts b/cdk/src/handlers/shared/linear-agent-session-handler.ts index 75f96b55e..87b5eac37 100644 --- a/cdk/src/handlers/shared/linear-agent-session-handler.ts +++ b/cdk/src/handlers/shared/linear-agent-session-handler.ts @@ -29,6 +29,9 @@ import { buildAgentSessionTaskDescription, emitAgentActivity, fetchAgentSessionIssue, + fetchSessionActivityShown, + fetchSessionPromptActivity, + type SessionPromptActivity, type AgentActivityContent, type AgentSessionIssue, } from './linear-agent-session'; @@ -47,6 +50,16 @@ import { writeSessionTaskPointer, } from './linear-channel-metadata'; import { resolveLinearOauthToken, type ResolvedLinearToken } from './linear-oauth-resolver'; +import { + isBareApprovalAnswer, + NOTHING_TO_APPROVE_MESSAGE, + parseSessionApprovalAnswer, + repeatedApprovalChoice, + sessionApprovalNoticeId, + sessionDecisionNote, + type SessionApprovalActivity, + type SessionApprovalAnswer, +} from './linear-session-approval'; import { fetchIssueParentId } from './linear-subissue-fetch'; import { lookupTaskByLinearIssue, type LinearIssueTask } from './linear-task-by-issue'; import { logger } from './logger'; @@ -70,6 +83,8 @@ const TASK_EVENTS_TABLE_NAME = process.env.TASK_EVENTS_TABLE_NAME!; const TASK_RETENTION_DAYS = Number(process.env.TASK_RETENTION_DAYS ?? '90'); /** Optional: without it a follow-up to a running task cannot be forwarded to the agent. */ const NUDGES_TABLE_NAME = process.env.NUDGES_TABLE_NAME; +/** Set when approval replies are configured; a session decides a request only then. */ +const TASK_APPROVALS_TABLE_NAME = process.env.TASK_APPROVALS_TABLE_NAME; /** Same value TaskApi gives `POST /tasks/{id}/nudge`: both paths share one counter row. */ const NUDGE_RATE_LIMIT_PER_MINUTE = Number(process.env.NUDGE_RATE_LIMIT_PER_MINUTE ?? '10'); /** Optional: holds the session โ†’ task pointer that covers the issue index's lag. */ @@ -130,8 +145,8 @@ export async function handleAgentSessionEvent(payload: LinearAgentSessionEvent): logger.warn('Agent-session delivery for an unresolvable workspace โ€” ignoring', logCtx); return; } - const emit = (content: AgentActivityContent, ephemeral = false) => - emitSessionActivity(resolved.accessToken, request, content, ephemeral); + const emit = (content: AgentActivityContent, ephemeral = false, signal?: Omit) => + emitSessionActivity(resolved.accessToken, request, content, ephemeral, signal); // Per-workspace evidence that sessions open here; the comment trigger only // yields to sessions in workspaces that carry it. Started now but awaited // only once the delivery is handled, so its round trip never sits between @@ -189,7 +204,13 @@ async function respondToAgentSession( const priorTask = await findPriorTask(request); if (priorTask && !isTerminal(priorTask.status)) { - await steerRunningTask(request, priorTask, platformUserId, emit); + await steerRunningTask(request, priorTask, platformUserId, emit, resolved.accessToken); + return; + } + // A late "approve" / "deny" (after its request timed out, or in the wrong session) + // is an answer to nothing. Taken as a prompt it would start new work. + if (isBareApprovalAnswer(request.directive)) { + await emit({ type: 'response', body: NOTHING_TO_APPROVE_MESSAGE }); return; } @@ -421,10 +442,20 @@ async function steerRunningTask( request: AgentSessionRequest, task: PriorTask, platformUserId: string, - emit: (content: AgentActivityContent) => Promise, + emit: SessionEmit, + accessToken: string, ): Promise { const ownSession = isRunningTasksOwnSession(request, task); const reply = (body: string) => emit(ownSession ? { type: 'thought', body } : { type: 'response', body }); + const openRequest = task.status === 'AWAITING_APPROVAL' ? task.awaiting_approval_request_id : undefined; + if (ownSession && openRequest && request.directive) { + await decideSessionApproval(request, task, openRequest, platformUserId, emit, accessToken); + return; + } + if (isBareApprovalAnswer(request.directive)) { + await reply(NOTHING_TO_APPROVE_MESSAGE); + return; + } if (!request.directive) { await reply(ownSession ? `Already working on this (task \`${task.task_id}\`) โ€” I'll report back here.` @@ -464,9 +495,126 @@ async function steerRunningTask( await reply(body); } +type SessionEmit = ( + content: AgentActivityContent, ephemeral?: boolean, signal?: Omit, +) => Promise; + +/** + * A reply in the session while its task waits on an approval request: an approve / + * deny from the task's owner decides that request through the API's decision path. + * Anything else shows the choice again, so the request stays the session's last + * activity (a thought would end its waiting-for-input state and bury it). + */ +async function decideSessionApproval( + request: AgentSessionRequest, + task: PriorTask, + requestId: string, + platformUserId: string, + emit: SessionEmit, + accessToken: string, +): Promise { + const again = async (lead: string) => { + const activity = repeatedApprovalChoice(lead, requestId, (await readOpenRequest(task.task_id, requestId)).ruleIds); + await emit(activity.content, false, activity); + }; + const answer = parseSessionApprovalAnswer(request.directive); + if (!answer) { + await again('That isn\'t an answer to the open approval request, so I haven\'t passed it to the agent.'); + return; + } + // A button names the request it was shown with; an older choice clicked late must + // not decide the request that is open now. + if (answer.requestId && answer.requestId !== requestId) { + await again('That answer was for an earlier request, which is no longer open, so nothing was decided.'); + return; + } + if (task.user_id !== platformUserId) { + await again(`Only the task owner can decide this request. ${NOT_OWNER_MESSAGE}`); + return; + } + if (!TASK_APPROVALS_TABLE_NAME) { + await emit({ type: 'thought', body: 'Approvals can\'t be answered in Linear on this deployment. Use `bgagent approve` / `bgagent deny`.' }); + return; + } + const prompt = await confirmedPrompt(request, answer, accessToken); + if (!prompt) { + logger.warn('Agent-session approval reply not confirmed by Linear โ€” no decision recorded', { + linear_agent_session_id: request.sessionId, task_id: task.task_id, request_id: requestId, + }); + await again('I couldn\'t confirm this answer with Linear, so nothing was decided.'); + return; + } + // An answer belongs to the request whose choice was showing when it was written. + // Both times are Linear's: the worker's own clock, and Lambda retry timing, play no + // part. A delivery retried after its request closed and another opened, or written + // before the new choice was posted, decides nothing. + const shown = await fetchSessionActivityShown( + accessToken, request.workspaceId, sessionApprovalNoticeId('approval_requested', requestId), + ); + if (shown?.sessionId !== request.sessionId || !(Date.parse(prompt.createdAt) > Date.parse(shown.createdAt))) { + await again('That answer was written before this request was shown here, so nothing was decided.'); + return; + } + const open = await readOpenRequest(task.task_id, requestId); + // Loaded only when a session decides: other session deliveries do not need the + // decision handlers' environment. + const record = answer.decision === 'approve' + ? (await import('../approve-task.js')).recordApprovalForUser + : (await import('../deny-task.js')).recordDenialForUser; + const ruleIds = answer.wholeTask ? open.ruleIds : []; + const ruleScope = ruleIds.length === 1 ? `rule:${ruleIds[0]}` : undefined; + const result = await record({ + userId: platformUserId, + taskId: task.task_id, + decisionSource: JSON.stringify(['linear_session', request.workspaceId, request.deliveryId]), + body: JSON.stringify({ + request_id: requestId, + decision: answer.decision, + ...(ruleScope && { scope: ruleScope }), + ...(answer.decision === 'deny' && answer.reason ? { reason: answer.reason } : {}), + }), + }); + logger.info('Agent-session approval reply', { + linear_agent_session_id: request.sessionId, + task_id: task.task_id, + request_id: requestId, + decision: answer.decision, + scope: ruleScope ?? 'this_call', + status_code: result.statusCode, + }); + await emit({ type: 'thought', body: sessionDecisionNote(answer, result, ruleScope) }); +} + +/** + * Linear's copy of this delivery when it is a human's prompt in this session, from + * the same person, with the same answer; else null. The decision is consent, so it + * is taken from Linear's copy, not the webhook's (see ``fetchSessionPromptActivity``). + */ +async function confirmedPrompt( + request: AgentSessionRequest, answer: SessionApprovalAnswer, accessToken: string, +): Promise { + const prompt = await fetchSessionPromptActivity(accessToken, request.workspaceId, request.deliveryId); + const echoed = prompt ? parseSessionApprovalAnswer(prompt.body) : null; + const same = prompt?.sessionId === request.sessionId && prompt.authorId === request.actorId + && echoed?.decision === answer.decision && (echoed.reason ?? '') === (answer.reason ?? '') + && Boolean(echoed.wholeTask) === Boolean(answer.wholeTask) && echoed.requestId === answer.requestId; + return same ? prompt : null; +} + +/** The rules the open request matched, read consistently from its row, never from the reply. */ +async function readOpenRequest(taskId: string, requestId: string): Promise<{ ruleIds: string[] }> { + if (!TASK_APPROVALS_TABLE_NAME) return { ruleIds: [] }; + const { Item } = await ddb.send(new GetCommand({ + TableName: TASK_APPROVALS_TABLE_NAME, Key: { task_id: taskId, request_id: requestId }, ConsistentRead: true, + })); + const ids: unknown[] = Array.isArray(Item?.matching_rule_ids) ? Item.matching_rule_ids : []; + return { ruleIds: ids.filter((id): id is string => typeof id === 'string') }; +} + /** The prior task as read from the base table (strongly consistent). */ type PriorTask = LinearIssueTask & ClarifyHoldRow - & Pick + & Pick & { readonly status: TaskStatusType; readonly channel_metadata?: Readonly>; @@ -582,8 +730,9 @@ async function emitSessionActivity( request: AgentSessionRequest, content: AgentActivityContent, ephemeral: boolean, + signal?: Omit, ): Promise { - const result = await emitAgentActivity(accessToken, request.sessionId, content, { ephemeral }); + const result = await emitAgentActivity(accessToken, request.sessionId, content, { ephemeral, ...signal }); if (!result.ok) { // Best-effort: the task outcome is still delivered by the fan-out plane. logger.warn('Failed to emit Linear agent activity', { diff --git a/cdk/src/handlers/shared/linear-agent-session.ts b/cdk/src/handlers/shared/linear-agent-session.ts index 532bf0f8a..6f5de8c0c 100644 --- a/cdk/src/handlers/shared/linear-agent-session.ts +++ b/cdk/src/handlers/shared/linear-agent-session.ts @@ -76,11 +76,24 @@ export async function emitAgentActivity( accessToken: string, agentSessionId: string, content: AgentActivityContent, - options: { readonly ephemeral?: boolean } = {}, + options: { + readonly ephemeral?: boolean; + readonly id?: string; + /** ``select`` turns an elicitation into buttons; ``signalMetadata.options`` lists them. */ + readonly signal?: 'select'; + readonly signalMetadata?: Readonly>; + } = {}, ): Promise { const ephemeral = options.ephemeral === true && (content.type === 'thought' || content.type === 'action'); return graphqlRequest(accessToken, AGENT_ACTIVITY_CREATE_MUTATION, { - input: { agentSessionId, content, ...(ephemeral && { ephemeral: true }) }, + // `id` (a version-4 UUID) makes a retried emit the same activity rather than a second one. + input: { + agentSessionId, + content, + ...(ephemeral && { ephemeral: true }), + ...(options.id && { id: options.id }), + ...(options.signal && { signal: options.signal, signalMetadata: options.signalMetadata ?? {} }), + }, }); } @@ -99,6 +112,18 @@ export async function addAgentSessionExternalUrl( }); } +/** + * Replace the session's checklist (Linear's ``plan``, technology preview). The whole + * list goes on every call. + */ +export async function setAgentSessionPlan( + accessToken: string, + agentSessionId: string, + steps: readonly { readonly content: string; readonly status: string }[], +): Promise { + return graphqlRequest(accessToken, AGENT_SESSION_UPDATE_MUTATION, { id: agentSessionId, input: { plan: steps } }); +} + export interface AgentSessionIssue { readonly id: string; readonly identifier: string | null; @@ -132,6 +157,93 @@ export async function fetchAgentSessionIssue( }); } +/** A human's prompt in a session, as Linear records it. */ +export interface SessionPromptActivity { + readonly sessionId: string; + readonly authorId: string; + readonly body: string; + /** When the person wrote it (ISO), as Linear records it. */ + readonly createdAt: string; +} + +const SESSION_PROMPT_QUERY = ` +query VerifySessionPrompt($id: String!) { + organization { id } + viewer { id } + agentActivity(id: $id) { + createdAt + agentSession { id } + content { __typename ... on AgentActivityPromptContent { body } } + user { id app } + promptAuthor { id app } + } +}`; + +/** + * Read a session prompt back from Linear before acting on it as consent. Webhook + * authentication alone is not enough: legacy worker credentials can read the OAuth + * bundle that holds the webhook signing key (the comment path reads its replies back + * for the same reason, ``readLinearApprovalComment``). Null when the activity is not a + * human's prompt: missing, not a prompt, written by an app, or by this token's own + * identity. Throws when Linear cannot answer, so the delivery retries instead of + * falling back to the webhook's fields. + */ +export async function fetchSessionPromptActivity( + accessToken: string, + workspaceId: string, + activityId: string, +): Promise { + const result = await graphqlData(accessToken, SESSION_PROMPT_QUERY, { id: activityId }); + if (!result.ok) throw new Error('Linear session prompt verification unavailable'); + const data = result.value as { + organization?: { id?: string }; + viewer?: { id?: string }; + agentActivity?: { + createdAt?: string; + agentSession?: { id?: string } | null; + content?: { __typename?: string; body?: string } | null; + user?: { id?: string; app?: boolean } | null; + promptAuthor?: { id?: string; app?: boolean } | null; + } | null; + }; + if (data.organization?.id !== workspaceId) throw new Error('Linear session prompt verification workspace mismatch'); + const viewerId = data.viewer?.id; + if (!viewerId) throw new Error('Linear session prompt verification identity unavailable'); + const activity = data.agentActivity; + const author = activity?.promptAuthor ?? activity?.user; + const sessionId = activity?.agentSession?.id; + if (activity?.content?.__typename !== 'AgentActivityPromptContent' || !sessionId + || !author?.id || author.app || author.id === viewerId) return null; + return { sessionId, authorId: author.id, body: activity.content.body ?? '', createdAt: activity.createdAt ?? '' }; +} + +const SESSION_ACTIVITY_QUERY = ` +query SessionActivityShown($id: String!) { + organization { id } + agentActivity(id: $id) { createdAt agentSession { id } } +}`; + +/** + * When Linear recorded one of this app's activities, and in which session; null when + * it does not exist. Throws when Linear cannot answer, so the caller retries. + */ +export async function fetchSessionActivityShown( + accessToken: string, + workspaceId: string, + activityId: string, +): Promise<{ readonly sessionId: string; readonly createdAt: string } | null> { + const result = await graphqlData(accessToken, SESSION_ACTIVITY_QUERY, { id: activityId }); + if (!result.ok) throw new Error('Linear session activity lookup unavailable'); + const data = result.value as { + organization?: { id?: string }; + agentActivity?: { createdAt?: string; agentSession?: { id?: string } | null } | null; + }; + if (data.organization?.id !== workspaceId) throw new Error('Linear session activity lookup workspace mismatch'); + const sessionId = data.agentActivity?.agentSession?.id; + const createdAt = data.agentActivity?.createdAt; + return sessionId && createdAt ? { sessionId, createdAt } : null; +} + /** Separator + heading that introduces Linear's `promptContext` in the description. */ const SESSION_CONTEXT_PREFIX = '\n\n## Linear session context\n\n'; const CONTEXT_TRUNCATION_NOTICE = '\n\n_(session context truncated)_'; diff --git a/cdk/src/handlers/shared/linear-approval-reply.ts b/cdk/src/handlers/shared/linear-approval-reply.ts new file mode 100644 index 000000000..77c5c9c2a --- /dev/null +++ b/cdk/src/handlers/shared/linear-approval-reply.ts @@ -0,0 +1,140 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { GetCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { + closeLinearApprovalThread, linearApprovalCommentId, parseLinearApprovalReply, readLinearApprovalThread, + type LinearApprovalReply, +} from './linear-approval-thread'; +import { postIdentifiedComment, readLinearApprovalComment } from './linear-feedback'; +import { logger } from './logger'; + +interface ApprovalReplyEvent { + action: string; + organizationId?: string; + actor?: { id?: string }; + data: { id: string; body?: string; parentId?: string; issueId?: string; issue?: { id?: string } }; +} + +interface ApprovalReplyDependencies { + ddb: DynamoDBDocumentClient; + approvalsTable: string; + taskTable: string; + registryTable: string; + lookupUser: (workspaceId: string, actorId: string) => Promise; +} + +function sameReply(a: LinearApprovalReply | null, b: LinearApprovalReply): boolean { + return a?.decision === b.decision && (a.reason ?? '') === (b.reason ?? ''); +} + +/** A verified webhook may decide only the exact gate bound to its thread. */ +export async function handleLinearApprovalReply( + event: ApprovalReplyEvent, deps: ApprovalReplyDependencies, +): Promise { + const reply = parseLinearApprovalReply(event.data.body); + const workspaceId = event.organizationId; + const parentId = event.data.parentId; + if (event.action !== 'create' || !reply || !workspaceId || !parentId || !event.data.id) return false; + const { decision } = reply; + const thread = await readLinearApprovalThread(deps.ddb, deps.approvalsTable, workspaceId, parentId); + if (!thread) return false; + const issueId = event.data.issueId ?? event.data.issue?.id; + if (issueId !== thread.issueId) return true; + const ctx = { linearWorkspaceId: workspaceId, registryTableName: deps.registryTable }; + const comment = await readLinearApprovalComment(ctx, event.data.id); + if (!comment || comment.id !== event.data.id || comment.botActor || !comment.user?.id + || comment.issue?.id !== issueId || comment.parent?.id !== parentId + || !sameReply(parseLinearApprovalReply(comment.body), reply)) { + logger.warn('Linear approval webhook does not match a human comment', { + task_id: thread.taskId, request_id: thread.requestId, comment_id: event.data.id, + }); + return true; + } + const respond = async (body: string): Promise => { + const posted = await postIdentifiedComment(ctx, { + id: linearApprovalCommentId({ ...thread, requestId: `${thread.requestId}#reply#${event.data.id}` }), + issueId, + parentId, + body, + }); + if (!posted.ok) { + logger.warn('Linear approval acknowledgement failed', { + task_id: thread.taskId, request_id: thread.requestId, comment_id: event.data.id, retryable: posted.retryable, + }); + if (posted.retryable) throw new Error('Retryable Linear approval acknowledgement failure'); + } + }; + const userId = await deps.lookupUser(workspaceId, comment.user.id); + if (!userId || userId !== thread.userId) { + await respond('Only the task owner can decide this request. Link your Linear account to ABCA, then reply again.'); + return true; + } + const task = (await deps.ddb.send(new GetCommand({ + TableName: deps.taskTable, Key: { task_id: thread.taskId }, ConsistentRead: true, + }))).Item; + if (!task || task.user_id !== userId || task.channel_source !== 'linear' + || task.channel_metadata?.linear_workspace_id !== workspaceId + || task.channel_metadata?.linear_issue_id !== issueId) { + await respond('This approval is no longer available for this task. No decision was recorded.'); + return true; + } + const source = JSON.stringify(['linear', workspaceId, event.data.id]); + const expectedStatus = decision === 'approve' ? 'APPROVED' : 'DENIED'; + const readApproval = async () => (await deps.ddb.send(new GetCommand({ + TableName: deps.approvalsTable, Key: { task_id: thread.taskId, request_id: thread.requestId }, ConsistentRead: true, + }))).Item; + const alreadyRecorded = (row: Awaited>) => + row?.user_id === userId && row.status === expectedStatus && row.decision_source === source; + let recorded = alreadyRecorded(await readApproval()); + if (!recorded) { + // Loaded only for configured approval integrations; ordinary comment paths + // do not require the decision handlers' environment variables. + const record = decision === 'approve' + ? (await import('../approve-task.js')).recordApprovalForUser + : (await import('../deny-task.js')).recordDenialForUser; + const result = await record({ + userId, + taskId: thread.taskId, + decisionSource: source, + // The verified comment body (read back from Linear), not the webhook copy. + body: JSON.stringify({ + request_id: thread.requestId, + decision, + ...(decision === 'deny' && reply.reason ? { reason: reply.reason } : {}), + }), + }); + recorded = result.statusCode === 202 || alreadyRecorded(await readApproval()); + if (!recorded) { + if (result.statusCode >= 500) throw new Error(`Linear approval decision failed: HTTP ${result.statusCode}`); + await respond(result.statusCode === 429 + ? 'Too many approval decisions. Wait a minute, then send a new reply.' + : 'This request is already closed, expired, or no longer waiting. No new decision was recorded.'); + return true; + } + } + await closeLinearApprovalThread(deps.ddb, deps.approvalsTable, thread); + await respond(decision === 'approve' + ? 'Approved for this action once. The decision is saved and the agent continues.' + : 'Denied. The decision is saved and the agent receives your denial.'); + logger.info('Linear approval reply recorded', { + task_id: thread.taskId, request_id: thread.requestId, comment_id: event.data.id, decision, + }); + return true; +} diff --git a/cdk/src/handlers/shared/linear-approval-thread.ts b/cdk/src/handlers/shared/linear-approval-thread.ts new file mode 100644 index 000000000..ded628758 --- /dev/null +++ b/cdk/src/handlers/shared/linear-approval-thread.ts @@ -0,0 +1,112 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { createHash } from 'node:crypto'; +import { GetCommand, UpdateCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { computeTtlEpoch } from './validation'; + +export interface LinearApprovalThread { + readonly workspaceId: string; + readonly issueId: string; + readonly taskId: string; + readonly requestId: string; + readonly userId: string; +} + +/** Linear requires UUIDv4; stable hash-derived bits make comment retries address the same ID. */ +export function linearApprovalCommentId(thread: LinearApprovalThread): string { + const hash = createHash('sha256').update(JSON.stringify([ + 'abca-linear-approval-v1', thread.workspaceId, thread.issueId, thread.taskId, thread.requestId, + ])).digest('hex'); + const groups = hash.match(/^(.{8})(.{4}).(.{3}).(.{3})(.{12})/)!; + return `${groups[1]}-${groups[2]}-4${groups[3]}-a${groups[4]}-${groups[5]}`; +} + +function threadKey(workspaceId: string, commentId: string): { task_id: string; request_id: string } { + return { task_id: `LINEAR_COMMENT#${workspaceId}#${commentId}`, request_id: 'APPROVAL' }; +} + +/** Mapping is coordinator-owned: task-scoped worker credentials cannot write this key. */ +export async function saveLinearApprovalThread( + ddb: DynamoDBDocumentClient, tableName: string, thread: LinearApprovalThread, +): Promise { + const commentId = linearApprovalCommentId(thread); + await ddb.send(new UpdateCommand({ + TableName: tableName, + Key: threadKey(thread.workspaceId, commentId), + UpdateExpression: 'SET #kind = :kind, #thread = :thread', + ConditionExpression: 'attribute_not_exists(task_id) OR (#kind = :kind AND #thread = :thread)', + ExpressionAttributeNames: { '#kind': 'kind', '#thread': 'thread' }, + ExpressionAttributeValues: { ':kind': 'linear_approval_thread', ':thread': thread }, + })); + return commentId; +} + +export async function readLinearApprovalThread( + ddb: DynamoDBDocumentClient, tableName: string, workspaceId: string, commentId: string, +): Promise { + const result = await ddb.send(new GetCommand({ + TableName: tableName, Key: threadKey(workspaceId, commentId), ConsistentRead: true, + })); + const thread = result.Item?.thread as LinearApprovalThread | undefined; + if (result.Item?.kind !== 'linear_approval_thread' || !thread + || ![thread.workspaceId, thread.issueId, thread.taskId, thread.requestId, thread.userId] + .every(value => typeof value === 'string' && value.length > 0) + || thread.workspaceId !== workspaceId || linearApprovalCommentId(thread) !== commentId) return null; + return thread; +} + +/** Pending mappings have no TTL, like pending approvals; closure starts retention. */ +export async function closeLinearApprovalThread( + ddb: DynamoDBDocumentClient, tableName: string, thread: LinearApprovalThread, +): Promise { + try { + await ddb.send(new UpdateCommand({ + TableName: tableName, + Key: threadKey(thread.workspaceId, linearApprovalCommentId(thread)), + UpdateExpression: 'SET #ttl = if_not_exists(#ttl, :ttl)', + ConditionExpression: 'attribute_exists(task_id)', + ExpressionAttributeNames: { '#ttl': 'ttl' }, + ExpressionAttributeValues: { ':ttl': computeTtlEpoch(Number(process.env.TASK_RETENTION_DAYS ?? '90')) }, + })); + } catch (error) { + if ((error as { name?: string }).name !== 'ConditionalCheckFailedException') throw error; + } +} + +export interface LinearApprovalReply { + readonly decision: 'approve' | 'deny'; + /** Optional free text after ``deny``; never accepted after ``approve``. */ + readonly reason?: string; +} + +/** + * Only an explicit answer in an approval thread is a decision, never prose or an + * edit: ``approve`` alone, or ``deny`` optionally followed by a reason + * (``deny use staging``, ``deny: use staging``). Anything else is not a decision. + */ +export function parseLinearApprovalReply(body: unknown): LinearApprovalReply | null { + if (typeof body !== 'string') return null; + const trimmed = body.trim(); + if (/^approve[.!]?$/i.test(trimmed)) return { decision: 'approve' }; + const deny = /^deny(?:[.!]?$|[\s:-]+([\s\S]+))/i.exec(trimmed); + if (!deny) return null; + const reason = deny[1]?.trim(); + return reason ? { decision: 'deny', reason } : { decision: 'deny' }; +} diff --git a/cdk/src/handlers/shared/linear-channel-metadata.ts b/cdk/src/handlers/shared/linear-channel-metadata.ts index 592ccb660..e8744a69f 100644 --- a/cdk/src/handlers/shared/linear-channel-metadata.ts +++ b/cdk/src/handlers/shared/linear-channel-metadata.ts @@ -55,6 +55,8 @@ export async function lookupLinearPlatformUser( const result = await ddb.send(new GetCommand({ TableName: userMappingTableName, Key: { linear_identity: `${workspaceId}#${userId}` }, + // Decisions (approval replies, a session stop) are authorized from this mapping. + ConsistentRead: true, })); if (!result.Item || result.Item.status === 'pending') return null; return (result.Item.platform_user_id as string) ?? null; diff --git a/cdk/src/handlers/shared/linear-console.ts b/cdk/src/handlers/shared/linear-console.ts index 9c763b713..e6b3e1916 100644 --- a/cdk/src/handlers/shared/linear-console.ts +++ b/cdk/src/handlers/shared/linear-console.ts @@ -19,6 +19,7 @@ import { ConditionalCheckFailedException } from '@aws-sdk/client-dynamodb'; import { DeleteCommand, type DynamoDBDocumentClient, GetCommand, PutCommand } from '@aws-sdk/lib-dynamodb'; +import { redactValue } from './deny-reason-scanner'; /** * Linear helpers for the operator console: list a mapped project's open issues, and @@ -50,7 +51,7 @@ async function linearQuery(accessToken: string, query: string, variables: Rec resp = await fetchImpl(LINEAR_GRAPHQL_URL, { method: 'POST', headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' }, - body: JSON.stringify({ query, variables }), + body: JSON.stringify({ query, variables: redactValue(variables) }), signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), }); } catch (err) { diff --git a/cdk/src/handlers/shared/linear-feedback.ts b/cdk/src/handlers/shared/linear-feedback.ts index d82525bcd..ae84b0259 100644 --- a/cdk/src/handlers/shared/linear-feedback.ts +++ b/cdk/src/handlers/shared/linear-feedback.ts @@ -17,6 +17,7 @@ * SOFTWARE. */ +import { redactValue } from './deny-reason-scanner'; import { isTerminalMaturingReply, preservePreviewSuffix } from './iteration-reply'; import { resolveLinearOauthToken } from './linear-oauth-resolver'; import { logger } from './logger'; @@ -255,7 +256,7 @@ export async function graphqlData( const resp = await fetch(LINEAR_GRAPHQL_URL, { method: 'POST', headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' }, - body: JSON.stringify({ query, variables }), + body: JSON.stringify({ query, variables: redactValue(variables) }), signal: controller.signal, }); if (!resp.ok) { @@ -308,7 +309,7 @@ export async function graphqlRequest( 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json', }, - body: JSON.stringify({ query, variables }), + body: JSON.stringify({ query, variables: redactValue(variables) }), signal: controller.signal, }); if (!resp.ok) { @@ -389,6 +390,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 @@ -841,6 +911,7 @@ function pickState( states: readonly TeamState[], type: string, preferredNames: readonly string[], + requirePreferredName: boolean, ): TeamState | null { const ofType = states.filter((s) => s.type === type); if (ofType.length === 0) return null; @@ -848,6 +919,7 @@ function pickState( const hit = ofType.find((s) => s.name.toLowerCase() === name.toLowerCase()); if (hit) return hit; } + if (requirePreferredName) return null; return [...ofType].sort((a, b) => a.position - b.position)[0]; } @@ -880,6 +952,12 @@ export async function transitionIssueState( * still ALWAYS blocked โ€” this only relaxes the same-type position tiebreak. */ allowSameTypeRegression = false, + /** + * Move only to a state named in ``preferredNames``. Without it a team that lacks + * the name gets its first state of ``targetType``, which for "In Review" is "In + * Progress": the wrong move for a caller that means review specifically. + */ + requirePreferredName = false, ): Promise { const token = await resolveToken(ctx); if (!token) return false; @@ -894,7 +972,7 @@ export async function transitionIssueState( return false; } - const target = pickState(states, targetType, preferredNames); + const target = pickState(states, targetType, preferredNames, requirePreferredName); if (!target) { logger.warn('Linear state transition: no state of target type', { issue_id: issueId, target_type: targetType }); return false; @@ -989,8 +1067,8 @@ export async function revertIssueToNotStarted( // Prefer an unstarted "Todo" (the natural "not started, waiting" state); fall // back to backlog. Within a type, prefer the named state, else lowest position. - const target = pickState(states, 'unstarted', ['Todo', 'To Do']) - ?? pickState(states, 'backlog', ['Backlog', 'Triage']); + const target = pickState(states, 'unstarted', ['Todo', 'To Do'], false) + ?? pickState(states, 'backlog', ['Backlog', 'Triage'], false); if (!target) { logger.info('Revert-to-not-started: no unstarted/backlog state on the team โ€” leaving it', { issue_id: issueId }); return false; diff --git a/cdk/src/handlers/shared/linear-grant-health.ts b/cdk/src/handlers/shared/linear-grant-health.ts new file mode 100644 index 000000000..1d0c2da94 --- /dev/null +++ b/cdk/src/handlers/shared/linear-grant-health.ts @@ -0,0 +1,128 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Scheduled Linear grant health probe (#1004). + * + * Revocation detection (#812) runs only when something needs a Linear token, which + * means when a Linear event arrives. A workspace whose webhook stopped delivering, or + * that nobody used for a while, therefore never re-detects a dead grant: observed + * live, a workspace sat with an expired refresh token for months with one ERROR log + * line. Linear refresh tokens also expire when unused, so the outage was preventable. + * + * The probe resolves a token for every active workspace on a schedule. That does two + * jobs with the existing code path: + * - it refreshes expiring access tokens, which keeps an idle refresh token alive; + * - a grant Linear rejects goes through the resolver's revocation recorder, which + * latches the workspace and announces it on OperationalAlerts (once). + */ + +import { ScanCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; + +/** How often each workspace is probed. Linear access tokens last about a day. */ +const GRANT_HEALTH_PROBE_INTERVAL_HOURS = 12; + +const MS_PER_MINUTE = 60_000; +const MS_PER_HOUR = 3_600_000; + +/** Async invocation payload that selects probe mode in the webhook processor. */ +export const GRANT_HEALTH_PROBE_EVENT = { grant_health_probe: true } as const; + +export function isGrantHealthProbe(event: unknown): event is typeof GRANT_HEALTH_PROBE_EVENT { + return typeof event === 'object' && event !== null + && (event as Record).grant_health_probe === true; +} + +/** + * True on exactly one tick per interval for a job that runs every `tickMinutes`: + * the tick falling in the half-open window `[k * interval, k * interval + tick)`. + * Ticks are `tick` apart, so each window holds exactly one. A nonsensical cadence + * probes every tick rather than never, so a misconfiguration cannot silently + * disable detection. + */ +export function isProbeTick( + nowMs: number, + tickMinutes: number, + intervalHours: number = GRANT_HEALTH_PROBE_INTERVAL_HOURS, +): boolean { + const tickMs = tickMinutes * MS_PER_MINUTE; + const intervalMs = intervalHours * MS_PER_HOUR; + if (!(tickMs > 0) || !(intervalMs > 0) || tickMs >= intervalMs) return true; + return nowMs % intervalMs < tickMs; +} + +export interface GrantHealthReport { + readonly checked: number; + readonly healthy: number; + /** Slugs (or ids when a row has no slug) whose token could not be resolved. */ + readonly unhealthy: readonly string[]; + /** Rows already latched `revoked`; not re-probed, they were already announced. */ + readonly revoked: readonly string[]; +} + +interface RegistryRow { + readonly linear_workspace_id?: string; + readonly workspace_slug?: string; + readonly status?: string; +} + +/** + * Resolve a token for every active registry row, sequentially (a handful of + * workspaces; sequential keeps the probe gentle on Linear's token endpoint). + */ +export async function probeLinearGrants( + ddb: DynamoDBDocumentClient, + registryTableName: string, + resolve: (linearWorkspaceId: string) => Promise, +): Promise { + const rows: RegistryRow[] = []; + let startKey: Record | undefined; + do { + const page = await ddb.send(new ScanCommand({ + TableName: registryTableName, + ProjectionExpression: 'linear_workspace_id, workspace_slug, #status', + ExpressionAttributeNames: { '#status': 'status' }, + ExclusiveStartKey: startKey, + })); + rows.push(...(page.Items ?? []) as RegistryRow[]); + startKey = page.LastEvaluatedKey; + } while (startKey); + + let healthy = 0; + const unhealthy: string[] = []; + const revoked: string[] = []; + let checked = 0; + for (const row of rows) { + if (!row.linear_workspace_id) continue; + const label = row.workspace_slug ?? row.linear_workspace_id; + if (row.status !== 'active') { + revoked.push(label); + continue; + } + checked++; + try { + if (await resolve(row.linear_workspace_id)) healthy++; + else unhealthy.push(label); + } catch { + // One workspace's failure must not hide the others. + unhealthy.push(label); + } + } + return { checked, healthy, unhealthy, revoked }; +} diff --git a/cdk/src/handlers/shared/linear-session-approval.ts b/cdk/src/handlers/shared/linear-session-approval.ts new file mode 100644 index 000000000..f1cefac1d --- /dev/null +++ b/cdk/src/handlers/shared/linear-session-approval.ts @@ -0,0 +1,224 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Cedar approval requests answered inside a Linear agent session (#1066). + * + * The fan-out posts a pending request as an ``elicitation`` with Approve / Deny + * buttons (``signal: select``) and a reply-by line, using the same notice text as + * the comment channel (``approval-notifications.ts``, so the same redaction and + * escaping). A reply in the session decides the task's open request through the + * API's decision path (``recordApprovalForUser`` / ``recordDenialForUser``): only + * the task's owner can decide, and a request that already timed out or was + * answered is left alone. The open request is the task record's + * ``awaiting_approval_request_id``, so a session needs no pointer rows. + */ + +import { approvalNotificationMarkdown, type ApprovalNotification } from './approval-notifications'; +import type { AgentActivityContent } from './linear-agent-session'; +import { parseLinearApprovalReply, type LinearApprovalReply } from './linear-approval-thread'; +import { progressActivityId } from './linear-session-progress'; + +/** + * An answer from the session: approve once, approve the request's rule for the rest + * of the task, or deny. ``requestId`` is set when the answer came from a button, + * which names the request it was shown with. + */ +export type SessionApprovalAnswer = LinearApprovalReply & { readonly wholeTask?: boolean; readonly requestId?: string }; + +/** A button value names its request: ``approve request ``. Request ids are ULIDs. */ +const BUTTON_REQUEST = /^(approve|approve for this task|deny) request ([0-9A-HJKMNP-TV-Z]{26})$/i; +const WHOLE_TASK = /^approve\s+for\s+(?:this|the)\s+(?:whole\s+)?task[.!]?$/i; + +/** + * A reply that answers an approval request, or null: a button's value, or a typed + * ``approve``, ``approve for this task`` or ``deny [reason]``. + * @param text - the reply. + */ +export function parseSessionApprovalAnswer(text: string): SessionApprovalAnswer | null { + const trimmed = text.trim(); + const button = BUTTON_REQUEST.exec(trimmed); + if (button) { + const verb = button[1].toLowerCase(); + return verb === 'deny' ? { decision: 'deny', requestId: button[2] } + : { decision: 'approve', requestId: button[2], ...(verb !== 'approve' && { wholeTask: true }) }; + } + if (WHOLE_TASK.test(trimmed)) return { decision: 'approve', wholeTask: true }; + return parseLinearApprovalReply(text); +} + +/** + * An answer with nothing left to answer: a button's value, or approve / deny alone. + * ``deny `` is not one, because with no request open it reads as an instruction + * ("deny anonymous access to /admin"). + * @param text - the prompt. + */ +export function isBareApprovalAnswer(text: string): boolean { + const answer = parseSessionApprovalAnswer(text); + return answer !== null && !answer.reason; +} + +/** + * The session activity id of an approval notice: derived from the event and the + * request, so a retried notice is the same activity and the reply handler can read + * back when a request's choice was shown. + * @param eventType - the approval event (``approval_requested`` for the choice). + * @param requestId - the request. + */ +export function sessionApprovalNoticeId(eventType: string, requestId: string): string { + return progressActivityId(`notified_linear_session_${eventType}#${requestId}`); +} + +/** One activity plus the options ``emitAgentActivity`` takes. */ +export interface SessionApprovalActivity { + readonly content: AgentActivityContent; + readonly signal?: 'select'; + readonly signalMetadata?: Readonly>; +} + +const MINUTE_MS = 60_000; +const MINUTES_PER_HOUR = 60; +const HOURS_PER_DAY = 24; +const ISO_CLOCK = { start: 11, end: 16 } as const; +const ISO_DATE_END = 10; +const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] as const; +const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] as const; + +/** ``in 30 min``, ``in 3 h``, ``in 2 days``, ``now``. */ +function relativeTime(ms: number): string { + const min = Math.round(ms / MINUTE_MS); + if (min <= 0) return 'now'; + if (min < MINUTES_PER_HOUR * 2) return `in ${min} min`; + const hours = Math.round(min / MINUTES_PER_HOUR); + if (hours < HOURS_PER_DAY * 2) return `in ${hours} h`; + return `in ${Math.round(hours / HOURS_PER_DAY)} days`; +} + +/** + * A deadline as a person reads it: ``21:40 UTC (in 30 min)``, with the date when it + * is not today (``Tue 17 Nov, 09:40 UTC (in 12 h)``). Null for an unparseable time. + * @param iso - the deadline. + * @param now - the reference time. + */ +export function formatDeadline(iso: string, now: Date = new Date()): string | null { + const at = new Date(iso); + if (Number.isNaN(at.getTime())) return null; + const hhmm = at.toISOString().slice(ISO_CLOCK.start, ISO_CLOCK.end); + const sameDay = at.toISOString().slice(0, ISO_DATE_END) === now.toISOString().slice(0, ISO_DATE_END); + const day = sameDay ? '' : `${WEEKDAYS[at.getUTCDay()]} ${at.getUTCDate()} ${MONTHS[at.getUTCMonth()]}, `; + return `${day}${hhmm} UTC (${relativeTime(at.getTime() - now.getTime())})`; +} + +/** + * The line that says the reader has to act, and by when. + * @param deadline - when the request is denied unanswered (ISO), if it has one. + * @param now - the reference time. + */ +export function waitingOnYouLine(deadline: string | undefined, now: Date = new Date()): string { + const when = deadline ? formatDeadline(deadline, now) : null; + return when + ? `**Waiting on you.** Reply by ${when}, or it is denied and the agent carries on without it.` + : '**Waiting on you.** The agent is paused until you answer.'; +} + +/** + * The buttons for one request, as ``emitAgentActivity`` options. Each value names the + * request, so a click on an older choice cannot decide a later request. "Approve for + * this task" is offered only when the request matched exactly one rule: the agent + * treats a rule approval as covering any later request that rule is among, so + * approving one of several matched rules would also pass requests the others raise. + */ +function choice(body: string, requestId: string, ruleIds?: readonly string[]): SessionApprovalActivity { + const option = (label: string, verb: string) => ({ label, value: `${verb} request ${requestId}` }); + const options = [ + option('Approve', 'approve'), + ...(ruleIds?.length === 1 ? [option('Approve for this task', 'approve for this task')] : []), + option('Deny', 'deny'), + ]; + return { content: { type: 'elicitation', body }, signal: 'select', signalMetadata: { options } }; +} + +/** + * The session activity for an approval notice: a pending request is a choice with + * buttons; a decision, a timeout or a stranded wait is a thought. + * @param eventType - the approval event. + * @param notification - the notice loaded for the ``linear_session`` channel. + * @param now - the reference time for the deadline. + */ +export function sessionApprovalActivity( + eventType: string, notification: ApprovalNotification, now: Date = new Date(), +): SessionApprovalActivity { + const body = approvalNotificationMarkdown(notification); + if (eventType === 'approval_requested') { + return choice(`${body}\n\n${waitingOnYouLine(notification.deadline, now)}`, notification.requestId, notification.ruleIds); + } + return { content: { type: 'thought', body } }; +} + +/** + * The choice again, with a line above it. Posted when a reply could not decide the + * request, so the request stays the session's last activity and Linear keeps + * showing the session as waiting for input. + * @param lead - why it is shown again. + * @param requestId - the open request. + * @param ruleIds - the rules it matched, when known. + */ +export function repeatedApprovalChoice(lead: string, requestId: string, ruleIds?: readonly string[]): SessionApprovalActivity { + return choice(`${lead}\n\nChoose **Approve** or **Deny**, or reply deny with a reason.`, requestId, ruleIds); +} + +/** What the decision handlers return. */ +export interface DecisionResult { readonly statusCode: number } + +const HTTP_OK_MIN = 200; +const HTTP_OK_END = 300; +const HTTP_NOT_FOUND = 404; +const HTTP_CONFLICT = 409; +const HTTP_TOO_MANY = 429; + +/** + * The note after a decision was attempted. + * @param reply - the parsed answer. + * @param result - the decision handler's result. + */ +export function sessionDecisionNote( + reply: SessionApprovalAnswer, result: DecisionResult, ruleScope?: string, +): string { + if (result.statusCode >= HTTP_OK_MIN && result.statusCode < HTTP_OK_END) { + if (reply.wholeTask && ruleScope) { + return `Approved for the rest of this task: the agent won't ask again for \`${ruleScope}\`.`; + } + if (reply.wholeTask) { + return 'Approved this action only: it matched more than one rule, so I can\'t approve it for the whole task. ' + + 'The agent continues.'; + } + return reply.decision === 'approve' + ? 'Approved. The agent continues with this action.' + : `Denied. The agent carries on without it${reply.reason ? ` (your reason: ${reply.reason})` : ''}.`; + } + if (result.statusCode === HTTP_CONFLICT || result.statusCode === HTTP_NOT_FOUND) { + return 'That request was already answered or timed out, so nothing changed. The agent asks again if it still needs to.'; + } + if (result.statusCode === HTTP_TOO_MANY) return 'Too many approval decisions in the last minute. Reply again in a moment.'; + return 'I couldn\'t record that decision. Reply again, or use `bgagent approve` / `bgagent deny`.'; +} + +/** The reply to an approve / deny when nothing in the session is waiting for one. */ +export const NOTHING_TO_APPROVE_MESSAGE = 'Nothing is waiting for your approval here, so nothing was approved or denied. ' + + 'I haven\'t started or re-run anything. To ask for more work, say what you want done.'; diff --git a/cdk/src/handlers/shared/linear-session-checklist.ts b/cdk/src/handlers/shared/linear-session-checklist.ts new file mode 100644 index 000000000..93a3a5709 --- /dev/null +++ b/cdk/src/handlers/shared/linear-session-checklist.ts @@ -0,0 +1,129 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * The session checklist (Linear's ``AgentSession.plan``) and the closing line of the + * session's final message (#1066). Pure: the fan-out consumer does the writes. + * + * The checklist lists the stages a person cares about, from understanding the ticket + * to "ready for your review". Its position is kept on the task record + * (``linear_checklist_stage``), so it only moves forward whichever Lambda instance + * sees an event. + * + * The ``plan`` shape follows the Linear developer docs ("Agent Plans", technology + * preview): the whole list, replaced on every update, each step + * ``{ content, status: 'pending' | 'inProgress' | 'completed' | 'canceled' }``. + */ + +export type ChecklistStepStatus = 'pending' | 'inProgress' | 'completed' | 'canceled'; + +export interface ChecklistStep { + readonly content: string; + readonly status: ChecklistStepStatus; +} + +/** A new change, or an update to an existing pull request. */ +export type ChecklistKind = 'new' | 'iteration'; + +const PR_ITERATION_WORKFLOW = 'coding/pr-iteration-v1'; +const NEW_TASK_WORKFLOW = 'coding/new-task-v1'; + +/** Stage positions (the index of the step in progress). */ +export const CHECKLIST_STAGE = { understand: 0, setup: 1, code: 2, pr: 3, review: 4 } as const; + +const LABELS: Readonly> = { + new: ['Understand the ticket', 'Set up the repository', 'Write the code', 'Open the pull request', 'Ready for your review'], + iteration: ['Read the request', 'Set up the repository', 'Update the code', 'Push to the pull request', 'Ready for your review'], +}; + +/** + * The checklist a task's session gets, or null for a workflow that has no such stages + * (a repo-less workflow, a review). Records that predate ``resolved_workflow`` are coding tasks. + * @param workflowId - the task's resolved workflow id. + */ +export function checklistKind(workflowId: string | undefined): ChecklistKind | null { + if (workflowId === PR_ITERATION_WORKFLOW) return 'iteration'; + if (workflowId === undefined || workflowId === NEW_TASK_WORKFLOW) return 'new'; + return null; +} + +/** Where the checklist stands. */ +export interface ChecklistState { + readonly stage: number; + /** A few words on the step in progress ("queued for a free slot"). */ + readonly note?: string; + /** ``#12`` once the pull request exists. */ + readonly pr?: string; +} + +/** How the task ended: every step done, or the step in progress and the rest cancelled. */ +export type ChecklistEnding = 'done' | 'stopped'; + +/** + * The steps for ``state``: steps before the stage are completed, the stage is in + * progress (with its note), the rest are pending. + * @param kind - which wording. + * @param state - the stage, note and pull request. + * @param ending - set on the task's last write. + */ +export function renderChecklist(kind: ChecklistKind, state: ChecklistState, ending?: ChecklistEnding): ChecklistStep[] { + const labels = LABELS[kind]; + const stage = ending === 'done' ? labels.length : Math.max(0, Math.min(state.stage, labels.length - 1)); + return labels.map((label, i) => { + let status: ChecklistStepStatus = 'pending'; + if (i < stage) status = 'completed'; + else if (ending === 'stopped') status = 'canceled'; + else if (i === stage) status = 'inProgress'; + const extra = [i === CHECKLIST_STAGE.pr ? state.pr : undefined, i === stage ? state.note : undefined] + .filter((s): s is string => Boolean(s)).join(' ยท '); + return { content: extra ? `${label} โ€” ${extra}` : label, status }; + }); +} + +/** + * The stage an event moves the checklist to, or null when it does not. + * @param effectiveType - the event type, or a milestone's name. + */ +export function checklistMoveForEvent(effectiveType: string): Omit | null { + switch (effectiveType) { + case 'admission_queued': return { stage: CHECKLIST_STAGE.understand, note: 'queued for a free slot' }; + case 'hydration_complete': return { stage: CHECKLIST_STAGE.setup }; + case 'repo_setup_complete': return { stage: CHECKLIST_STAGE.code }; + case 'agent_execution_complete': return { stage: CHECKLIST_STAGE.pr }; + case 'pr_created': return { stage: CHECKLIST_STAGE.review }; + default: return null; + } +} + +/** How a finished task reads to the person who asked for it. */ +export type SessionOutcome = 'pr' | 'question' | 'no_change' | 'cancelled' | 'failed'; + +/** + * The last line of the session's final message: whether the reader has to act. + * @param outcome - how the task ended. + */ +export function closingLine(outcome: SessionOutcome): string { + switch (outcome) { + case 'pr': return '_Your turn: review the pull request. Reply here if it needs changes._'; + case 'question': return '**Waiting on you.** Nothing continues until you reply here.'; + case 'no_change': return '_Nothing needed from you. Reply here if you want a change after all._'; + case 'cancelled': return '_Nothing needed from you. Reply here to start again._'; + case 'failed': return '_Reply here to try again._'; + } +} diff --git a/cdk/src/handlers/shared/linear-session-progress.ts b/cdk/src/handlers/shared/linear-session-progress.ts new file mode 100644 index 000000000..e9a6ac29a --- /dev/null +++ b/cdk/src/handlers/shared/linear-session-progress.ts @@ -0,0 +1,213 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Task progress โ†’ Linear agent-session activities (ADR-018, #1066). + * + * The session already shows the acknowledgement, the PR, a throttled keep-alive and the + * final outcome (fanout-task-events.ts). This maps the events in between onto + * activities, so a run is visible while it happens: + * + * - the agent's own messages become persistent thoughts; + * - tool calls become an ephemeral action: the "currently doing" line, replaced + * by the next one rather than stacking up; + * - platform steps (queued, sandbox, context, clone) and agent milestones become + * persistent steps, except the queue and sandbox lines, which are ephemeral. + * + * Pure: no I/O. The dispatcher decides what to emit, caps the persistent ones per task + * and keeps them idempotent. + */ + +import { createHash } from 'node:crypto'; +import type { AgentActivityContent } from './linear-agent-session'; + +/** One activity to emit; ephemeral ones are replaced by the session's next activity. */ +export interface SessionProgressActivity { + readonly content: AgentActivityContent; + readonly ephemeral: boolean; +} + +/** + * Event types (as routed: an agent_milestone carries its milestone name) that matter + * only to agent sessions. The comment path ignores them, and the fan-out counts them + * apart from the events every channel needs, so a burst of them never pushes a PR or a + * terminal event out of a batch. + */ +export const LINEAR_SESSION_PROGRESS_EVENTS: ReadonlySet = new Set([ + 'agent_turn', + 'agent_tool_call', + 'admission_queued', + 'hydration_complete', + 'repo_setup_complete', + 'nudge_acknowledged', + 'attachments_downloaded', + 'agent_execution_complete', +]); + +/** Milestones the session uses; each must also be routable by name (ROUTABLE_MILESTONES). */ +export const LINEAR_SESSION_PROGRESS_MILESTONES: readonly string[] = [ + 'repo_setup_complete', + 'nudge_acknowledged', + 'attachments_downloaded', + // No activity of its own: it moves the session checklist to "Open the pull request". + 'agent_execution_complete', +]; + +const THOUGHT_MAX = 600; +const TOOL_PARAMETER_MAX = 120; +const BRANCH_MAX = 80; +/** A digest's hex digits as a UUID's fields, skipping the version and variant nibbles. */ +const UUID_FIELDS = /^(.{8})(.{4}).(.{3}).(.{3})(.{12})/; + +function clip(value: string, max: number): string { + const flat = value.replace(/\s+/g, ' ').trim(); + return flat.length <= max ? flat : `${flat.slice(0, max - 1).trimEnd()}โ€ฆ`; +} + +/** `k=v k=v` milestone details โ†’ a map (values without spaces). */ +function parseDetails(details: unknown): Record { + const out: Record = {}; + if (typeof details !== 'string') return out; + for (const m of details.matchAll(/(\w+)=(\S+)/g)) out[m[1]] = m[2]; + return out; +} + +/** + * A `'key': 'value'` pair of a tool-input preview: the agent writes the input dict's + * Python repr (`{'file_path': '...'}`), cut at a fixed length. Key and value quote + * independently, because repr switches a value to double quotes when it holds a + * single quote. A match consumes its whole value, so text inside a value is never + * read as a key. + */ +const INPUT_FIELD = /['"](\w+)['"]\s*:\s*(['"])((?:(?!\2)[^\\]|\\.)*)/g; + +/** The first non-empty string value among `keys`, in that order of preference. */ +function inputField(preview: unknown, keys: readonly string[]): string | undefined { + if (typeof preview !== 'string' || preview.length === 0) return undefined; + const values = new Map(); + for (const [, key, , value] of preview.matchAll(INPUT_FIELD)) { + if (value && !values.has(key)) values.set(key, value); + } + const value = keys.map((k) => values.get(k)).find((v) => v !== undefined); + return value?.replace(/\\(['"])/g, '$1').replace(/\\n/g, ' '); +} + +const WORKSPACE_PREFIX = /\/workspace\/[^/\s'"]+\/?/g; + +/** `/workspace//src/app.ts` โ†’ `src/app.ts`. */ +function repoRelative(p: string): string { + return p.replace(WORKSPACE_PREFIX, ''); +} + +/** `cd /workspace/; npm test` โ†’ `npm test`. */ +function readableCommand(cmd: string): string { + return cmd.replace(/^\s*cd\s+\/workspace\/[^\s;&]+\s*(?:;|&&)\s*/, '').replace(WORKSPACE_PREFIX, ''); +} + +const TOOL_VERBS: Readonly> = { + Read: { action: 'Reading', keys: ['file_path', 'path'], path: true }, + Edit: { action: 'Editing', keys: ['file_path'], path: true }, + MultiEdit: { action: 'Editing', keys: ['file_path'], path: true }, + Write: { action: 'Writing', keys: ['file_path'], path: true }, + NotebookEdit: { action: 'Editing', keys: ['notebook_path'], path: true }, + Bash: { action: 'Running', keys: ['command'] }, + Grep: { action: 'Searching', keys: ['pattern'] }, + Glob: { action: 'Finding files', keys: ['pattern'] }, + WebFetch: { action: 'Fetching', keys: ['url'] }, + WebSearch: { action: 'Searching the web', keys: ['query'] }, + Task: { action: 'Delegating', keys: ['description'] }, + TodoWrite: { action: 'Updating its plan', keys: [] }, +}; + +function toolActivity(meta: Record): SessionProgressActivity | null { + const tool = typeof meta.tool_name === 'string' ? meta.tool_name : ''; + if (!tool) return null; + const verb = TOOL_VERBS[tool]; + if (!verb) { + // An MCP or unknown tool: name it, without guessing at its input. + return { content: { type: 'action', action: `Using ${clip(tool, TOOL_PARAMETER_MAX)}`, parameter: '' }, ephemeral: true }; + } + const raw = inputField(meta.tool_input_preview, verb.keys); + const value = raw === undefined ? '' : verb.path ? repoRelative(raw) : readableCommand(raw); + const parameter = value ? `\`${clip(value, TOOL_PARAMETER_MAX).replace(/`/g, "'")}\`` : ''; + return { content: { type: 'action', action: verb.action, parameter }, ephemeral: true }; +} + +function milestoneActivity(name: string, details: unknown): SessionProgressActivity | null { + const d = parseDetails(details); + switch (name) { + case 'repo_setup_complete': + return { + content: { type: 'action', action: 'Cloned the repository', parameter: d.branch ? `on branch \`${clip(d.branch, BRANCH_MAX)}\`` : '' }, + ephemeral: false, + }; + case 'attachments_downloaded': + return { content: { type: 'action', action: 'Read the issue attachments', parameter: d.count ? `${d.count} file(s)` : '' }, ephemeral: false }; + case 'nudge_acknowledged': + return { content: { type: 'thought', body: 'Picked up your message and working it in.' }, ephemeral: false }; + default: + return null; + } +} + +/** + * The activity for one progress event, or null when it has nothing to show. + * @param effectiveType - the routed type (an `agent_milestone` carries its milestone name). + * @param metadata - the event's metadata. + */ +export function sessionProgressActivity( + effectiveType: string, + metadata: Record | undefined, +): SessionProgressActivity | null { + const meta = metadata ?? {}; + switch (effectiveType) { + case 'agent_turn': { + const text = typeof meta.text_preview === 'string' ? meta.text_preview.trim() : ''; + return text ? { content: { type: 'thought', body: clip(text, THOUGHT_MAX) }, ephemeral: false } : null; + } + case 'agent_tool_call': + return toolActivity(meta); + case 'admission_queued': { + // Ephemeral: the admission reconciler re-emits it with `waited_s` while the task + // waits, which also keeps a long wait from turning the session stale. + const waitedMin = Math.round(Number(meta.waited_s) / 60); + const lead = Number.isFinite(waitedMin) && waitedMin > 0 ? `Still queued (${waitedMin} min so far)` : 'Queued'; + return { + content: { type: 'thought', body: `${lead}: you already have the maximum number of tasks running. This one starts as soon as one finishes.` }, + ephemeral: true, + }; + } + case 'hydration_complete': + return { content: { type: 'action', action: 'Gathered the issue context', parameter: '' }, ephemeral: false }; + default: + return milestoneActivity(effectiveType, meta.details); + } +} + +/** + * A deterministic activity id for an event, so a redelivered or re-run record emits the + * same activity rather than a second one. Linear accepts only version-4 UUIDs, so the + * hash gets the v4 version and variant bits. + * @param seed - unique per activity (the task event id). + */ +export function progressActivityId(seed: string): string { + const hex = createHash('sha256').update(`linear-session-progress:${seed}`).digest('hex'); + const [, a, b, c, d, e] = UUID_FIELDS.exec(hex)!; + return `${a}-${b}-4${c}-a${d}-${e}`; +} diff --git a/cdk/src/handlers/shared/repo-config.ts b/cdk/src/handlers/shared/repo-config.ts index 57a123b4d..5374aecf3 100644 --- a/cdk/src/handlers/shared/repo-config.ts +++ b/cdk/src/handlers/shared/repo-config.ts @@ -67,6 +67,13 @@ export interface RepoConfig { * path falls back to the platform default of 50. */ readonly approval_gate_cap?: number; + /** + * Cedar HITL: per-blueprint default approval window in seconds, written by the + * Blueprint construct from ``security.approvalTimeoutSeconds``. Resolved at + * submit time onto the TaskRecord's ``approval_timeout_s`` (a request's own + * value wins). Absent: the platform default from ``contracts/constants.json``. + */ + readonly approval_timeout_s?: number; /** * Registry (#246) ``registry://`` refs for MCP servers pinned by the * blueprint. Resolved by the orchestrator at task start and merged into the diff --git a/cdk/src/handlers/shared/types.ts b/cdk/src/handlers/shared/types.ts index b0d810d3a..ad7c42f69 100644 --- a/cdk/src/handlers/shared/types.ts +++ b/cdk/src/handlers/shared/types.ts @@ -342,6 +342,11 @@ export interface TaskRecord { * appended link is never duplicated. */ readonly linear_session_pr_link_event_id?: string; + /** + * Stage the Linear agent session's checklist has reached (#1066). Written with a + * forward-only conditional update, so the checklist never moves back. + */ + readonly linear_checklist_stage?: number; /** * Event ID of the terminal event whose ordinary Jira final-status comment * was successfully posted (fan-out plane). This marker makes that create diff --git a/cdk/src/stacks/agent.ts b/cdk/src/stacks/agent.ts index 328448402..c182ba5d8 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -296,6 +296,17 @@ function linearAgentSessionsProps( }; } +/** + * Whether the Linear OAuth token vault is deployed. An explicit context value wins; + * otherwise `byDefault` (on when Linear and AgentCore are both deployed: see the call site). + */ +function resolveLinearIdentityVault(context: unknown, byDefault: boolean): boolean { + if (context === true || context === 'true') return true; + if (context === false || context === 'false') return false; + if (context !== undefined) throw new Error('enableLinearIdentityVault must be true or false'); + return byDefault; +} + export class AgentStack extends Stack { /** The REST API and its Cognito user pool; the operator console stack signs users in against these. */ public readonly taskApi: TaskApi; @@ -490,11 +501,17 @@ export class AgentStack extends Stack { // unchanged and introduces no new CFN types into the bootstrap policy set. const toolGatewayEnabled = features.toolGateway; - // RFC #249 Phase 1 (Linear OAuth token vault). Additive + default-off: - // resolved here (early) so the agent runtime env map + the LinearIdentityVault - // construct + the token grants all key off one predicate and cannot drift. - const linearIdentityVaultEnabled = this.node.tryGetContext('enableLinearIdentityVault') === true - || this.node.tryGetContext('enableLinearIdentityVault') === 'true'; + // RFC #249 Linear OAuth token vault (AgentCore Identity). Default ON wherever + // Linear and AgentCore are both deployed: AgentCore already proves the region + // has it, and the vault refreshes the Linear grant itself, so an idle workspace + // cannot strand an expired refresh token in Secrets Manager. Deployments without + // AgentCore default to Secrets Manager, and without Linear there is no grant to + // vault. `--context enableLinearIdentityVault=true|false` overrides the default + // (an explicit true without Linear still fails below). Resolved early so the + // runtime env map, the LinearIdentityVault construct and the token grants share + // one predicate. + const linearIdentityVaultEnabled = resolveLinearIdentityVault( + this.node.tryGetContext('enableLinearIdentityVault'), agentCoreEnabled && features.linear); if (linearIdentityVaultEnabled && !features.linear) { throw new Error('enableLinearIdentityVault requires the linear feature; enable Linear or drop the vault switch'); } @@ -1578,7 +1595,7 @@ export class AgentStack extends Stack { const concurrencyMaintenance = new NestedStack(this, 'ConcurrencyMaintenance'); // --- Concurrency counter reconciler (drift correction) --- - new ConcurrencyReconciler(concurrencyMaintenance, 'ConcurrencyReconciler', { + const concurrencyReconciler = new ConcurrencyReconciler(concurrencyMaintenance, 'ConcurrencyReconciler', { taskTable: taskTable.table, userConcurrencyTable: userConcurrencyTable.table, }); @@ -1747,6 +1764,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 @@ -2131,6 +2149,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 @@ -2265,6 +2284,9 @@ export class AgentStack extends Stack { // not exist yet at this point in the constructor. if (linearIntegration) { operationalAlerts.grantPublish(linearIntegration.webhookProcessorFn); + // #1004: the reconciler kicks the processor's grant health probe twice a day, so a + // grant that dies while nobody uses Linear is still detected and announced here. + concurrencyReconciler.triggerLinearGrantProbe(linearIntegration.webhookProcessorFn); linearIntegration.webhookProcessorFn.addEnvironment( 'OPERATIONAL_ALERT_TOPIC_ARN', operationalAlerts.topic.topicArn, diff --git a/cdk/test/constructs/blueprint.test.ts b/cdk/test/constructs/blueprint.test.ts index 6a7e607ee..cb032bff7 100644 --- a/cdk/test/constructs/blueprint.test.ts +++ b/cdk/test/constructs/blueprint.test.ts @@ -563,6 +563,37 @@ describe('Blueprint construct', () => { ); }); + // --- security.approvalTimeoutSeconds (#1066) ----------------------------- + + test('persists approval_timeout_s on create and update when approvalTimeoutSeconds is set', () => { + const { template } = createStack({ security: { approvalTimeoutSeconds: 2700 } }); + expect(getCreateJoinParts(template).join('')).toContain('"approval_timeout_s":{"N":"2700"}'); + const update = getUpdateJoinParts(template).join(''); + expect(update).toContain('#approval_timeout_s'); + expect(update).toContain('"N":"2700"'); + }); + + test('omits approval_timeout_s when approvalTimeoutSeconds is unset', () => { + const { template } = createStack({ security: { approvalGateCap: 10 } }); + expect(getCreateJoinParts(template).join('')).not.toContain('approval_timeout_s'); + }); + + test('a redeploy without approvalTimeoutSeconds removes the window an earlier deploy set', () => { + const { template } = createStack({ security: { approvalGateCap: 10 } }); + const removeClause = /REMOVE ([^"\\]*)/.exec(getUpdateJoinParts(template).join(''))?.[1] ?? ''; + expect(removeClause).toContain('#approval_timeout_s'); + }); + + test.each([10, 3601, 90.5])('rejects approvalTimeoutSeconds %p at synth', (seconds) => { + const app = new App(); + const stack = new Stack(app, 'TestStack'); + const repoTable = new dynamodb.Table(stack, 'RepoTable', { + partitionKey: { name: 'repo', type: dynamodb.AttributeType.STRING }, + }); + new Blueprint(stack, 'Blueprint', { repo: 'org/my-repo', repoTable, security: { approvalTimeoutSeconds: seconds } }); + expect(() => Template.fromStack(stack)).toThrow(/Invalid security.approvalTimeoutSeconds/); + }); + // --- Chunk 7b: security.approvalGateCap --------------------------------- test('exposes approvalGateCap as public property when configured', () => { diff --git a/cdk/test/constructs/concurrency-reconciler.test.ts b/cdk/test/constructs/concurrency-reconciler.test.ts index 34e1e88e4..e3d9f82ef 100644 --- a/cdk/test/constructs/concurrency-reconciler.test.ts +++ b/cdk/test/constructs/concurrency-reconciler.test.ts @@ -20,6 +20,7 @@ import { App, Stack } from 'aws-cdk-lib'; import { Template, Match } from 'aws-cdk-lib/assertions'; import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; +import * as lambda from 'aws-cdk-lib/aws-lambda'; import { ConcurrencyReconciler } from '../../src/constructs/concurrency-reconciler'; function createStack(): Template { @@ -70,3 +71,41 @@ describe('ConcurrencyReconciler construct', () => { }); }); }); + +describe('ConcurrencyReconciler Linear grant probe trigger (#1004)', () => { + function build(withProbe: boolean): Template { + const stack = new Stack(new App(), 'ProbeStack'); + const table = (id: string, pk: string) => new dynamodb.Table(stack, id, { + partitionKey: { name: pk, type: dynamodb.AttributeType.STRING }, + }); + const reconciler = new ConcurrencyReconciler(stack, 'ConcurrencyReconciler', { + taskTable: table('Tasks', 'task_id'), + userConcurrencyTable: table('Users', 'user_id'), + }); + const processor = new lambda.Function(stack, 'Processor', { + runtime: lambda.Runtime.NODEJS_22_X, handler: 'index.handler', code: lambda.Code.fromInline('exports.handler=async()=>{}'), + }); + if (withProbe) reconciler.triggerLinearGrantProbe(processor); + return Template.fromStack(stack); + } + + test('grants invoke and passes the target without adding any resource', () => { + const without = build(false); + const template = build(true); + const types = (t: Template) => Object.entries(t.toJSON().Resources as Record) + .map(([id, r]) => `${r.Type} ${id}`).sort(); + + expect(types(template)).toEqual(types(without)); + template.hasResourceProperties('AWS::Lambda::Function', { + Environment: { + Variables: Match.objectLike({ + RECONCILER_TICK_MINUTES: '15', + LINEAR_GRANT_PROBE_FUNCTION_ARN: { 'Fn::GetAtt': [Match.stringLikeRegexp('Processor'), 'Arn'] }, + }), + }, + }); + template.hasResourceProperties('AWS::IAM::Policy', { + PolicyDocument: { Statement: Match.arrayWith([Match.objectLike({ Action: 'lambda:InvokeFunction' })]) }, + }); + }); +}); diff --git a/cdk/test/constructs/fanout-consumer.test.ts b/cdk/test/constructs/fanout-consumer.test.ts index c4343ce03..dece9caf8 100644 --- a/cdk/test/constructs/fanout-consumer.test.ts +++ b/cdk/test/constructs/fanout-consumer.test.ts @@ -287,4 +287,46 @@ describe('FanOutConsumer', () => { expect(vars.TASK_TABLE_NAME).toBeUndefined(); } }); + + test('approval notices (#1001): wires TASK_APPROVALS_TABLE_NAME with only GetItem + UpdateItem', () => { + const app = new App(); + const stack = new Stack(app, 'TestStack'); + const approvals = new dynamodb.Table(stack, 'ApprovalsTable', { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + sortKey: { name: 'request_id', type: dynamodb.AttributeType.STRING }, + }); + new FanOutConsumer(stack, 'FanOut', { + taskEventsTable: makeTaskEventsTable(stack), + taskApprovalsTable: approvals, + }); + const template = Template.fromStack(stack); + const approvalsId = stack.getLogicalId(approvals.node.defaultChild as dynamodb.CfnTable); + + template.hasResourceProperties('AWS::Lambda::Function', { + Environment: { Variables: Match.objectLike({ TASK_APPROVALS_TABLE_NAME: { Ref: approvalsId } }) }, + }); + const approvalActions: string[] = []; + for (const policy of Object.values(template.findResources('AWS::IAM::Policy'))) { + const stmts = (policy as { Properties: { PolicyDocument: { Statement: Array<{ Action: unknown; Resource: unknown }> } } }) + .Properties.PolicyDocument.Statement; + for (const s of stmts) { + if (JSON.stringify(s.Resource).includes(approvalsId)) { + approvalActions.push(...(Array.isArray(s.Action) ? s.Action : [s.Action]) as string[]); + } + } + } + expect(approvalActions.sort()).toEqual(['dynamodb:GetItem', 'dynamodb:UpdateItem']); + }); + + test('approval notices (#1001): no approvals env or grant when the table is omitted', () => { + const app = new App(); + const stack = new Stack(app, 'TestStack'); + new FanOutConsumer(stack, 'FanOut', { taskEventsTable: makeTaskEventsTable(stack) }); + const template = Template.fromStack(stack); + for (const fn of Object.values(template.findResources('AWS::Lambda::Function'))) { + const vars = ((fn as { Properties?: { Environment?: { Variables?: Record } } }) + .Properties?.Environment?.Variables) ?? {}; + expect(vars.TASK_APPROVALS_TABLE_NAME).toBeUndefined(); + } + }); }); diff --git a/cdk/test/constructs/linear-integration.test.ts b/cdk/test/constructs/linear-integration.test.ts index 5df92ed6c..eb9ee8e14 100644 --- a/cdk/test/constructs/linear-integration.test.ts +++ b/cdk/test/constructs/linear-integration.test.ts @@ -548,3 +548,68 @@ describe('LinearIntegration construct โ€” agent sessions (ADR-018 Phase 2)', () expect(nudgeStatements(t)).toEqual([]); }); }); + +describe('LinearIntegration construct โ€” approval replies (#1001)', () => { + function buildWith(opts: { withApprovals: boolean }): { t: Template; approvalsId?: string } { + const app = new App(); + const stack = new Stack(app, 'TestStack'); + const api = new apigw.RestApi(stack, 'TestApi'); + const userPool = new cognito.UserPool(stack, 'TestUserPool'); + const taskTable = new dynamodb.Table(stack, 'TaskTable', { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + }); + const taskEventsTable = new dynamodb.Table(stack, 'TaskEventsTable', { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + sortKey: { name: 'event_id', type: dynamodb.AttributeType.STRING }, + }); + const taskApprovalsTable = opts.withApprovals + ? new dynamodb.Table(stack, 'ApprovalsTable', { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + sortKey: { name: 'request_id', type: dynamodb.AttributeType.STRING }, + }) + : undefined; + new LinearIntegration(stack, 'LinearIntegration', { + api, + userPool, + taskTable, + taskEventsTable, + ...(taskApprovalsTable && { taskApprovalsTable }), + }); + return { + t: Template.fromStack(stack), + approvalsId: taskApprovalsTable && stack.getLogicalId(taskApprovalsTable.node.defaultChild as dynamodb.CfnTable), + }; + } + + test('wires TASK_APPROVALS_TABLE_NAME on the processor and grants it the approvals table', () => { + const { t, approvalsId } = buildWith({ withApprovals: true }); + t.hasResourceProperties('AWS::Lambda::Function', { + Environment: { + Variables: Match.objectLike({ + TASK_APPROVALS_TABLE_NAME: { Ref: approvalsId }, + LINEAR_WORKSPACE_REGISTRY_TABLE_NAME: Match.anyValue(), + }), + }, + }); + const grants = Object.values(t.findResources('AWS::IAM::Policy')).filter((p) => { + const stmts = (p as { Properties: { PolicyDocument: { Statement: Array<{ Action: unknown; Resource: unknown }> } } }) + .Properties.PolicyDocument.Statement; + return stmts.some((s) => { + const actions = Array.isArray(s.Action) ? s.Action : [s.Action]; + return actions.includes('dynamodb:UpdateItem') && actions.includes('dynamodb:GetItem') + && JSON.stringify(s.Resource).includes(approvalsId!); + }); + }); + expect(grants).toHaveLength(1); + }); + + test('does NOT set TASK_APPROVALS_TABLE_NAME when the table is omitted (back-compat)', () => { + const { t } = buildWith({ withApprovals: false }); + const fns = t.findResources('AWS::Lambda::Function', { + Properties: { + Environment: { Variables: Match.objectLike({ TASK_APPROVALS_TABLE_NAME: Match.anyValue() }) }, + }, + }); + expect(Object.keys(fns)).toHaveLength(0); + }); +}); diff --git a/cdk/test/handlers/approve-task.test.ts b/cdk/test/handlers/approve-task.test.ts index f05148b9b..67e5f5d73 100644 --- a/cdk/test/handlers/approve-task.test.ts +++ b/cdk/test/handlers/approve-task.test.ts @@ -61,7 +61,7 @@ process.env.TASK_APPROVALS_TABLE_NAME = 'Approvals'; process.env.TASK_EVENTS_TABLE_NAME = 'Events'; process.env.APPROVE_RATE_LIMIT_PER_MINUTE = '30'; -import { handler } from '../../src/handlers/approve-task'; +import { handler, recordApprovalForUser } from '../../src/handlers/approve-task'; function makeEvent(overrides: Partial = {}): APIGatewayProxyEvent { return { @@ -304,3 +304,41 @@ describe('trusted channel decision source', () => { expect(update.UpdateExpression).not.toContain('decision_source'); }); }); + +describe('approve-task โ€” decision source (#1001)', () => { + test('API callers record no decision_source (behaviour unchanged)', async () => { + mockSend.mockResolvedValue({}); + await handler(makeEvent({ body: JSON.stringify({ request_id: '01KREQ1', decision: 'approve' }) })); + const tx = mockSend.mock.calls.find((c) => c[0]._type === 'TransactWrite')?.[0].input; + const update = tx.TransactItems[0].Update; + expect(update.UpdateExpression).not.toContain('decision_source'); + expect(update.ExpressionAttributeValues[':source']).toBeUndefined(); + const audit = mockSend.mock.calls.find((c) => c[0]._type === 'Put')?.[0].input; + expect(audit.Item.metadata.decision_source).toBeUndefined(); + }); + + test('recordApprovalForUser records the given decision_source on the row and the audit event', async () => { + mockSend.mockResolvedValue({}); + const res = await recordApprovalForUser({ + userId: 'user-alice', + taskId: 'task-1', + body: JSON.stringify({ request_id: '01KREQ1', decision: 'approve' }), + decisionSource: 'linear', + }); + expect(res.statusCode).toBe(202); + expect(JSON.parse(res.body).data.status).toBe('APPROVED'); + const tx = mockSend.mock.calls.find((c) => c[0]._type === 'TransactWrite')?.[0].input; + const update = tx.TransactItems[0].Update; + expect(update.UpdateExpression).toContain('decision_source = :source'); + expect(update.ExpressionAttributeValues[':source']).toBe('linear'); + const audit = mockSend.mock.calls.find((c) => c[0]._type === 'Put')?.[0].input; + expect(audit.Item.metadata.decision_source).toBe('linear'); + expect(audit.Item.metadata.caller_user_id).toBe('user-alice'); + }); + + test('recordApprovalForUser rejects a missing user with 401', async () => { + const res = await recordApprovalForUser({ userId: null, taskId: 'task-1', body: '{}', decisionSource: 'linear' }); + expect(res.statusCode).toBe(401); + expect(mockSend).not.toHaveBeenCalled(); + }); +}); diff --git a/cdk/test/handlers/deny-task.test.ts b/cdk/test/handlers/deny-task.test.ts index dcaeaf15f..2a9cc22df 100644 --- a/cdk/test/handlers/deny-task.test.ts +++ b/cdk/test/handlers/deny-task.test.ts @@ -53,7 +53,7 @@ process.env.TASK_TABLE_NAME = 'Tasks'; process.env.TASK_APPROVALS_TABLE_NAME = 'Approvals'; process.env.TASK_EVENTS_TABLE_NAME = 'Events'; -import { handler } from '../../src/handlers/deny-task'; +import { handler, recordDenialForUser } from '../../src/handlers/deny-task'; // Secret fixtures assembled at runtime so the source file itself // never holds a contiguous secret literal (Code Defender pre-commit @@ -339,3 +339,41 @@ describe('trusted channel decision source', () => { expect(update.UpdateExpression).not.toContain('decision_source'); }); }); + +describe('deny-task โ€” decision source (#1001)', () => { + test('API callers record no decision_source (behaviour unchanged)', async () => { + mockSend.mockResolvedValue({}); + await handler(makeEvent({ body: JSON.stringify({ request_id: '01KREQ1', decision: 'deny' }) })); + const tx = mockSend.mock.calls.find((c) => c[0]._type === 'TransactWrite')?.[0].input; + const update = tx.TransactItems[0].Update; + expect(update.UpdateExpression).not.toContain('decision_source'); + expect(update.ExpressionAttributeValues[':source']).toBeUndefined(); + const audit = mockSend.mock.calls.find((c) => c[0]._type === 'Put')?.[0].input; + expect(audit.Item.metadata.decision_source).toBeUndefined(); + }); + + test('recordDenialForUser records the given decision_source on the row and the audit event', async () => { + mockSend.mockResolvedValue({}); + const res = await recordDenialForUser({ + userId: 'user-alice', + taskId: 'task-1', + body: JSON.stringify({ request_id: '01KREQ1', decision: 'deny' }), + decisionSource: 'linear', + }); + expect(res.statusCode).toBe(202); + expect(JSON.parse(res.body).data.status).toBe('DENIED'); + const tx = mockSend.mock.calls.find((c) => c[0]._type === 'TransactWrite')?.[0].input; + const update = tx.TransactItems[0].Update; + expect(update.UpdateExpression).toContain('decision_source = :source'); + expect(update.ExpressionAttributeValues[':source']).toBe('linear'); + const audit = mockSend.mock.calls.find((c) => c[0]._type === 'Put')?.[0].input; + expect(audit.Item.metadata.decision_source).toBe('linear'); + expect(audit.Item.metadata.caller_user_id).toBe('user-alice'); + }); + + test('recordDenialForUser rejects a missing user with 401', async () => { + const res = await recordDenialForUser({ userId: null, taskId: 'task-1', body: '{}', decisionSource: 'linear' }); + expect(res.statusCode).toBe(401); + expect(mockSend).not.toHaveBeenCalled(); + }); +}); diff --git a/cdk/test/handlers/fanout-linear-agent-session.test.ts b/cdk/test/handlers/fanout-linear-agent-session.test.ts index 3f25f5a0b..d054fa1f9 100644 --- a/cdk/test/handlers/fanout-linear-agent-session.test.ts +++ b/cdk/test/handlers/fanout-linear-agent-session.test.ts @@ -99,8 +99,10 @@ function mockTask(task: Record, updateError?: Error): void { }); } +/** Task-record writes, without the session checklist's stage (covered in fanout-linear-session-progress.test.ts). */ function updates(): Array<{ UpdateExpression: string; ConditionExpression?: string }> { - return mockDdbSend.mock.calls.filter((c) => c[0]._type === 'Update').map((c) => c[0].input); + return mockDdbSend.mock.calls.filter((c) => c[0]._type === 'Update').map((c) => c[0].input) + .filter((u) => !String(u.UpdateExpression).includes('linear_checklist_stage')); } beforeEach(() => { diff --git a/cdk/test/handlers/fanout-linear-session-progress.test.ts b/cdk/test/handlers/fanout-linear-session-progress.test.ts new file mode 100644 index 000000000..e54cb64e4 --- /dev/null +++ b/cdk/test/handlers/fanout-linear-session-progress.test.ts @@ -0,0 +1,330 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +// Session progress streamed by the fan-out Linear dispatcher (#1066). A separate file +// because the flag is read when the module builds CHANNEL_DEFAULTS, so it must be set +// before import. + +import type { DynamoDBRecord } from 'aws-lambda'; + +const mockDdbSend = jest.fn(); +jest.mock('@aws-sdk/client-dynamodb', () => ({ DynamoDBClient: jest.fn(() => ({})) })); +jest.mock('@aws-sdk/lib-dynamodb', () => ({ + DynamoDBDocumentClient: { from: jest.fn(() => ({ send: mockDdbSend })) }, + GetCommand: jest.fn((input: unknown) => ({ _type: 'Get', input })), + UpdateCommand: jest.fn((input: unknown) => ({ _type: 'Update', input })), + QueryCommand: jest.fn((input: unknown) => ({ _type: 'Query', input })), +})); + +const mockPostIssueComment = jest.fn().mockResolvedValue({ ok: true }); +const mockResolveToken = jest.fn(); +const mockTransitionIssueState = jest.fn().mockResolvedValue({ ok: true }); +jest.mock('../../src/handlers/shared/linear-feedback', () => ({ + transitionIssueState: (...args: unknown[]) => mockTransitionIssueState(...args), + postIssueComment: (...args: unknown[]) => mockPostIssueComment(...args), + replyToComment: jest.fn(), + upsertThreadedReply: jest.fn(), + swapCommentReaction: jest.fn(), + resolveToken: (...args: unknown[]) => mockResolveToken(...args), +})); + +const mockEmitAgentActivity = jest.fn(); +const mockSetPlan = jest.fn(); +jest.mock('../../src/handlers/shared/linear-agent-session', () => ({ + setAgentSessionPlan: (...args: unknown[]) => mockSetPlan(...args), + emitAgentActivity: (...args: unknown[]) => mockEmitAgentActivity(...args), + addAgentSessionExternalUrl: jest.fn().mockResolvedValue({ ok: true }), +})); + +const mockLoadApproval = jest.fn(); +const mockMarkApproval = jest.fn().mockResolvedValue(undefined); +jest.mock('../../src/handlers/shared/approval-notifications', () => ({ + ...jest.requireActual('../../src/handlers/shared/approval-notifications'), + loadApprovalNotification: (...args: unknown[]) => mockLoadApproval(...args), + markApprovalNotificationDelivered: (...args: unknown[]) => mockMarkApproval(...args), +})); + +process.env.LINEAR_AGENT_SESSIONS_ENABLED = 'true'; +process.env.TASK_APPROVALS_TABLE_NAME = 'Approvals'; +process.env.TASK_TABLE_NAME = 'Tasks'; +process.env.LINEAR_WORKSPACE_REGISTRY_TABLE_NAME = 'LinearWorkspaceRegistry'; + +import { + CHANNEL_DEFAULTS, + resetLinearHeartbeatMemoForTests, + routeEvent, + supersededToolCallIds, + type FanOutEvent, + type TaskNotificationsConfig, +} from '../../src/handlers/fanout-task-events'; +import { progressActivityId } from '../../src/handlers/shared/linear-session-progress'; + +const LINEAR_ONLY: TaskNotificationsConfig = { + slack: { enabled: false }, github: { enabled: false }, jira: { enabled: false }, email: { enabled: false }, +} as TaskNotificationsConfig; + +const SESSION_TASK = { + task_id: 't-sess', + user_id: 'u-1', + status: 'RUNNING', + repo: 'acme/web', + channel_source: 'linear', + channel_metadata: { linear_issue_id: 'issue-1', linear_workspace_id: 'org-1', linear_agent_session_id: 'session-1' }, +}; +const COMMENT_TASK = { ...SESSION_TASK, channel_metadata: { linear_issue_id: 'issue-1', linear_workspace_id: 'org-1' } }; + +function ev(eventType: string, metadata?: Record, eventId = `e-${eventType}`): FanOutEvent { + return { task_id: 't-sess', event_id: eventId, event_type: eventType, timestamp: '2026-11-20T00:00:00Z', metadata }; +} + +/** Get โ†’ the task; Update (the progress slot) โ†’ succeeds unless `updateError` is set. */ +function mockTask(task: Record, updateError?: Error): void { + mockDdbSend.mockReset().mockImplementation(async (cmd: { _type: string }) => { + if (cmd._type === 'Get') return { Item: task }; + if (cmd._type === 'Update' && updateError) throw updateError; + return {}; + }); +} +const updates = () => mockDdbSend.mock.calls.filter((c) => c[0]._type === 'Update').map((c) => c[0].input); + +beforeEach(() => { + mockPostIssueComment.mockClear(); + mockResolveToken.mockReset().mockResolvedValue('lin_tok'); + mockEmitAgentActivity.mockReset().mockResolvedValue({ ok: true }); + mockSetPlan.mockReset().mockResolvedValue({ ok: true }); + mockTransitionIssueState.mockClear(); + mockLoadApproval.mockReset(); + mockMarkApproval.mockClear(); + resetLinearHeartbeatMemoForTests(); +}); + +test('the flag subscribes the Linear channel to the progress events', () => { + for (const type of ['agent_turn', 'agent_tool_call', 'admission_queued', 'hydration_complete', 'repo_setup_complete', 'nudge_acknowledged', 'attachments_downloaded', 'agent_execution_complete']) { + expect(CHANNEL_DEFAULTS.linear.has(type)).toBe(true); + } +}); + +test('a tool call is an ephemeral action with a deterministic id, and takes no persistent slot', async () => { + mockTask(SESSION_TASK); + const outcome = await routeEvent(ev('agent_tool_call', { tool_name: 'Read', tool_input_preview: "{'file_path': '/workspace/t-sess/src/app.ts'}" }), LINEAR_ONLY); + expect(outcome.infraRejections).toEqual([]); + expect(mockEmitAgentActivity).toHaveBeenCalledWith('lin_tok', 'session-1', + { type: 'action', action: 'Reading', parameter: '`src/app.ts`' }, + { ephemeral: true, id: progressActivityId('e-agent_tool_call') }); + expect(updates()).toEqual([]); +}); + +test("the agent's message is a persistent thought that claims one of the task's progress slots", async () => { + mockTask(SESSION_TASK); + await routeEvent(ev('agent_turn', { text_preview: 'Found it: the parser drops the last token.' }), LINEAR_ONLY); + expect(updates()).toEqual([expect.objectContaining({ UpdateExpression: 'ADD linear_session_progress_count :one' })]); + expect(mockEmitAgentActivity).toHaveBeenCalledWith('lin_tok', 'session-1', + { type: 'thought', body: 'Found it: the parser drops the last token.' }, expect.objectContaining({ ephemeral: false })); +}); + +test('past the cap, persistent progress is dropped; the stream never throws', async () => { + mockTask(SESSION_TASK, Object.assign(new Error('cap'), { name: 'ConditionalCheckFailedException' })); + const capped = await routeEvent(ev('hydration_complete'), LINEAR_ONLY); + expect(capped.infraRejections).toEqual([]); + expect(mockEmitAgentActivity).not.toHaveBeenCalled(); + + mockTask(SESSION_TASK); + mockEmitAgentActivity.mockResolvedValueOnce({ ok: false, retryable: true }); + const failed = await routeEvent(ev('agent_tool_call', { tool_name: 'Bash', tool_input_preview: "{'command': 'ls'}" }), LINEAR_ONLY); + expect(failed.infraRejections).toEqual([]); // best effort: no batch retry +}); + +test('nothing is posted once the session has closed, so a late event cannot reopen it', async () => { + for (const task of [{ ...SESSION_TASK, linear_final_comment_event_id: 'e-done' }, { ...SESSION_TASK, status: 'COMPLETED' }]) { + mockTask(task); + mockEmitAgentActivity.mockClear(); + await routeEvent(ev('agent_tool_call', { tool_name: 'Bash', tool_input_preview: "{'command': 'ls'}" }), LINEAR_ONLY); + expect(mockEmitAgentActivity).not.toHaveBeenCalled(); + } +}); + +test('a comment-path Linear task ignores progress milestones (no PR-opened comment from nudge_acknowledged)', async () => { + mockTask({ ...COMMENT_TASK, pr_url: 'https://github.com/acme/web/pull/7' }); + await routeEvent(ev('agent_milestone', { milestone: 'nudge_acknowledged' }), LINEAR_ONLY); + expect(mockPostIssueComment).not.toHaveBeenCalled(); + expect(mockEmitAgentActivity).not.toHaveBeenCalled(); +}); + +test('a task known not to be a session task skips the task read for later progress events', async () => { + mockTask(COMMENT_TASK); + await routeEvent(ev('agent_tool_call', { tool_name: 'Bash' }, 'e-1'), LINEAR_ONLY); + const readsAfterFirst = mockDdbSend.mock.calls.filter((c) => c[0]._type === 'Get').length; + await routeEvent(ev('agent_tool_call', { tool_name: 'Bash' }, 'e-2'), LINEAR_ONLY); + expect(mockDdbSend.mock.calls.filter((c) => c[0]._type === 'Get').length).toBe(readsAfterFirst); +}); + +function toolCallRecord(taskId: string, eventId: string): DynamoDBRecord { + return { + eventID: eventId, + eventName: 'INSERT', + eventSource: 'aws:dynamodb', + dynamodb: { + SequenceNumber: `seq-${eventId}`, + NewImage: { + task_id: { S: taskId }, + event_id: { S: eventId }, + event_type: { S: 'agent_tool_call' }, + timestamp: { S: '2026-11-20T00:00:00Z' }, + metadata: { M: { tool_name: { S: 'Bash' } } }, + }, + }, + } as unknown as DynamoDBRecord; +} + +test('only the newest tool call of each task in a batch is kept', () => { + const records = [toolCallRecord('a', 'a1'), toolCallRecord('b', 'b1'), toolCallRecord('a', 'a2'), toolCallRecord('a', 'a3')]; + expect([...supersededToolCallIds(records)].sort()).toEqual(['a1', 'a2']); +}); + +// --- The session checklist, the closing line and In Review --- + +const planStatuses = () => (mockSetPlan.mock.calls.at(-1)?.[2] as Array<{ status: string }>).map((s) => s.status); +const stageWrites = () => updates().filter((u) => String(u.UpdateExpression).includes('linear_checklist_stage')); + +test('a step that moves the checklist forward records the stage, then replaces the session plan', async () => { + mockTask(SESSION_TASK); + await routeEvent(ev('agent_milestone', { milestone: 'repo_setup_complete' }), LINEAR_ONLY); + expect(stageWrites()).toEqual([expect.objectContaining({ ExpressionAttributeValues: { ':s': 2 } })]); + expect(mockSetPlan).toHaveBeenCalledWith('lin_tok', 'session-1', expect.any(Array)); + expect(planStatuses()).toEqual(['completed', 'completed', 'inProgress', 'pending', 'pending']); +}); + +test('the checklist never moves back: a stale step loses the conditional write and is not shown', async () => { + mockTask({ ...SESSION_TASK, linear_checklist_stage: 3 }, Object.assign(new Error('stale'), { name: 'ConditionalCheckFailedException' })); + await routeEvent(ev('hydration_complete'), LINEAR_ONLY); + expect(mockSetPlan).not.toHaveBeenCalled(); +}); + +test('the agent finishing moves the checklist to the pull request step, with no activity of its own', async () => { + mockTask(SESSION_TASK); + await routeEvent(ev('agent_milestone', { milestone: 'agent_execution_complete' }), LINEAR_ONLY); + expect(planStatuses()).toEqual(['completed', 'completed', 'completed', 'inProgress', 'pending']); + expect(mockEmitAgentActivity).not.toHaveBeenCalled(); +}); + +test('a workflow without coding stages gets no checklist', async () => { + mockTask({ ...SESSION_TASK, resolved_workflow: { id: 'review/pr-review-v1', version: '1' } }); + await routeEvent(ev('hydration_complete'), LINEAR_ONLY); + expect(mockSetPlan).not.toHaveBeenCalled(); +}); + +const PR_URL = 'https://github.com/acme/web/pull/7'; + +test('a task that ends with a pull request completes the checklist, says what is next, and moves the issue to In Review', async () => { + mockTask({ ...SESSION_TASK, status: 'COMPLETED', pr_url: PR_URL, linear_checklist_stage: 4 }); + await routeEvent(ev('task_completed'), LINEAR_ONLY); + expect(planStatuses()).toEqual(Array(5).fill('completed')); + const final = mockEmitAgentActivity.mock.calls.at(-1)?.[2] as { type: string; body: string }; + expect(final.type).toBe('response'); + expect(final.body).toMatch(/_Your turn: review the pull request\. Reply here if it needs changes\._$/); + expect(mockTransitionIssueState).toHaveBeenCalledWith(expect.anything(), 'issue-1', 'started', ['In Review'], false, true); +}); + +test('a failed task cancels what was left, offers a retry, and leaves the issue where it is', async () => { + mockTask({ ...SESSION_TASK, status: 'FAILED', linear_checklist_stage: 2, error_message: 'boom' }); + await routeEvent(ev('task_failed'), LINEAR_ONLY); + expect(planStatuses()).toEqual(['completed', 'completed', 'canceled', 'canceled', 'canceled']); + expect((mockEmitAgentActivity.mock.calls.at(-1)?.[2] as { body: string }).body).toMatch(/_Reply here to try again\._$/); + expect(mockTransitionIssueState).not.toHaveBeenCalled(); +}); + +test('a run that stopped to ask a question waits on the reader, and the checklist says so', async () => { + mockTask({ ...SESSION_TASK, status: 'COMPLETED', code_changed: false, answer_text: 'Which page?', linear_checklist_stage: 2 }); + await routeEvent(ev('task_completed'), LINEAR_ONLY); + const final = mockEmitAgentActivity.mock.calls.at(-1)?.[2] as { type: string; body: string }; + expect(final.type).toBe('elicitation'); + expect(final.body).toMatch(/\*\*Waiting on you\.\*\* Nothing continues until you reply here\.$/); + const plan = mockSetPlan.mock.calls.at(-1)?.[2] as Array<{ content: string; status: string }>; + expect(plan[2]).toEqual({ content: 'Write the code โ€” waiting on your answer', status: 'inProgress' }); + expect(mockTransitionIssueState).not.toHaveBeenCalled(); +}); + +test('a failed checklist write never blocks the final response', async () => { + mockTask({ ...SESSION_TASK, status: 'COMPLETED', pr_url: PR_URL }); + mockSetPlan.mockRejectedValueOnce(new Error('linear down')); + const outcome = await routeEvent(ev('task_completed'), LINEAR_ONLY); + expect(outcome.infraRejections).toEqual([]); + expect(mockEmitAgentActivity).toHaveBeenCalledWith('lin_tok', 'session-1', expect.objectContaining({ type: 'response' })); +}); + +// --- Approval requests in the session --- + +const PENDING_NOTICE = { + title: 'Approval needed', + text: 'Approval needed\nThe agent wants to run a shell command.', + taskId: 't-sess', + requestId: 'req-1', + userId: 'u-1', + marker: 'notified_linear_session_approval_requested', + deadline: '2026-11-20T00:30:00Z', +}; + +test('a pending request goes into the session as Approve / Deny buttons, once', async () => { + mockTask({ ...SESSION_TASK, status: 'AWAITING_APPROVAL', awaiting_approval_request_id: 'req-1' }); + mockLoadApproval.mockResolvedValue(PENDING_NOTICE); + await routeEvent(ev('agent_milestone', { milestone: 'approval_requested', request_id: 'req-1' }), LINEAR_ONLY); + expect(mockLoadApproval).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ task_id: 't-sess' }), + 'approval_requested', expect.objectContaining({ request_id: 'req-1' }), 'linear_session'); + const [, session, content, options] = mockEmitAgentActivity.mock.calls[0]; + expect(session).toBe('session-1'); + expect(content.type).toBe('elicitation'); + expect(content.body).toContain('**Waiting on you.**'); + expect(options).toEqual(expect.objectContaining({ signal: 'select', id: expect.stringMatching(/^[0-9a-f-]{36}$/) })); + expect(mockMarkApproval).toHaveBeenCalledWith(expect.anything(), PENDING_NOTICE); + expect(mockPostIssueComment).not.toHaveBeenCalled(); +}); + +test('a request that is no longer open is not shown', async () => { + mockTask(SESSION_TASK); + mockLoadApproval.mockResolvedValue(null); + await routeEvent(ev('agent_milestone', { milestone: 'approval_requested', request_id: 'req-1' }), LINEAR_ONLY); + expect(mockEmitAgentActivity).not.toHaveBeenCalled(); +}); + +test('a decision made in the session is not echoed; one made elsewhere is a note', async () => { + mockTask(SESSION_TASK); + mockLoadApproval.mockResolvedValue({ ...PENDING_NOTICE, title: 'Approval recorded', marker: 'notified_linear_session_approval_decision_recorded' }); + await routeEvent(ev('agent_milestone', { + milestone: 'approval_decision_recorded', request_id: 'req-1', decision_source: '["linear_session","org-1","p-1"]', + }), LINEAR_ONLY); + expect(mockLoadApproval).not.toHaveBeenCalled(); + await routeEvent(ev('agent_milestone', { milestone: 'approval_decision_recorded', request_id: 'req-1' }, 'e-cli'), LINEAR_ONLY); + expect(mockEmitAgentActivity).toHaveBeenCalledWith('lin_tok', 'session-1', expect.objectContaining({ type: 'thought' }), expect.anything()); +}); + +test('a transient failure retries the batch, and nothing is marked delivered', async () => { + mockTask({ ...SESSION_TASK, status: 'AWAITING_APPROVAL', awaiting_approval_request_id: 'req-1' }); + mockLoadApproval.mockResolvedValue(PENDING_NOTICE); + mockEmitAgentActivity.mockResolvedValueOnce({ ok: false, retryable: true }); + const outcome = await routeEvent(ev('agent_milestone', { milestone: 'approval_requested', request_id: 'req-1' }), LINEAR_ONLY); + expect(outcome.infraRejections).toEqual(['linear']); + expect(mockMarkApproval).not.toHaveBeenCalled(); +}); + +test('after the final response nothing reopens the session', async () => { + mockTask({ ...SESSION_TASK, linear_final_comment_event_id: 'e-done' }); + mockLoadApproval.mockResolvedValue(PENDING_NOTICE); + await routeEvent(ev('agent_milestone', { milestone: 'approval_timed_out', request_id: 'req-1' }), LINEAR_ONLY); + expect(mockEmitAgentActivity).not.toHaveBeenCalled(); +}); diff --git a/cdk/test/handlers/fanout-task-events.test.ts b/cdk/test/handlers/fanout-task-events.test.ts index 6c6c7033a..fe522d76b 100644 --- a/cdk/test/handlers/fanout-task-events.test.ts +++ b/cdk/test/handlers/fanout-task-events.test.ts @@ -112,7 +112,9 @@ const mockSwapCommentReaction: jest.Mock = jest.fn().mockResolvedValue(true); // place) via upsertThreadedReply(ctx, issueId, parentCommentId, body, existingId?) // rather than posting a fresh replyToComment. const mockUpsertThreadedReply: jest.Mock = jest.fn().mockResolvedValue('reply-id'); +const mockPostIdentifiedComment: jest.Mock = jest.fn().mockResolvedValue({ ok: true }); jest.mock('../../src/handlers/shared/linear-feedback', () => ({ + postIdentifiedComment: (...args: unknown[]) => mockPostIdentifiedComment(...args), postIssueComment: ( ctx: { linearWorkspaceId: string; registryTableName: string }, issueId: string, @@ -191,6 +193,7 @@ jest.mock('../../src/handlers/shared/jira-feedback', () => ({ })); process.env.TASK_TABLE_NAME = 'Tasks'; +process.env.TASK_APPROVALS_TABLE_NAME = 'Approvals'; process.env.GITHUB_TOKEN_SECRET_ARN = 'arn:aws:secretsmanager:us-east-1:0:secret:platform'; process.env.LINEAR_WORKSPACE_REGISTRY_TABLE_NAME = 'LinearWorkspaceRegistry'; process.env.JIRA_WORKSPACE_REGISTRY_TABLE_NAME = 'JiraWorkspaceRegistry'; @@ -420,6 +423,10 @@ describe('fanout-task-events: per-channel filter contract (design ยง6.2)', () => // that times out still settles (matches Jira/Slack, which already had it). const f = CHANNEL_DEFAULTS.linear; expect([...f].sort()).toEqual([ + 'approval_decision_recorded', + 'approval_requested', + 'approval_stranded', + 'approval_timed_out', 'pr_created', 'task_cancelled', 'task_completed', @@ -1639,6 +1646,97 @@ describe('fanout-task-events: Linear dispatcher', () => { }); }; + describe('approval notices (#1001)', () => { + const pendingRow = { + user_id: 'u-1', + status: 'PENDING', + tool_name: 'Bash', + severity: 'medium', + reason: 'Review this', + tool_input_preview: '{"command":"git push"}', + timeout_s: 1800, + created_at: '2026-09-16T12:00:00Z', + }; + const awaiting = { ...TASK_RECORD_LINEAR, status: 'AWAITING_APPROVAL', awaiting_approval_request_id: 'g1' }; + const answer = (approvalRow: unknown, task: unknown) => mockDdbSend.mockImplementation(async (command: any) => { + if (command._type !== 'Get') return {}; + return { Item: command.input.TableName === 'Approvals' ? approvalRow : task }; + }); + + test.each([false, true])('posts the request as a reply-able notice without settling the task (post failure=%s)', async fails => { + answer(pendingRow, awaiting); + if (fails) mockPostIdentifiedComment.mockResolvedValueOnce({ ok: false, retryable: true }); + const outcome = await routeEvent({ + task_id: 't-lin', + event_id: 'approval-event', + event_type: 'agent_milestone', + timestamp: '2026-09-16T12:00:00Z', + metadata: { milestone: 'approval_requested', request_id: 'g1' }, + }); + expect(mockPostIdentifiedComment).toHaveBeenCalledTimes(1); + const posted = mockPostIdentifiedComment.mock.calls[0][1]; + expect(posted.issueId).toBe('issue-uuid-42'); + expect(posted.body).toContain('Approval needed'); + expect(posted.body).toContain('Reply approve, or deny with an optional reason'); + expect(posted.body).toContain('bgagent approve t-lin g1 --scope this_call'); + expect(mockPostIssueComment).not.toHaveBeenCalled(); + expect(mockUpsertThreadedReply).not.toHaveBeenCalled(); + const updates = mockDdbSend.mock.calls.filter(([c]: any[]) => c._type === 'Update'); + // Thread mapping first (keyed on the comment id), then the delivery receipt. + expect(updates[0][0].input.Key.task_id).toMatch(/^LINEAR_COMMENT#org-uuid-acme#/); + if (fails) { + expect(outcome.infraRejections).toHaveLength(1); + expect(updates).toHaveLength(1); + } else { + expect(outcome.infraRejections).toHaveLength(0); + expect(updates).toHaveLength(2); + expect(updates[1][0].input.ExpressionAttributeNames).toEqual({ '#marker': 'notified_linear_approval_requested' }); + } + }); + + test('an outcome notice closes the reply thread even when the post fails', async () => { + answer({ ...pendingRow, status: 'TIMED_OUT' }, { ...awaiting, status: 'RUNNING' }); + mockPostIssueComment.mockResolvedValueOnce({ ok: false, retryable: false }); + await routeEvent({ + task_id: 't-lin', + event_id: 'timeout-event', + event_type: 'agent_milestone', + timestamp: '2026-09-16T12:30:00Z', + metadata: { milestone: 'approval_timed_out', request_id: 'g1' }, + }); + const updates = mockDdbSend.mock.calls.filter(([c]: any[]) => c._type === 'Update'); + expect(updates[0][0].input.UpdateExpression).toBe('SET #ttl = if_not_exists(#ttl, :ttl)'); + expect(mockPostIssueComment.mock.calls[0][2]).toContain('Approval request timed out'); + expect(updates.some(([c]: any[]) => c.input.ExpressionAttributeNames?.['#marker'])).toBe(false); + }); + + test('a task that ends while waiting closes its reply thread before the terminal comment', async () => { + answer(pendingRow, { ...awaiting, status: 'CANCELLED' }); + await routeEvent({ + task_id: 't-lin', + event_id: 'cancel-event', + event_type: 'task_cancelled', + timestamp: '2026-09-16T12:10:00Z', + metadata: {}, + }); + const updates = mockDdbSend.mock.calls.filter(([c]: any[]) => c._type === 'Update'); + expect(updates[0][0].input.Key.task_id).toMatch(/^LINEAR_COMMENT#org-uuid-acme#/); + expect(updates[0][0].input.UpdateExpression).toBe('SET #ttl = if_not_exists(#ttl, :ttl)'); + }); + + test('a non-approval milestone is not treated as an approval', async () => { + answer(pendingRow, awaiting); + await routeEvent({ + task_id: 't-lin', + event_id: 'other', + event_type: 'agent_milestone', + timestamp: '2026-09-16T12:00:00Z', + metadata: { milestone: 'approval_gate_cap_reached', request_id: 'g1' }, + }); + expect(mockPostIdentifiedComment).not.toHaveBeenCalled(); + }); + }); + test('task_completed posts โœ… comment with cost / turns / duration on linked Linear issue', async () => { mockGet(TASK_RECORD_LINEAR); diff --git a/cdk/test/handlers/get-policies.test.ts b/cdk/test/handlers/get-policies.test.ts index 2d9dd59f3..f9fa7186b 100644 --- a/cdk/test/handlers/get-policies.test.ts +++ b/cdk/test/handlers/get-policies.test.ts @@ -355,6 +355,6 @@ describe('get-policies', () => { (r: { rule_id: string }) => r.rule_id === 'force_push_any', ); expect(soft.severity).toBe('medium'); - expect(soft.approval_timeout_s).toBe(300); + expect(soft.approval_timeout_s).toBe(3600); }); }); diff --git a/cdk/test/handlers/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/linear-webhook-processor.test.ts b/cdk/test/handlers/linear-webhook-processor.test.ts index 79f53882f..ec51f8434 100644 --- a/cdk/test/handlers/linear-webhook-processor.test.ts +++ b/cdk/test/handlers/linear-webhook-processor.test.ts @@ -25,6 +25,7 @@ jest.mock('@aws-sdk/client-dynamodb', () => ({ DynamoDBClient: jest.fn(() => ({} jest.mock('@aws-sdk/lib-dynamodb', () => ({ DynamoDBDocumentClient: { from: jest.fn(() => ({ send: ddbSend })) }, GetCommand: jest.fn((input: unknown) => ({ _type: 'Get', input })), + ScanCommand: jest.fn((input: unknown) => ({ _type: 'Scan', input })), })); const createTaskCoreMock = jest.fn(); @@ -132,6 +133,34 @@ function issue(overrides: Record = {}): Record }; } +describe('linear-webhook-processor scheduled grant health probe (#1004)', () => { + beforeEach(() => { + ddbSend.mockReset(); + createTaskCoreMock.mockReset(); + resolveLinearOauthTokenMock.mockReset(); + }); + + test('the probe event resolves every active workspace and never takes the webhook path', async () => { + ddbSend.mockResolvedValueOnce({ + Items: [ + { linear_workspace_id: 'ws-live', workspace_slug: 'live', status: 'active' }, + { linear_workspace_id: 'ws-dead', workspace_slug: 'dead', status: 'active' }, + { linear_workspace_id: 'ws-latched', workspace_slug: 'latched', status: 'revoked' }, + ], + }); + resolveLinearOauthTokenMock.mockImplementation(async (id: string) => (id === 'ws-live' ? { access_token: 't' } : null)); + + await handler({ grant_health_probe: true }); + + expect(ddbSend.mock.calls[0][0]).toMatchObject({ _type: 'Scan', input: { TableName: 'LinearWorkspaceRegistry' } }); + expect(resolveLinearOauthTokenMock.mock.calls).toEqual([ + ['ws-live', 'LinearWorkspaceRegistry'], + ['ws-dead', 'LinearWorkspaceRegistry'], + ]); + expect(createTaskCoreMock).not.toHaveBeenCalled(); + }); +}); + describe('linear-webhook-processor handler', () => { beforeEach(() => { ddbSend.mockReset(); diff --git a/cdk/test/handlers/reconcile-admission-queue.test.ts b/cdk/test/handlers/reconcile-admission-queue.test.ts index 6d3983fe3..9f2209c78 100644 --- a/cdk/test/handlers/reconcile-admission-queue.test.ts +++ b/cdk/test/handlers/reconcile-admission-queue.test.ts @@ -47,7 +47,7 @@ process.env.MAX_CONCURRENT_TASKS_PER_USER = '3'; process.env.QUEUE_MAX_AGE_SECONDS = '86400'; process.env.TASK_RETENTION_DAYS = '90'; -import { handler } from '../../src/handlers/reconcile-admission-queue'; +import { handler, queueHeartbeatMark } from '../../src/handlers/reconcile-admission-queue'; /** A QUEUED StatusIndex row as the DDB low-level client returns it. */ function queuedRow(opts: { @@ -481,3 +481,86 @@ describe('reconcile-admission-queue โ€” #331 regression (fan-out burst)', () => expect(flipped).toEqual(['P1', 'P2']); }); }); + +describe('reconcile-admission-queue โ€” queue heartbeat (#1066)', () => { + test('the mark counts whole 15-minute periods queued', () => { + expect([0, 899, 900, 1799, 1800, 2700].map(queueHeartbeatMark)).toEqual([0, 0, 1, 1, 2, 3]); + }); + + /** A full queue for user u1 with one task queued for ``age`` seconds; ``claim`` scripts the mark's conditional write. */ + function fullQueue(age: number, claim: () => Promise = () => Promise.resolve({})): void { + mockDdbSend.mockImplementation((cmd: SentCommand) => { + if (cmd._type === 'Query') return Promise.resolve({ Items: [queuedRow({ task_id: 'LONG', user_id: 'u1', created_at: isoAge(age) })] }); + if (cmd._type === 'GetItem') return Promise.resolve({ Item: { active_count: { N: '3' } } }); + if (cmd._type === 'UpdateItem' && cmd.input.UpdateExpression === 'SET queue_heartbeat_mark = :mark') return claim(); + return Promise.resolve({}); + }); + } + const announced = () => sentDdbCommands('PutItem').map(c => c.input.Item).filter(i => i.event_type.S === 'admission_queued'); + + test('a mark is announced by the first run past it, even when runs drift past the minute after it', async () => { + fullQueue(961); + await handler(); + expect(announced()).toHaveLength(1); + const claim = sentDdbCommands('UpdateItem').find(c => c.input.UpdateExpression === 'SET queue_heartbeat_mark = :mark')!; + expect(claim.input.ExpressionAttributeValues[':mark']).toEqual({ N: '1' }); + expect(claim.input.ConditionExpression).toContain('#s = :queued'); + }); + + test('a mark already announced (the conditional write fails) is not announced again', async () => { + fullQueue(1000, () => Promise.reject(Object.assign(new Error('claimed'), { name: 'ConditionalCheckFailedException' }))); + await handler(); + expect(announced()).toEqual([]); + }); + + test('a claim that fails for another reason sends nothing and does not fail the run', async () => { + fullQueue(1000, () => Promise.reject(new Error('throttled'))); + await expect(handler()).resolves.toEqual(expect.objectContaining({ queued_seen: 1 })); + expect(announced()).toEqual([]); + }); + + test('a task still waiting past a mark gets an admission_queued event with waited_s', async () => { + mockDdbSend.mockImplementation((cmd: SentCommand) => { + if (cmd._type === 'Query') { + return Promise.resolve({ + Items: [ + queuedRow({ task_id: 'LONG', user_id: 'u1', created_at: isoAge(920) }), + queuedRow({ task_id: 'FRESH', user_id: 'u1', created_at: isoAge(120) }), + ], + }); + } + if (cmd._type === 'GetItem') return Promise.resolve({ Item: { active_count: { N: '3' } } }); // full + return Promise.resolve({}); + }); + + await handler(); + const puts = sentDdbCommands('PutItem').map(c => c.input.Item); + expect(puts).toHaveLength(1); + expect(puts[0].task_id).toEqual({ S: 'LONG' }); + expect(puts[0].event_type).toEqual({ S: 'admission_queued' }); + expect(puts[0].metadata.M.reason).toEqual({ S: 'concurrency_limit' }); + // Past the 15-minute mark; the exact second depends on how long the test took to reach the handler. + expect(Number(puts[0].metadata.M.waited_s.N)).toBeGreaterThanOrEqual(900); + expect(mockLambdaSend).not.toHaveBeenCalled(); + }); + + test('picked-up tasks get no heartbeat; the ones left behind do', async () => { + mockDdbSend.mockImplementation((cmd: SentCommand) => { + if (cmd._type === 'Query') { + return Promise.resolve({ + Items: [ + queuedRow({ task_id: 'FIRST', user_id: 'u1', created_at: isoAge(930) }), + queuedRow({ task_id: 'SECOND', user_id: 'u1', created_at: isoAge(920) }), + ], + }); + } + if (cmd._type === 'GetItem') return Promise.resolve({ Item: { active_count: { N: '2' } } }); // one slot + return Promise.resolve({}); + }); + mockLambdaSend.mockResolvedValue({ StatusCode: 202 }); + + await handler(); + const heartbeats = sentDdbCommands('PutItem').map(c => c.input.Item).filter(i => i.event_type.S === 'admission_queued'); + expect(heartbeats.map(i => i.task_id.S)).toEqual(['SECOND']); + }); +}); diff --git a/cdk/test/handlers/reconcile-concurrency-grant-probe.test.ts b/cdk/test/handlers/reconcile-concurrency-grant-probe.test.ts new file mode 100644 index 000000000..4ecf30b57 --- /dev/null +++ b/cdk/test/handlers/reconcile-concurrency-grant-probe.test.ts @@ -0,0 +1,61 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +// The reconciler kicks the Linear grant health probe (#1004). +const mockLambdaSend = jest.fn(); +jest.mock('@aws-sdk/client-lambda', () => ({ + LambdaClient: jest.fn(() => ({ send: mockLambdaSend })), + InvokeCommand: jest.fn((input: unknown) => ({ _type: 'Invoke', input })), + InvocationType: { Event: 'Event' }, +})); +jest.mock('@aws-sdk/client-dynamodb', () => ({ + DynamoDBClient: jest.fn(() => ({ send: jest.fn() })), + ScanCommand: jest.fn(), + QueryCommand: jest.fn(), + UpdateItemCommand: jest.fn(), +})); + +process.env.TASK_TABLE_NAME = 'Tasks'; +process.env.USER_CONCURRENCY_TABLE_NAME = 'UserConcurrency'; +process.env.LINEAR_GRANT_PROBE_FUNCTION_ARN = 'arn:aws:lambda:us-east-1:123456789012:function:processor'; +process.env.RECONCILER_TICK_MINUTES = '15'; + +import { triggerLinearGrantProbe } from '../../src/handlers/reconcile-concurrency'; + +const WINDOW = 12 * 3_600_000; + +beforeEach(() => mockLambdaSend.mockReset()); + +test('async-invokes the processor with the probe event on the window tick only', async () => { + mockLambdaSend.mockResolvedValue({}); + expect(await triggerLinearGrantProbe(WINDOW * 100 + 60_000)).toBe(true); + expect(mockLambdaSend).toHaveBeenCalledTimes(1); + const { input } = mockLambdaSend.mock.calls[0][0]; + expect(input.FunctionName).toBe(process.env.LINEAR_GRANT_PROBE_FUNCTION_ARN); + expect(input.InvocationType).toBe('Event'); + expect(JSON.parse(Buffer.from(input.Payload).toString())).toEqual({ grant_health_probe: true }); + + expect(await triggerLinearGrantProbe(WINDOW * 100 + 20 * 60_000)).toBe(false); + expect(mockLambdaSend).toHaveBeenCalledTimes(1); +}); + +test('an invoke failure never breaks the reconciler', async () => { + mockLambdaSend.mockRejectedValue(new Error('throttled')); + await expect(triggerLinearGrantProbe(WINDOW * 7)).resolves.toBe(false); +}); diff --git a/cdk/test/handlers/shared/approval-notifications.test.ts b/cdk/test/handlers/shared/approval-notifications.test.ts new file mode 100644 index 000000000..f137bb687 --- /dev/null +++ b/cdk/test/handlers/shared/approval-notifications.test.ts @@ -0,0 +1,204 @@ +/** + * 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); + // eslint-disable-next-line no-control-regex -- asserts the escape character was stripped + expect(message.text).not.toMatch(/[\u001b\u202e]/); +}); diff --git a/cdk/test/handlers/shared/create-task-core.test.ts b/cdk/test/handlers/shared/create-task-core.test.ts index 4b7ec6e1b..684892ec4 100644 --- a/cdk/test/handlers/shared/create-task-core.test.ts +++ b/cdk/test/handlers/shared/create-task-core.test.ts @@ -1178,6 +1178,31 @@ describe('createTaskCore', () => { expect(record.approval_gate_cap).toBe(50); }); + // --- approval window: request > blueprint > platform default (#1066) --- + + test('the blueprint\'s approval window becomes the task\'s when the request sets none', async () => { + mockOnboardedWithConfig({ approval_timeout_s: 2700 }); + const result = await createTaskCore({ repo: 'org/repo', task_description: 'x' }, makeContext(), 'req-ats-repo'); + expect(result.statusCode).toBe(201); + expect(getPersistedTaskRecord().approval_timeout_s).toBe(2700); + }); + + test('a request\'s own approval window wins over the blueprint\'s', async () => { + mockOnboardedWithConfig({ approval_timeout_s: 2700 }); + const result = await createTaskCore( + { repo: 'org/repo', task_description: 'x', approval_timeout_s: 120 }, makeContext(), 'req-ats-body', + ); + expect(result.statusCode).toBe(201); + expect(getPersistedTaskRecord().approval_timeout_s).toBe(120); + }); + + test.each([5, 7200, 90.5, '1800'])('a blueprint window of %p is ignored, not a reason to refuse the task', async (bad) => { + mockOnboardedWithConfig({ approval_timeout_s: bad }); + const result = await createTaskCore({ repo: 'org/repo', task_description: 'x' }, makeContext(), 'req-ats-bad'); + expect(result.statusCode).toBe(201); + expect(getPersistedTaskRecord().approval_timeout_s).toBeUndefined(); + }); + test('persists blueprint-configured approval_gate_cap when within bounds', async () => { mockOnboardedWithConfig({ approval_gate_cap: 150 }); const result = await createTaskCore( diff --git a/cdk/test/handlers/shared/deny-reason-scanner.test.ts b/cdk/test/handlers/shared/deny-reason-scanner.test.ts index 4cbc50995..dd982c560 100644 --- a/cdk/test/handlers/shared/deny-reason-scanner.test.ts +++ b/cdk/test/handlers/shared/deny-reason-scanner.test.ts @@ -19,7 +19,7 @@ import * as fs from 'fs'; import * as path from 'path'; -import { DENY_REASON_SECRET_NAMES, scanDenyReason } from '../../../src/handlers/shared/deny-reason-scanner'; +import { DENY_REASON_SECRET_NAMES, redactValue, scanDenyReason } from '../../../src/handlers/shared/deny-reason-scanner'; // Shared with agent/tests/test_output_scanner.py: the agent's scanner has to // give the same text for a URL with a user and a password. @@ -381,3 +381,21 @@ describe('scanDenyReason', () => { expect(DENY_REASON_SECRET_NAMES).toContain('PRIVATE_KEY'); }); }); + +describe('redactValue (outbound Linear and GitHub text, #1066)', () => { + test('redacts every string in a nested value and keeps the shape and other values', () => { + const value = { + input: { body: 'token lin_api_EXAMPLE0EXAMPLE0EX here', count: 3, ok: true }, + list: ['AKIAIOSFODNN7EXAMPLE', null], + }; + expect(redactValue(value)).toEqual({ + input: { body: 'token [REDACTED-LINEAR_TOKEN] here', count: 3, ok: true }, + list: ['[REDACTED-AWS_KEY]', null], + }); + }); + + test('leaves ids and ordinary text alone', () => { + const value = { id: '420f1277-9f2b-4058-b9c1-ddbceeee6b96', body: 'Opened pull request https://github.com/acme/web/pull/7' }; + expect(redactValue(value)).toEqual(value); + }); +}); diff --git a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts index afdf004f3..c49699524 100644 --- a/cdk/test/handlers/shared/linear-agent-session-handler.test.ts +++ b/cdk/test/handlers/shared/linear-agent-session-handler.test.ts @@ -41,12 +41,16 @@ jest.mock('../../../src/handlers/shared/linear-oauth-resolver', () => ({ const emitAgentActivityMock = jest.fn(); const fetchAgentSessionIssueMock = jest.fn(); +const fetchSessionPromptActivityMock = jest.fn(); +const fetchSessionActivityShownMock = jest.fn(); jest.mock('../../../src/handlers/shared/linear-agent-session', () => { const actual = jest.requireActual('../../../src/handlers/shared/linear-agent-session'); return { ...actual, emitAgentActivity: (...args: unknown[]) => emitAgentActivityMock(...args), fetchAgentSessionIssue: (...args: unknown[]) => fetchAgentSessionIssueMock(...args), + fetchSessionPromptActivity: (...args: unknown[]) => fetchSessionPromptActivityMock(...args), + fetchSessionActivityShown: (...args: unknown[]) => fetchSessionActivityShownMock(...args), }; }); @@ -93,6 +97,12 @@ process.env.TASK_EVENTS_TABLE_NAME = 'TaskEvents'; process.env.NUDGES_TABLE_NAME = 'Nudges'; process.env.NUDGE_RATE_LIMIT_PER_MINUTE = '4'; process.env.LINEAR_WEBHOOK_DEDUP_TABLE_NAME = 'LinearDedup'; +process.env.TASK_APPROVALS_TABLE_NAME = 'Approvals'; + +const recordApprovalMock = jest.fn(); +const recordDenialMock = jest.fn(); +jest.mock('../../../src/handlers/approve-task', () => ({ recordApprovalForUser: (...a: unknown[]) => recordApprovalMock(...a) })); +jest.mock('../../../src/handlers/deny-task', () => ({ recordDenialForUser: (...a: unknown[]) => recordDenialMock(...a) })); import { SESSION_STOP_CANCELLED_VIA } from '../../../src/handlers/shared/linear-agent-session-event'; import { handleAgentSessionEvent } from '../../../src/handlers/shared/linear-agent-session-handler'; @@ -158,6 +168,7 @@ function ddbWith(opts: { linked?: boolean; mapping?: Record | n const key = (cmd.input as unknown as { Key: { task_id: string } }).Key.task_id; return { Item: taskRecords.get(key) }; } + if (cmd.input.TableName === 'Approvals') return approvalRow ? { Item: approvalRow } : {}; if (cmd.input.TableName === 'LinearDedup' && (cmd as unknown as { _type: string })._type === 'Get') { return sessionPointer ? { Item: { task_id: sessionPointer, ttl: Math.floor(Date.now() / 1000) + 600 } } : {}; } @@ -167,6 +178,8 @@ function ddbWith(opts: { linked?: boolean; mapping?: Record | n /** Task id the (strongly consistent) session โ†’ task pointer names, if any. */ let sessionPointer: string | null = null; +/** The approval request row the handler reads for a whole-task approval. */ +let approvalRow: Record | null = null; /** Commands sent to one table, by type. */ function sent(table: string, type: string): Array<{ input: Record }> { @@ -212,6 +225,7 @@ beforeEach(() => { jest.clearAllMocks(); taskRecords.clear(); sessionPointer = null; + approvalRow = null; resetSessionWorkspaceCacheForTests(); stopTaskComputeMock.mockResolvedValue(undefined); screenWithGuardrailMock.mockResolvedValue({ action: 'NONE' }); @@ -797,3 +811,178 @@ describe('channel_metadata builders', () => { expect(offenders).toEqual([]); }); }); + +describe('handleAgentSessionEvent โ€” approval requests in the session (#1066)', () => { + const OPEN = '01M89PC2Y1YDH7SJEVVYR0VCAX'; + const OPENED = '2026-11-26T10:00:00Z'; + const WRITTEN = '2026-11-26T10:05:00.000Z'; + const waiting = (user = 'platform-user-1') => { + approvalRow = { task_id: 't-1', request_id: OPEN, created_at: OPENED, matching_rule_ids: [] }; + priorTask({ + task_id: 't-1', + status: 'AWAITING_APPROVAL', + awaiting_approval_request_id: OPEN, + user_id: user, + linear_workspace_id: 'org-1', + session: 'session-1', + }); + }; + const lastEmit = () => emitAgentActivityMock.mock.calls.at(-1)!; + + /** Send a prompt that Linear holds as written: the same session, author and body. */ + const answer = async (body: string) => { + fetchSessionPromptActivityMock.mockResolvedValue({ sessionId: 'session-1', authorId: 'linear-user-1', body, createdAt: WRITTEN }); + await handleAgentSessionEvent(prompted({ content: { body } })); + }; + + beforeEach(() => { + // Linear recorded the open request's choice at 10:01; answers are written at 10:05. + fetchSessionActivityShownMock.mockResolvedValue({ sessionId: 'session-1', createdAt: '2026-11-26T10:01:00.000Z' }); + recordApprovalMock.mockResolvedValue({ statusCode: 202 }); + recordDenialMock.mockResolvedValue({ statusCode: 202 }); + }); + + test('the owner\'s Approve decides the open request through the API path, not as a nudge', async () => { + waiting(); + await answer('approve'); + expect(recordApprovalMock).toHaveBeenCalledWith({ + userId: 'platform-user-1', + taskId: 't-1', + decisionSource: JSON.stringify(['linear_session', 'org-1', 'activity-9']), + body: JSON.stringify({ request_id: OPEN, decision: 'approve' }), + }); + expect(submitNudgeMock).not.toHaveBeenCalled(); + expect(lastEmit()[2]).toEqual({ type: 'thought', body: 'Approved. The agent continues with this action.' }); + }); + + test('a deny with a reason passes the reason on', async () => { + waiting(); + await answer('deny use the staging config'); + expect(JSON.parse(recordDenialMock.mock.calls[0][0].body)).toEqual({ request_id: OPEN, decision: 'deny', reason: 'use the staging config' }); + expect(String(lastEmit()[2].body)).toContain('your reason: use the staging config'); + }); + + test('a request that was already answered or timed out changes nothing, and says so', async () => { + waiting(); + recordApprovalMock.mockResolvedValue({ statusCode: 409 }); + await answer('approve'); + expect(String(lastEmit()[2].body)).toContain('already answered or timed out'); + }); + + test('someone other than the owner gets the choice again, and nothing is decided', async () => { + waiting('someone-else'); + await answer('approve'); + expect(recordApprovalMock).not.toHaveBeenCalled(); + const [, , content, options] = lastEmit(); + expect(content.type).toBe('elicitation'); + expect(String(content.body)).toMatch(/^Only the task owner can decide this request\./); + expect(options).toEqual(expect.objectContaining({ signal: 'select' })); + }); + + test('anything else keeps the request open: the choice comes back, nothing is nudged', async () => { + waiting(); + await answer('what does this command do?'); + expect(recordApprovalMock).not.toHaveBeenCalled(); + expect(submitNudgeMock).not.toHaveBeenCalled(); + expect(lastEmit()[2].type).toBe('elicitation'); + }); + + test('"Approve for this task" approves the request\'s one rule for the rest of the task', async () => { + waiting(); + approvalRow = { ...approvalRow, matching_rule_ids: ['write_env_files'] }; + await answer('approve for this task'); + expect(JSON.parse(recordApprovalMock.mock.calls[0][0].body)).toEqual({ request_id: OPEN, decision: 'approve', scope: 'rule:write_env_files' }); + expect(String(lastEmit()[2].body)).toContain('won\'t ask again for `rule:write_env_files`'); + }); + + test('a whole-task answer to a request that matched several rules approves this action only', async () => { + waiting(); + approvalRow = { ...approvalRow, matching_rule_ids: ['force_push_any', 'force_push_main'] }; + await answer('approve for this task'); + expect(JSON.parse(recordApprovalMock.mock.calls[0][0].body)).toEqual({ request_id: OPEN, decision: 'approve' }); + expect(String(lastEmit()[2].body)).toMatch(/^Approved this action only/); + }); + + test('a late Approve after the task finished starts nothing', async () => { + priorTask({ task_id: 't-1', status: 'COMPLETED', repo: 'acme/web', linear_workspace_id: 'org-1', session: 'session-1' }); + await answer('approve'); + expect(createTaskCoreMock).not.toHaveBeenCalled(); + expect(lastEmit()[2]).toEqual(expect.objectContaining({ type: 'response', body: expect.stringContaining('Nothing is waiting for your approval') })); + }); + + test('a new session whose request starts with "Deny" starts the task', async () => { + await handleAgentSessionEvent(created({ + agentSession: { id: 'session-1', issueId: 'issue-1', creatorId: 'linear-user-1', comment: { body: 'Deny anonymous access to /admin' } }, + })); + expect(createTaskCoreMock).toHaveBeenCalledTimes(1); + }); + + test('a follow-up that starts with "deny" while the task runs without a request is passed to the agent', async () => { + priorTask({ task_id: 't-1', status: 'RUNNING', user_id: 'platform-user-1', linear_workspace_id: 'org-1', session: 'session-1' }); + await answer('deny-list the tracker domains too'); + expect(submitNudgeMock).toHaveBeenCalledWith(expect.objectContaining({ message: 'deny-list the tracker domains too' })); + }); + + test('an Approve while the task runs without a request is not passed to the agent', async () => { + priorTask({ task_id: 't-1', status: 'RUNNING', user_id: 'platform-user-1', linear_workspace_id: 'org-1', session: 'session-1' }); + await answer('deny'); + expect(submitNudgeMock).not.toHaveBeenCalled(); + expect(lastEmit()[2]).toEqual(expect.objectContaining({ type: 'thought', body: expect.stringContaining('Nothing is waiting') })); + }); + + test('a button from an earlier request decides nothing; the current request\'s button does', async () => { + waiting(); + await answer('approve request 01M89PAAAAAAAAAAAAAAAAAAAA'); + expect(recordApprovalMock).not.toHaveBeenCalled(); + expect(String(lastEmit()[2].body)).toMatch(/^That answer was for an earlier request/); + expect(lastEmit()[3]).toEqual(expect.objectContaining({ signal: 'select' })); + + await answer(`deny request ${OPEN}`); + expect(JSON.parse(recordDenialMock.mock.calls[0][0].body)).toEqual({ request_id: OPEN, decision: 'deny' }); + }); + + test('a reply Linear does not hold as written decides nothing (a forged webhook)', async () => { + waiting(); + for (const held of [ + null, + { sessionId: 'session-1', authorId: 'someone-else', body: 'approve' }, + { sessionId: 'other-session', authorId: 'linear-user-1', body: 'approve' }, + { sessionId: 'session-1', authorId: 'linear-user-1', body: 'deny' }, + ]) { + recordApprovalMock.mockClear(); + fetchSessionPromptActivityMock.mockResolvedValue(held); + await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); + expect(recordApprovalMock).not.toHaveBeenCalled(); + expect(String(lastEmit()[2].body)).toMatch(/^I couldn't confirm this answer with Linear/); + } + expect(fetchSessionPromptActivityMock).toHaveBeenCalledWith('lin_tok', 'org-1', 'activity-9'); + }); + + test('when Linear cannot be asked, the delivery fails so it is retried, and nothing is decided', async () => { + waiting(); + fetchSessionPromptActivityMock.mockRejectedValue(new Error('Linear session prompt verification unavailable')); + await expect(handleAgentSessionEvent(prompted({ content: { body: 'approve' } }))).rejects.toThrow('verification unavailable'); + expect(recordApprovalMock).not.toHaveBeenCalled(); + }); + + test('an answer Linear recorded before the open request\'s choice decides nothing (a delayed retry)', async () => { + waiting(); + fetchSessionPromptActivityMock.mockResolvedValue({ + sessionId: 'session-1', authorId: 'linear-user-1', body: 'approve', createdAt: '2026-11-26T10:00:59.999Z', + }); + await handleAgentSessionEvent(prompted({ content: { body: 'approve' } })); + expect(recordApprovalMock).not.toHaveBeenCalled(); + expect(String(lastEmit()[2].body)).toMatch(/^That answer was written before this request was shown here/); + expect(fetchSessionActivityShownMock).toHaveBeenCalledWith('lin_tok', 'org-1', expect.stringMatching(/^[0-9a-f-]{36}$/)); + }); + + test.each([ + ['not posted yet', null], + ['posted in another session', { sessionId: 'other-session', createdAt: '2026-11-26T10:01:00.000Z' }], + ])('a choice %s cannot be answered here', async (_label, shown) => { + waiting(); + fetchSessionActivityShownMock.mockResolvedValue(shown); + await answer('approve'); + expect(recordApprovalMock).not.toHaveBeenCalled(); + }); +}); diff --git a/cdk/test/handlers/shared/linear-agent-session.test.ts b/cdk/test/handlers/shared/linear-agent-session.test.ts index 1cd071dfe..b10afafe7 100644 --- a/cdk/test/handlers/shared/linear-agent-session.test.ts +++ b/cdk/test/handlers/shared/linear-agent-session.test.ts @@ -27,6 +27,8 @@ import { buildAgentSessionTaskDescription, emitAgentActivity, fetchAgentSessionIssue, + fetchSessionActivityShown, + fetchSessionPromptActivity, } from '../../../src/handlers/shared/linear-agent-session'; import { isHandledAgentSessionAction, @@ -109,6 +111,17 @@ describe('parseAgentSessionEvent', () => { expect(at('https://linear.app/acme/issue/ENG-1 is related')).toBe('https://linear.app/acme/issue/ENG-1 is related'); }); + test('Linear\'s own delegation comment is not an instruction (it named every delegated branch)', () => { + const at = (body: string) => parseAgentSessionEvent({ + ...base, action: 'created', agentSession: { id: 's-1', issueId: 'i-1', comment: { body } }, + })?.directive; + expect(at('This thread is for an agent session with alanturing2.')).toBe(''); + expect(at('this thread is for an agent session with bgagent')).toBe(''); + // A person's comment that merely starts the same way is still theirs. + expect(at('This thread is for an agent session with bgagent, so please add tests')).toBe( + 'This thread is for an agent session with bgagent, so please add tests'); + }); + test('created by delegation has an empty directive and tolerates a blank promptContext', () => { const r = parseAgentSessionEvent({ ...base, action: 'created', agentSession: { id: 's-1', issueId: 'i-1' }, promptContext: ' ' }); expect(r).toEqual(expect.objectContaining({ directive: '', actorId: null, promptContext: null })); @@ -257,4 +270,53 @@ describe('GraphQL helpers', () => { expect(failed.ok).toBe(false); expect('error' in failed).toBe(true); }); + + describe('fetchSessionPromptActivity (consent is read from Linear, not the webhook)', () => { + const reply = (activity: unknown, org = 'org-1') => jsonResponse({ + data: { organization: { id: org }, viewer: { id: 'app-user' }, agentActivity: activity }, + }); + const prompt = (author: unknown, typename = 'AgentActivityPromptContent') => ({ + createdAt: '2026-11-26T10:05:00.000Z', + agentSession: { id: 's-1' }, + content: { __typename: typename, body: 'approve' }, + user: null, + promptAuthor: author, + }); + + test('a human\'s prompt comes back with its session, author and body', async () => { + fetchMock.mockResolvedValueOnce(reply(prompt({ id: 'u-1', app: false }))); + await expect(fetchSessionPromptActivity('tok', 'org-1', 'a-1')).resolves.toEqual({ + sessionId: 's-1', authorId: 'u-1', body: 'approve', createdAt: '2026-11-26T10:05:00.000Z', + }); + expect(sentBody(0).variables).toEqual({ id: 'a-1' }); + }); + + test.each([ + ['an app', prompt({ id: 'u-2', app: true })], + ['this token\'s own identity', prompt({ id: 'app-user', app: false })], + ['not a prompt', prompt({ id: 'u-1', app: false }, 'AgentActivityThoughtContent')], + ['missing', null], + ])('an activity by %s is not consent', async (_label, activity) => { + fetchMock.mockResolvedValueOnce(reply(activity)); + await expect(fetchSessionPromptActivity('tok', 'org-1', 'a-1')).resolves.toBeNull(); + }); + + test('fetchSessionActivityShown reads when Linear recorded an activity, and in which session', async () => { + fetchMock.mockResolvedValueOnce(jsonResponse({ + data: { organization: { id: 'org-1' }, agentActivity: { createdAt: '2026-11-26T10:01:00.000Z', agentSession: { id: 's-1' } } }, + })); + await expect(fetchSessionActivityShown('tok', 'org-1', 'n-1')).resolves.toEqual({ sessionId: 's-1', createdAt: '2026-11-26T10:01:00.000Z' }); + fetchMock.mockResolvedValueOnce(jsonResponse({ data: { organization: { id: 'org-1' }, agentActivity: null } })); + await expect(fetchSessionActivityShown('tok', 'org-1', 'n-1')).resolves.toBeNull(); + fetchMock.mockResolvedValueOnce(jsonResponse({}, 500)); + await expect(fetchSessionActivityShown('tok', 'org-1', 'n-1')).rejects.toThrow('unavailable'); + }); + + test('another workspace, or Linear failing, throws so the delivery retries', async () => { + fetchMock.mockResolvedValueOnce(reply(prompt({ id: 'u-1', app: false }), 'org-2')); + await expect(fetchSessionPromptActivity('tok', 'org-1', 'a-1')).rejects.toThrow('workspace mismatch'); + fetchMock.mockResolvedValueOnce(jsonResponse({}, 500)); + await expect(fetchSessionPromptActivity('tok', 'org-1', 'a-1')).rejects.toThrow('unavailable'); + }); + }); }); 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/cdk/test/handlers/shared/linear-feedback.test.ts b/cdk/test/handlers/shared/linear-feedback.test.ts index 50d668657..571a6228c 100644 --- a/cdk/test/handlers/shared/linear-feedback.test.ts +++ b/cdk/test/handlers/shared/linear-feedback.test.ts @@ -91,6 +91,13 @@ describe('linear-feedback', () => { expect(body.variables).toEqual({ issueId: ISSUE_ID, body: 'โŒ blocked' }); }); + test('a credential in the text is redacted before it leaves for Linear, the request token is not touched', async () => { + await postIssueComment(CTX, ISSUE_ID, 'Failed: push rejected for ghp_abcdefghijklmnopqrstuvwxyz0123456789AB'); + const [, init] = fetchMock.mock.calls[0]; + expect(JSON.parse(init.body as string).variables.body).toBe('Failed: push rejected for [REDACTED-GITHUB_TOKEN]'); + expect(init.headers).toMatchObject({ Authorization: `Bearer ${TOKEN}` }); + }); + test('terminal failure (not retryable) when the token cannot be resolved', async () => { resolveLinearOauthTokenMock.mockResolvedValueOnce(null); @@ -568,6 +575,13 @@ describe('linear-feedback', () => { expect(JSON.parse(fetchMock.mock.calls[1][1].body).variables.stateId).toBe('s-inreview'); }); + test('a strict name: a team without "In Review" gets no move, not its first started state', async () => { + const noReview = TEAM_STATES.filter((st) => st.id !== 's-inreview'); + fetchMock.mockResolvedValueOnce(jsonResponse({ data: { issue: { state: cur('s-backlog'), team: { states: { nodes: noReview } } } } })); + expect(await transitionIssueState(CTX, ISSUE_ID, 'started', ['In Review'], false, true)).toBe(false); + expect(fetchMock).toHaveBeenCalledTimes(1); // the query only, no issueUpdate + }); + test('already in target state โ†’ no mutation, returns false', async () => { fetchMock.mockResolvedValueOnce(statesResp(cur('s-inreview'))); const ok = await transitionIssueState(CTX, ISSUE_ID, 'started', ['In Review']); diff --git a/cdk/test/handlers/shared/linear-grant-health.test.ts b/cdk/test/handlers/shared/linear-grant-health.test.ts new file mode 100644 index 000000000..d4f8eb193 --- /dev/null +++ b/cdk/test/handlers/shared/linear-grant-health.test.ts @@ -0,0 +1,98 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { + GRANT_HEALTH_PROBE_EVENT, + isGrantHealthProbe, + isProbeTick, + probeLinearGrants, +} from '../../../src/handlers/shared/linear-grant-health'; + +function fakeDdb(pages: Array<{ Items: unknown[]; LastEvaluatedKey?: Record }>) { + const send = jest.fn(); + for (const page of pages) send.mockResolvedValueOnce(page); + return { client: { send } as unknown as DynamoDBDocumentClient, send }; +} + +describe('isGrantHealthProbe', () => { + test('recognises only the scheduled probe input', () => { + expect(isGrantHealthProbe(GRANT_HEALTH_PROBE_EVENT)).toBe(true); + expect(isGrantHealthProbe({ raw_body: '{}' })).toBe(false); + expect(isGrantHealthProbe({ grant_health_probe: 'true' })).toBe(false); + expect(isGrantHealthProbe(null)).toBe(false); + }); +}); + +describe('isProbeTick', () => { + const HOUR = 3_600_000; + test('fires on exactly one 15-minute tick per 12-hour window, wherever the ticks start', () => { + for (const offsetMs of [0, 7 * 60_000, 14 * 60_000 + 59_999]) { + const fired: number[] = []; + for (let t = offsetMs; t < 48 * HOUR; t += 15 * 60_000) if (isProbeTick(t, 15)) fired.push(t); + expect(fired).toHaveLength(4); + expect(fired.map(t => Math.floor(t / (12 * HOUR)))).toEqual([0, 1, 2, 3]); + } + }); + + test('a nonsensical cadence probes every tick instead of never', () => { + expect(isProbeTick(5 * HOUR, Number.NaN)).toBe(true); + expect(isProbeTick(5 * HOUR, 0)).toBe(true); + expect(isProbeTick(5 * HOUR, 15, Number.NaN)).toBe(true); + }); +}); + +describe('probeLinearGrants', () => { + test('pages the registry and resolves every active workspace, skipping latched ones', async () => { + const { client, send } = fakeDdb([ + { + Items: [ + { linear_workspace_id: 'ws-1', workspace_slug: 'alpha', status: 'active' }, + { linear_workspace_id: 'ws-2', workspace_slug: 'beta', status: 'revoked' }, + ], + LastEvaluatedKey: { linear_workspace_id: 'ws-2' }, + }, + { Items: [{ linear_workspace_id: 'ws-3', workspace_slug: 'gamma', status: 'active' }] }, + ]); + const resolve = jest.fn(async (id: string) => (id === 'ws-1' ? { access_token: 't' } : null)); + + const report = await probeLinearGrants(client, 'Registry', resolve); + + expect(resolve.mock.calls.map(([id]) => id)).toEqual(['ws-1', 'ws-3']); + expect(report).toEqual({ checked: 2, healthy: 1, unhealthy: ['gamma'], revoked: ['beta'] }); + expect(send).toHaveBeenCalledTimes(2); + expect(send.mock.calls[1][0].input.ExclusiveStartKey).toEqual({ linear_workspace_id: 'ws-2' }); + }); + + test('one workspace throwing does not hide the others', async () => { + const { client } = fakeDdb([{ + Items: [ + { linear_workspace_id: 'ws-1', workspace_slug: 'alpha', status: 'active' }, + { linear_workspace_id: 'ws-2', status: 'active' }, + ], + }]); + const resolve = jest.fn() + .mockRejectedValueOnce(new Error('throttled')) + .mockResolvedValueOnce({ access_token: 't' }); + + expect(await probeLinearGrants(client, 'Registry', resolve)).toEqual({ + checked: 2, healthy: 1, unhealthy: ['alpha'], revoked: [], + }); + }); +}); diff --git a/cdk/test/handlers/shared/linear-session-approval.test.ts b/cdk/test/handlers/shared/linear-session-approval.test.ts new file mode 100644 index 000000000..20dda4c64 --- /dev/null +++ b/cdk/test/handlers/shared/linear-session-approval.test.ts @@ -0,0 +1,120 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import type { ApprovalNotification } from '../../../src/handlers/shared/approval-notifications'; +import { + formatDeadline, + parseSessionApprovalAnswer, + repeatedApprovalChoice, + sessionApprovalActivity, + sessionDecisionNote, + waitingOnYouLine, +} from '../../../src/handlers/shared/linear-session-approval'; + +const NOW = new Date('2026-11-25T21:10:00Z'); +const REQ = '01M89PC2Y1YDH7SJEVVYR0VCAX'; +const values = (a: { signalMetadata?: unknown }) => (a.signalMetadata as { options: Array<{ label: string; value: string }> }).options; +const notice = (deadline?: string): ApprovalNotification => ({ + title: 'Approval needed', + text: 'Approval needed\nThe agent wants to run a shell command.', + taskId: 't-1', + requestId: REQ, + userId: 'u-1', + marker: 'notified_linear_session_approval_requested', + ...(deadline && { deadline }), +}); + +test('a deadline reads as a clock time and how long is left, with the date when it is not today', () => { + expect(formatDeadline('2026-11-25T21:40:00Z', NOW)).toBe('21:40 UTC (in 30 min)'); + expect(formatDeadline('2026-11-26T09:40:00Z', NOW)).toBe('Thu 26 Nov, 09:40 UTC (in 13 h)'); + expect(formatDeadline('not a date', NOW)).toBeNull(); +}); + +test('the waiting line says what happens if nobody answers', () => { + expect(waitingOnYouLine('2026-11-25T21:40:00Z', NOW)) + .toBe('**Waiting on you.** Reply by 21:40 UTC (in 30 min), or it is denied and the agent carries on without it.'); + expect(waitingOnYouLine(undefined, NOW)).toBe('**Waiting on you.** The agent is paused until you answer.'); +}); + +test('a pending request is a choice with Approve / Deny buttons and the waiting line', () => { + const a = sessionApprovalActivity('approval_requested', notice('2026-11-25T21:40:00Z'), NOW); + expect(a.content.type).toBe('elicitation'); + expect(a.signal).toBe('select'); + // Each button names its request, so a late click on it cannot decide a later one. + expect(values(a)).toEqual([ + { label: 'Approve', value: `approve request ${REQ}` }, + { label: 'Deny', value: `deny request ${REQ}` }, + ]); + const body = (a.content as { body: string }).body; + expect(body).toContain('The agent wants to run a shell command.'); + expect(body.endsWith('Reply by 21:40 UTC (in 30 min), or it is denied and the agent carries on without it.')).toBe(true); +}); + +test('a decision, timeout or stranded wait is a note without buttons', () => { + for (const type of ['approval_decision_recorded', 'approval_timed_out', 'approval_stranded']) { + const a = sessionApprovalActivity(type, notice(), NOW); + expect(a.content.type).toBe('thought'); + expect(a.signal).toBeUndefined(); + } +}); + +test('the repeated choice keeps the buttons', () => { + const a = repeatedApprovalChoice('Only the task owner can decide this request.', REQ, ['write_env_files']); + expect(values(a).map((o) => o.label)).toEqual(['Approve', 'Approve for this task', 'Deny']); + expect(a.content).toEqual({ type: 'elicitation', body: expect.stringMatching(/^Only the task owner can decide this request\./) }); + expect(a.signal).toBe('select'); +}); + +test('the note after a decision says what happened', () => { + expect(sessionDecisionNote({ decision: 'approve' }, { statusCode: 202 })).toBe('Approved. The agent continues with this action.'); + expect(sessionDecisionNote({ decision: 'deny', reason: 'use staging' }, { statusCode: 202 })) + .toBe('Denied. The agent carries on without it (your reason: use staging).'); + expect(sessionDecisionNote({ decision: 'approve' }, { statusCode: 409 })).toContain('already answered or timed out'); + expect(sessionDecisionNote({ decision: 'approve' }, { statusCode: 404 })).toContain('already answered or timed out'); + expect(sessionDecisionNote({ decision: 'deny' }, { statusCode: 429 })).toContain('Too many'); + expect(sessionDecisionNote({ decision: 'deny' }, { statusCode: 500 })).toContain('bgagent approve'); +}); + +test('"Approve for this task" is offered only for a request that matched exactly one rule', () => { + const labels = (ruleIds?: string[]) => (sessionApprovalActivity('approval_requested', { ...notice(), ...(ruleIds && { ruleIds }) }, NOW) + .signalMetadata as { options: Array<{ label: string }> }).options.map((o) => o.label); + expect(labels(['write_env_files'])).toEqual(['Approve', 'Approve for this task', 'Deny']); + expect(labels(['force_push_any', 'force_push_main'])).toEqual(['Approve', 'Deny']); + expect(labels()).toEqual(['Approve', 'Deny']); +}); + +test('the whole-task answer parses from the button value or typed', () => { + expect(parseSessionApprovalAnswer('approve for this task')).toEqual({ decision: 'approve', wholeTask: true }); + expect(parseSessionApprovalAnswer('Approve for the whole task.')).toEqual({ decision: 'approve', wholeTask: true }); + expect(parseSessionApprovalAnswer('approve')).toEqual({ decision: 'approve' }); + expect(parseSessionApprovalAnswer('approve for this task and also rename the file')).toBeNull(); +}); + +test('the note says what a whole-task approval covered', () => { + expect(sessionDecisionNote({ decision: 'approve', wholeTask: true }, { statusCode: 202 }, 'rule:write_env_files')) + .toBe('Approved for the rest of this task: the agent won\'t ask again for `rule:write_env_files`.'); + expect(sessionDecisionNote({ decision: 'approve', wholeTask: true }, { statusCode: 202 })).toMatch(/^Approved this action only/); +}); + +test('a button value carries its request; typed answers do not', () => { + expect(parseSessionApprovalAnswer(`approve request ${REQ}`)).toEqual({ decision: 'approve', requestId: REQ }); + expect(parseSessionApprovalAnswer(`approve for this task request ${REQ}`)).toEqual({ decision: 'approve', requestId: REQ, wholeTask: true }); + expect(parseSessionApprovalAnswer(`deny request ${REQ}`)).toEqual({ decision: 'deny', requestId: REQ }); + expect(parseSessionApprovalAnswer('deny request a refund')).toEqual({ decision: 'deny', reason: 'request a refund' }); +}); diff --git a/cdk/test/handlers/shared/linear-session-checklist.test.ts b/cdk/test/handlers/shared/linear-session-checklist.test.ts new file mode 100644 index 000000000..cca9dec4a --- /dev/null +++ b/cdk/test/handlers/shared/linear-session-checklist.test.ts @@ -0,0 +1,69 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { + CHECKLIST_STAGE, + checklistKind, + checklistMoveForEvent, + closingLine, + renderChecklist, +} from '../../../src/handlers/shared/linear-session-checklist'; + +const statuses = (steps: ReturnType) => steps.map((s) => s.status); + +test('coding tasks get a checklist, other workflows do not', () => { + expect(checklistKind('coding/new-task-v1')).toBe('new'); + expect(checklistKind(undefined)).toBe('new'); + expect(checklistKind('coding/pr-iteration-v1')).toBe('iteration'); + expect(checklistKind('review/pr-review-v1')).toBeNull(); +}); + +test('steps before the stage are done, the stage is in progress with its note', () => { + const steps = renderChecklist('new', { stage: CHECKLIST_STAGE.code, note: 'round 2' }); + expect(statuses(steps)).toEqual(['completed', 'completed', 'inProgress', 'pending', 'pending']); + expect(steps[2].content).toBe('Write the code โ€” round 2'); +}); + +test('the pull request number stays on its step once it exists', () => { + const steps = renderChecklist('iteration', { stage: CHECKLIST_STAGE.review, pr: '#7' }); + expect(steps[3].content).toBe('Push to the pull request โ€” #7'); + expect(steps[4]).toEqual({ content: 'Ready for your review', status: 'inProgress' }); +}); + +test('a finished task completes every step; a stopped one cancels what was left', () => { + expect(statuses(renderChecklist('new', { stage: CHECKLIST_STAGE.review }, 'done'))).toEqual(Array(5).fill('completed')); + expect(statuses(renderChecklist('new', { stage: CHECKLIST_STAGE.code }, 'stopped'))) + .toEqual(['completed', 'completed', 'canceled', 'canceled', 'canceled']); +}); + +test('events move the checklist to their stage; others do not move it', () => { + expect(checklistMoveForEvent('admission_queued')).toEqual({ stage: CHECKLIST_STAGE.understand, note: 'queued for a free slot' }); + expect(checklistMoveForEvent('hydration_complete')).toEqual({ stage: CHECKLIST_STAGE.setup }); + expect(checklistMoveForEvent('repo_setup_complete')).toEqual({ stage: CHECKLIST_STAGE.code }); + expect(checklistMoveForEvent('agent_execution_complete')).toEqual({ stage: CHECKLIST_STAGE.pr }); + expect(checklistMoveForEvent('pr_created')).toEqual({ stage: CHECKLIST_STAGE.review }); + expect(checklistMoveForEvent('agent_tool_call')).toBeNull(); +}); + +test('the closing line says whether the reader has to act', () => { + expect(closingLine('question')).toMatch(/^\*\*Waiting on you\.\*\*/); + expect(closingLine('pr')).toContain('review the pull request'); + for (const o of ['no_change', 'cancelled'] as const) expect(closingLine(o)).toContain('Nothing needed from you'); + expect(closingLine('failed')).toContain('try again'); +}); diff --git a/cdk/test/handlers/shared/linear-session-progress.test.ts b/cdk/test/handlers/shared/linear-session-progress.test.ts new file mode 100644 index 000000000..67f2e77b8 --- /dev/null +++ b/cdk/test/handlers/shared/linear-session-progress.test.ts @@ -0,0 +1,71 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { progressActivityId, sessionProgressActivity } from '../../../src/handlers/shared/linear-session-progress'; + +describe('sessionProgressActivity (#1066)', () => { + test('tool calls are an ephemeral "currently doing" line with a readable input', () => { + // The agent's tool_input_preview is the input dict's Python repr, cut at a fixed length. + expect(sessionProgressActivity('agent_tool_call', { tool_name: 'Read', tool_input_preview: "{'file_path': '/workspace/t-1/src/app.ts'}" })) + .toEqual({ content: { type: 'action', action: 'Reading', parameter: '`src/app.ts`' }, ephemeral: true }); + expect(sessionProgressActivity('agent_tool_call', { tool_name: 'Bash', tool_input_preview: "{'command': 'cd /workspace/t-1; npm test', 'description'" })) + .toEqual({ content: { type: 'action', action: 'Running', parameter: '`npm test`' }, ephemeral: true }); + // repr switches a value to double quotes when it contains a single quote. + expect(sessionProgressActivity('agent_tool_call', { tool_name: 'Grep', tool_input_preview: "{'pattern': \"don't\"}" })?.content) + .toEqual({ type: 'action', action: 'Searching', parameter: "`don't`" }); + // An MCP or unknown tool is named, and its input is not guessed at. + expect(sessionProgressActivity('agent_tool_call', { tool_name: 'mcp__gateway__lookup', tool_input_preview: '{}' })?.content) + .toEqual({ type: 'action', action: 'Using mcp__gateway__lookup', parameter: '' }); + expect(sessionProgressActivity('agent_tool_call', {})).toBeNull(); + }); + + test("the agent's own message is a persistent thought; a turn without text is nothing", () => { + expect(sessionProgressActivity('agent_turn', { text_preview: ' I found the bug in the parser. ' })) + .toEqual({ content: { type: 'thought', body: 'I found the bug in the parser.' }, ephemeral: false }); + expect((sessionProgressActivity('agent_turn', { text_preview: 'x'.repeat(2000) })?.content as { body: string }).body).toHaveLength(600); + expect(sessionProgressActivity('agent_turn', { text_preview: ' ', thinking_preview: 'private' })).toBeNull(); + }); + + test('queueing is ephemeral and says how long the task has waited', () => { + expect(sessionProgressActivity('admission_queued', { reason: 'concurrency_limit' })?.content) + .toMatchObject({ type: 'thought', body: expect.stringMatching(/^Queued: /) }); + const still = sessionProgressActivity('admission_queued', { waited_s: 1800 }); + expect(still?.ephemeral).toBe(true); + expect((still?.content as { body: string }).body).toMatch(/^Still queued \(30 min so far\): /); + }); + + test('platform steps and agent milestones are persistent steps', () => { + expect(sessionProgressActivity('hydration_complete', {})).toEqual({ + content: { type: 'action', action: 'Gathered the issue context', parameter: '' }, ephemeral: false, + }); + expect(sessionProgressActivity('repo_setup_complete', { details: 'branch=bgagent/t-1/fix-parser build_before=pass' })?.content) + .toEqual({ type: 'action', action: 'Cloned the repository', parameter: 'on branch `bgagent/t-1/fix-parser`' }); + expect(sessionProgressActivity('attachments_downloaded', { details: 'count=2' })?.content) + .toEqual({ type: 'action', action: 'Read the issue attachments', parameter: '2 file(s)' }); + expect(sessionProgressActivity('nudge_acknowledged', {})?.content).toEqual({ type: 'thought', body: 'Picked up your message and working it in.' }); + expect(sessionProgressActivity('trajectory_uploaded', {})).toBeNull(); + }); + + test('activity ids are deterministic version-4 UUIDs (Linear rejects other versions)', () => { + const id = progressActivityId('evt-1'); + expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + expect(progressActivityId('evt-1')).toBe(id); + expect(progressActivityId('evt-2')).not.toBe(id); + }); +}); diff --git a/cdk/test/handlers/shared/microvm/lifecycle.test.ts b/cdk/test/handlers/shared/microvm/lifecycle.test.ts index 7cf55cc3c..be1e67fde 100644 --- a/cdk/test/handlers/shared/microvm/lifecycle.test.ts +++ b/cdk/test/handlers/shared/microvm/lifecycle.test.ts @@ -100,28 +100,31 @@ describe('MicroVM lifecycle policy', () => { deadlineMs: NOW + sharedConstants.approval_timeout_s.default * 1000, }, }); - test('default timing: a 300 s gate sleeps after 60 s and wakes 60 s before its deadline', () => { - expect(sharedConstants.approval_timeout_s.default).toBe(300); + test('default timing: a default gate sleeps after 60 s and wakes 60 s before its deadline', () => { + expect(sharedConstants.approval_timeout_s.default).toBe(1800); expect(sharedConstants.microvm_sleep_after_s.default).toBe(60); + const gateMs = sharedConstants.approval_timeout_s.default * 1000; const current = defaultGate(); expect(policy('RUNNING', { snapshot: current, nowMs: NOW + 59_000 })) .toMatchObject({ action: 'wait', reason: 'suspend-grace', nextPollInMs: 1000 }); expect(policy('RUNNING', { snapshot: current, nowMs: NOW + 60_000 })).toMatchObject({ action: 'suspend' }); // Once the suspend intent for this gate is recorded, it stays asleep until the - // wake margin before the ORIGINAL deadline (300 - 60 = 240 s). - const asleep = { ...current, intent: { ...intent(), deadline_ms: NOW + 300_000 } }; - expect(policy('SUSPENDED', { snapshot: asleep, nowMs: NOW + 239_000 })) + // wake margin before the ORIGINAL deadline (1800 - 60 = 1740 s). + const asleep = { ...current, intent: { ...intent(), deadline_ms: NOW + gateMs } }; + expect(policy('SUSPENDED', { snapshot: asleep, nowMs: NOW + gateMs - 61_000 })) .toMatchObject({ action: 'wait', reason: 'intentionally-suspended', nextPollInMs: 1000 }); - expect(policy('SUSPENDED', { snapshot: asleep, nowMs: NOW + 240_000 })) + expect(policy('SUSPENDED', { snapshot: asleep, nowMs: NOW + gateMs - 60_000 })) .toMatchObject({ action: 'resume', reason: 'wake-deadline' }); - expect(current.approval).toMatchObject({ deadlineMs: NOW + 300_000 }); + expect(current.approval).toMatchObject({ deadlineMs: NOW + gateMs }); }); - test('a 600 s sleep-after never suspends a default 300 s gate', () => { - const current = { ...defaultGate(), sleepAfterSeconds: 600 }; - for (const elapsed of [60_000, 200_000, 239_000]) { + + test('a sleep-after as long as the gate never suspends it', () => { + const gateS = sharedConstants.approval_timeout_s.default; + const current = { ...defaultGate(), sleepAfterSeconds: gateS }; + for (const elapsed of [60_000, (gateS / 2) * 1000, gateS * 1000 - 61_000]) { expect(policy('RUNNING', { snapshot: current, nowMs: NOW + elapsed })).toMatchObject({ action: 'wait' }); } - expect(policy('RUNNING', { snapshot: current, nowMs: NOW + 240_000 })) + expect(policy('RUNNING', { snapshot: current, nowMs: NOW + gateS * 1000 - 60_000 })) .toMatchObject({ action: 'resume', reason: 'wake-deadline' }); }); test.each([0, -1, NaN, Infinity, 0.5, 3601, '30', null])('off or malformed delay %s keeps awake and repairs existing sleep', value => { diff --git a/cdk/test/stacks/agent.test.ts b/cdk/test/stacks/agent.test.ts index 04ada8982..5ddba5aaf 100644 --- a/cdk/test/stacks/agent.test.ts +++ b/cdk/test/stacks/agent.test.ts @@ -1253,6 +1253,8 @@ describe('AgentStack', () => { 'TestAgentStack/AgentRegistryStack': [], 'TestAgentStack/RegistryApi': [], 'TestAgentStack/ConcurrencyMaintenance': Array(2).fill(notifiesTopic), + // On by default with Linear and AgentCore; the consent page has no alarms of its own. + 'TestAgentStack/LinearVaultConsentPageStack': [], }); }); @@ -2152,8 +2154,11 @@ describe('AgentStack solution attribution (#319): AWS_SDK_UA_APP_ID via stack-le // unnoticed; the exact count fails if a Lambda is dropped OR if a new one // is added without being attributed below. // 48 existing handlers (5 scheduled maintenance jobs nested) + 2 registry - // provisioning handlers + 4 registry API handlers in nested stacks. - expect(abcaLambdas.length).toBe(54); + // provisioning handlers + 4 registry API handlers in nested stacks, + 3 now + // that the Linear identity vault is on by default (its provider onEvent + // handler, the provider framework function and the consent page's function + // in its nested stack). + expect(abcaLambdas.length).toBe(57); // Every ABCA-authored Lambda must carry the canonical `#` app-id. Collect // any offenders so a failure names the exact logical id(s) that are naked. const unattributed = abcaLambdas @@ -2285,8 +2290,21 @@ describe('AgentStack tool-gateway gate (ADR-019 P1)', () => { }); describe('AgentStack Linear identity vault gate (#809)', () => { - test('default synth omits the vault: no workload identity, no token grant, no agent env', () => { - const app = new App(); + test('default synth (AgentCore) provisions the vault and its hosted consent page', () => { + const rendered = JSON.stringify(Template.fromStack(new AgentStack(new App(), 'LinearVaultDefaultStack', { + env: { account: '123456789012', region: 'us-east-1' }, + })).toJSON()); + expect(rendered).toContain('Custom::LinearWorkloadIdentity'); + expect(rendered).toContain('GetResourceOauth2Token'); + expect(rendered).toContain('LINEAR_WORKLOAD_IDENTITY_NAME'); + expect(rendered).toContain('LinearVaultConsentUrl'); + }); + + test.each([ + ['explicit opt-out', { enableLinearIdentityVault: 'false' }], + ['a deployment without AgentCore', { compute_types: 'ecs' }], + ])('%s omits the vault: no workload identity, no token grant, no agent env', (_label, context) => { + const app = new App({ context }); const stack = new AgentStack(app, 'LinearVaultOffStack', { env: { account: '123456789012', region: 'us-east-1' }, }); @@ -2299,6 +2317,12 @@ describe('AgentStack Linear identity vault gate (#809)', () => { expect(rendered).not.toContain('LinearVaultConsentUrl'); }); + test('an unrecognised flag value fails synth instead of silently choosing a store', () => { + expect(() => new AgentStack(new App({ context: { enableLinearIdentityVault: 'yes' } }), 'LinearVaultBadStack', { + env: { account: '123456789012', region: 'us-east-1' }, + })).toThrow('enableLinearIdentityVault must be true or false'); + }); + test('flag on: agent runtime role gets the token data-plane grant + the agent env is set', () => { const app = new App({ context: { enableLinearIdentityVault: true } }); const stack = new AgentStack(app, 'LinearVaultOnStack', { diff --git a/cdk/test/stacks/compute-selection.test.ts b/cdk/test/stacks/compute-selection.test.ts index 5b9291da3..bf89befc3 100644 --- a/cdk/test/stacks/compute-selection.test.ts +++ b/cdk/test/stacks/compute-selection.test.ts @@ -150,7 +150,11 @@ describe.each([ { label: 'legacy ECS', selector: { compute_type: 'ecs' }, backends: ['agentcore', 'ecs'] }, { label: 'ECS default with AgentCore', selector: { compute_types: ['ecs', 'agentcore'] }, backends: ['ecs', 'agentcore'] }, { label: 'MicroVM default without AgentCore', selector: { compute_types: 'lambda-microvm,ecs' }, backends: ['lambda-microvm', 'ecs'] }, - { label: 'all backends', selector: { compute_types: 'agentcore,ecs,lambda-microvm' }, backends: ['agentcore', 'ecs', 'lambda-microvm'] }, + // All three backends with the inline network is an expected census rejection + // (`additive-agentcore+ecs+lambda-microvm-default-inline`, over the 490 budget); + // pin the default-on vault off so this backend-wiring test stays under + // CloudFormation's 500-resource limit. The vault itself is covered in agent.test. + { label: 'all backends', selector: { compute_types: 'agentcore,ecs,lambda-microvm', enableLinearIdentityVault: 'false' }, backends: ['agentcore', 'ecs', 'lambda-microvm'] }, ])('additive deployment from $label', ({ selector, backends }) => { let template: Template; let stack: Stack; diff --git a/cli/src/commands/linear.ts b/cli/src/commands/linear.ts index 71b694ccb..95fe1784b 100644 --- a/cli/src/commands/linear.ts +++ b/cli/src/commands/linear.ts @@ -46,6 +46,7 @@ import { resolveStoredGrantFields, readExistingWebhookSecret, StoredLinearOauthToken, + describePreservedFallback, } from '../linear-oauth'; import { clearPendingConsent, @@ -338,8 +339,9 @@ export function renderLinearAppTemplate(opts: LinearAppTemplateOptions = {}): st ] : [ ` ${callbackUrl}`, - ' (loopback โ€” needs the browser on this machine; deploy with', - ' `--context enableLinearIdentityVault=true` for a hosted consent page)', + ' (loopback โ€” needs the browser on this machine; the Identity vault provides a', + ' hosted consent page: on by default with AgentCore, or', + ' `--context enableLinearIdentityVault=true`)', ]), '', ' Public: OFF', @@ -1230,7 +1232,8 @@ export function makeLinearCommand(): Command { ? ' `--code` resumes the Secrets Manager authorization-code flow. A vault workspace ' + 'finishes its consent in one run โ€” re-run without `--code`.' : ` The stack '${stackName}' publishes no LinearVaultConsentUrl, so its last deploy ` - + 'omitted `--context enableLinearIdentityVault=true`. Re-deploy with it, or move ' + + 'had no Identity vault (no AgentCore, or `--context enableLinearIdentityVault=false`). ' + + 'Re-deploy with `--context enableLinearIdentityVault=true`, or move ' + 'this workspace off the vault deliberately by deleting its registry row first.'), ); } @@ -1239,8 +1242,8 @@ export function makeLinearCommand(): Command { // availability, only this stack's outputs. Naming the real cause is what lets // an operator fix it, and the wrong cause sends them to the AWS region table. console.log( - ` Stack '${stackName}' has no Identity vault (deployed without ` - + '`--context enableLinearIdentityVault=true`) โ€” using Secrets Manager.', + ` Stack '${stackName}' has no Identity vault (deployed without AgentCore, or with ` + + '`--context enableLinearIdentityVault=false`) โ€” using Secrets Manager.', ); } @@ -1464,8 +1467,8 @@ export function makeLinearCommand(): Command { console.log(` Redirecting to: ${setupRedirectUri}`); console.log(' That exact URI must be one of the app\'s Redirect URIs, or consent'); console.log(' fails with "Invalid redirect_uri parameter for the application".'); - console.log(' No localhost on this machine? Deploy the consent page with'); - console.log(' `--context enableLinearIdentityVault=true`.\n'); + console.log(' No localhost on this machine? Re-deploy with'); + console.log(' `--context enableLinearIdentityVault=true` for the hosted consent page.\n'); } if (resumed || vaultAccessToken) { // nothing to open: consent already happened in the operator's browser. @@ -1625,7 +1628,7 @@ export function makeLinearCommand(): Command { console.log(` โœ“ (${secretName})`); // After the progress line closes, not during it. if (preservedTokens) { - console.log(' โœ“ Kept the existing Secrets Manager token as a fallback'); + console.log(` ${describePreservedFallback(preservedTokens).message}`); } console.log(suppliedWebhookSecret ? ' โœ“ Using the webhook signing secret you entered' @@ -2401,10 +2404,9 @@ export function makeLinearCommand(): Command { console.log(` ${i + 1}. ${m.name ?? m.id}${email}`); }); console.log(); - const pickRaw = (await promptLine(` Which one is the teammate? [1-${humans.length}]`)).trim(); - const pickIdx = parseInt(pickRaw, 10) - 1; - if (Number.isNaN(pickIdx) || pickIdx < 0 || pickIdx >= humans.length) { - throw new CliError(`Invalid selection '${pickRaw}'.`); + const pickIdx = await promptChoice(` Which one is the teammate? [1-${humans.length}]`, humans.length); + if (pickIdx === undefined) { + throw new CliError('No valid selection.'); } const picked = humans[pickIdx]; const pickedLabel = `${picked.name ?? picked.id}${picked.email ? ` (${picked.email})` : ''}`; @@ -2827,6 +2829,26 @@ export function makeLinearCommand(): Command { return requireDeployedFeature(linear, 'linear'); } +/** + * Ask for a 1-based choice, re-asking on an empty or invalid answer. A paste that + * ends in a newline followed by Enter leaves a stray line for the NEXT prompt; + * failing on it would silently skip the choice. Returns undefined after `attempts`. + */ +export async function promptChoice( + label: string, + count: number, + ask: (label: string) => Promise = promptLine, + attempts = 3, +): Promise { + for (let attempt = 0; attempt < attempts; attempt++) { + const raw = (await ask(label)).trim(); + const idx = /^\d+$/.test(raw) ? parseInt(raw, 10) - 1 : -1; + if (idx >= 0 && idx < count) return idx; + if (attempt < attempts - 1) process.stderr.write(raw ? ` '${raw}' is not between 1 and ${count}.\n` : ''); + } + return undefined; +} + // โ”€โ”€โ”€ Auto-link โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ interface LinearViewer { @@ -3039,10 +3061,9 @@ async function runSelfLinkPicker(args: { console.log(` ${i + 1}. ${m.name ?? m.id}${email}`); }); console.log(); - const pickRaw = (await promptLine(` Which one is you? [1-${humans.length}]`)).trim(); - const pickIdx = parseInt(pickRaw, 10) - 1; - if (Number.isNaN(pickIdx) || pickIdx < 0 || pickIdx >= humans.length) { - console.log(` โš  Invalid selection '${pickRaw}'; skipping self-link.`); + const pickIdx = await promptChoice(` Which one is you? [1-${humans.length}]`, humans.length); + if (pickIdx === undefined) { + console.log(' โš  No valid selection; skipping self-link.'); console.log(' Re-run setup or pick yourself later via the picker that fires on first failed trigger.'); return false; } diff --git a/cli/src/commands/submit.ts b/cli/src/commands/submit.ts index 78d406741..5cefddd69 100644 --- a/cli/src/commands/submit.ts +++ b/cli/src/commands/submit.ts @@ -88,7 +88,7 @@ export function makeSubmitCommand(): Command { .option( '--approval-timeout ', `Cedar HITL per-task default approval timeout (${APPROVAL_TIMEOUT_S_MIN}-${APPROVAL_TIMEOUT_S_MAX}s). ` - + 'Overrides the platform default of 300s. Per-rule @approval_timeout_s still min-wins at gate-firing.', + + 'Overrides the platform default of 1800s and the repo blueprint\'s. Per-rule @approval_timeout_s still min-wins at gate-firing.', parseInt, ) .option( diff --git a/cli/src/linear-oauth.ts b/cli/src/linear-oauth.ts index c9e37ce96..68122e586 100644 --- a/cli/src/linear-oauth.ts +++ b/cli/src/linear-oauth.ts @@ -503,3 +503,26 @@ export async function verifyLinearRefreshAndPersist(args: { } return 'refreshed'; } + +/** + * How setup should describe a Secrets-Manager token it kept when moving onto the + * vault. A refresh token cannot be checked without rotating it, so an expired + * access token is reported as unverified rather than as a working fallback: + * Linear rejects refresh tokens that went unused for too long. + */ +export function describePreservedFallback( + preserved: Pick, + now: Date = new Date(), +): { readonly usable: boolean; readonly message: string } { + const expiresAt = Date.parse(preserved.expires_at); + if (Number.isFinite(expiresAt) && expiresAt <= now.getTime()) { + return { + usable: false, + message: + `โš  Kept the existing Secrets Manager token, but its access token expired on ${preserved.expires_at}. ` + + 'It only works as a fallback if Linear still accepts its refresh token, which expires when ' + + 'unused. Treat the vault as the only verified credential for this workspace.', + }; + } + return { usable: true, message: 'โœ“ Kept the existing Secrets Manager token as a fallback' }; +} diff --git a/cli/src/repo-lookup.ts b/cli/src/repo-lookup.ts index bea54f324..8091ee096 100644 --- a/cli/src/repo-lookup.ts +++ b/cli/src/repo-lookup.ts @@ -44,6 +44,7 @@ export interface RepoConfigRow { readonly egress_allowlist?: string[]; readonly cedar_policies?: string[]; readonly approval_gate_cap?: number; + readonly approval_timeout_s?: number; } /** diff --git a/cli/src/repo-onboard.ts b/cli/src/repo-onboard.ts index 69747c6de..40d5a7dfd 100644 --- a/cli/src/repo-onboard.ts +++ b/cli/src/repo-onboard.ts @@ -121,7 +121,7 @@ export async function onboardRepo( } if (existing?.egress_allowlist?.length) item.egress_allowlist = existing.egress_allowlist; if (existing?.cedar_policies?.length) item.cedar_policies = existing.cedar_policies; - for (const key of ['approval_gate_cap', 'max_budget_usd', 'memory_token_budget'] as const) { + for (const key of ['approval_gate_cap', 'approval_timeout_s', 'max_budget_usd', 'memory_token_budget'] as const) { if (existing?.[key] !== undefined) item[key] = existing[key]; } diff --git a/cli/test/commands/linear.test.ts b/cli/test/commands/linear.test.ts index b2a29d430..89080da7e 100644 --- a/cli/test/commands/linear.test.ts +++ b/cli/test/commands/linear.test.ts @@ -25,6 +25,7 @@ import { readStackWideWebhookSecret, queryLinearTeamKeys, parsePastedAuthorization, + promptChoice, renderLinearAppTemplate, } from '../../src/commands/linear'; import { generateInviteCode, INVITE_CODE_ALPHABET } from '../../src/invite-code'; @@ -818,3 +819,26 @@ describe('parsePastedAuthorization', () => { expect(parsePastedAuthorization('code=abc123&state=')).toEqual({ code: 'abc123' }); }); }); + +describe('promptChoice', () => { + const answers = (...values: string[]) => { + const queue = [...values]; + return jest.fn(async () => queue.shift() ?? ''); + }; + + test('re-asks after a stray empty line left by a pasted newline', async () => { + const ask = answers('', '2'); + expect(await promptChoice('Which one is you?', 2, ask)).toBe(1); + expect(ask).toHaveBeenCalledTimes(2); + }); + + test('re-asks on out-of-range or non-numeric answers', async () => { + expect(await promptChoice('Pick', 3, answers('9', 'x2', '3'))).toBe(2); + }); + + test('gives up after the attempt budget instead of looping forever', async () => { + const ask = answers('', '', ''); + expect(await promptChoice('Pick', 2, ask)).toBeUndefined(); + expect(ask).toHaveBeenCalledTimes(3); + }); +}); diff --git a/cli/test/commands/repo-onboard.test.ts b/cli/test/commands/repo-onboard.test.ts index 5e960bd5e..591d140d3 100644 --- a/cli/test/commands/repo-onboard.test.ts +++ b/cli/test/commands/repo-onboard.test.ts @@ -200,6 +200,7 @@ describe('repo onboard/offboard', () => { egress_allowlist: ['example.com'], cedar_policies: ['policy'], approval_gate_cap: 10, + approval_timeout_s: 2700, max_budget_usd: 5, memory_token_budget: 4000, }); @@ -210,14 +211,16 @@ describe('repo onboard/offboard', () => { expect(put.input.Item?.onboarded_at).toBe('2025-01-01T00:00:00Z'); expect(put.input.Item?.cedar_policies).toEqual(['policy']); // Blueprint-only settings have no flag here: a re-onboard must not drop them. - expect(put.input.Item).toMatchObject({ approval_gate_cap: 10, max_budget_usd: 5, memory_token_budget: 4000 }); + expect(put.input.Item).toMatchObject({ + approval_gate_cap: 10, approval_timeout_s: 2700, max_budget_usd: 5, memory_token_budget: 4000, + }); }); test('onboardRepo writes no Blueprint-only setting the existing row does not have', async () => { await onboardRepo('us-east-1', 'RepoTable', 'acme/a'); const put = ddbSend.mock.calls[0][0] as PutCommand; - for (const key of ['approval_gate_cap', 'max_budget_usd', 'memory_token_budget']) { + for (const key of ['approval_gate_cap', 'approval_timeout_s', 'max_budget_usd', 'memory_token_budget']) { expect(put.input.Item).not.toHaveProperty(key); } }); diff --git a/cli/test/linear-oauth.test.ts b/cli/test/linear-oauth.test.ts index 347477e84..4a5729017 100644 --- a/cli/test/linear-oauth.test.ts +++ b/cli/test/linear-oauth.test.ts @@ -21,6 +21,7 @@ import { CliError } from '../src/errors'; import { buildAuthorizationUrl, computeExpiresAt, + describePreservedFallback, exchangeAuthorizationCode, generatePkce, LINEAR_AUTHORIZE_ENDPOINT, @@ -601,3 +602,20 @@ describe('resolveStoredGrantFields โ€” a preserved grant must never be overwritt }); }); }); + +describe('describePreservedFallback', () => { + const now = new Date('2026-11-05T00:00:00Z'); + + test('an expired access token is reported as an unverified fallback, not a working one', () => { + const result = describePreservedFallback({ expires_at: '2026-07-29T10:09:20.000Z' }, now); + expect(result.usable).toBe(false); + expect(result.message).toContain('expired on 2026-07-29T10:09:20.000Z'); + expect(result.message).not.toContain('โœ“'); + }); + + test('a live access token is kept as a fallback', () => { + expect(describePreservedFallback({ expires_at: '2026-11-06T00:00:00Z' }, now)).toEqual({ + usable: true, message: 'โœ“ Kept the existing Secrets Manager token as a fallback', + }); + }); +}); diff --git a/contracts/constants.json b/contracts/constants.json index 5ebd494ff..e9f0aa1c2 100644 --- a/contracts/constants.json +++ b/contracts/constants.json @@ -7,7 +7,7 @@ "approval_timeout_s": { "min": 30, "max": 3600, - "default": 300 + "default": 1800 }, "microvm_sleep_after_s": { "min": 0, diff --git a/contracts/constants.md b/contracts/constants.md index 8ec8e0c78..9c7f8e479 100644 --- a/contracts/constants.md +++ b/contracts/constants.md @@ -104,7 +104,9 @@ JSON at TypeScript compile time via `resolveJsonModule`. before the `maxLifetime - 300` clip is applied (ยง7.3). 3600 seconds (1 hour). - **`approval_timeout_s.default`** โ€” value applied when the submit payload - omits `approval_timeout_s`. 300 seconds (5 minutes) per ยง6 decision #6. + omits `approval_timeout_s` and the repo's blueprint sets no + `security.approvalTimeoutSeconds`. 1800 seconds (30 minutes): long enough for + someone away from the session to answer. Was 300 s (ยง6 decision #6). - **`max_budget_usd.min`** โ€” floor for a task's `max_budget_usd` (1 cent). Validated server-side (`validation.ts`) and pre-validated by `bgagent submit --max-budget` (#258). @@ -198,9 +200,9 @@ fails the drift check *and* the image build. The coordinator suspends only images whose launched version declares this protocol. - **`microvm_sleep_after_s`** โ€” per-task approval-wait delay before MicroVM sleep (`min` 0 = off, `max` 3,600, `default` 60). The default is chosen against - `approval_timeout_s.default` (300 s): the supervisor wakes 60 s before the + `approval_timeout_s.default` (1800 s): the supervisor wakes 60 s before the deadline and never suspends for less than 30 s, so a default gate sleeps from - 60 s to 240 s. + 60 s to 1740 s. The published CLI package contains only `lib/`, so it cannot load the repository contract at runtime. It mirrors these values as literals and diff --git a/contracts/coverage-thresholds.json b/contracts/coverage-thresholds.json index 4cbf51001..9dfd116a0 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/contracts/secret-scan-vectors.json b/contracts/secret-scan-vectors.json index a22129026..f916d7cd7 100644 --- a/contracts/secret-scan-vectors.json +++ b/contracts/secret-scan-vectors.json @@ -185,6 +185,11 @@ "input": "redis://:@localhost:6379/0", "expected": "redis://:@localhost:6379/0", "note": "an empty user and an empty password" + }, + { + "input": "Linear said: token lin_oauth_EXAMPLE0EXAMPLE0EX is invalid", + "expected": "Linear said: token [REDACTED-LINEAR_TOKEN] is invalid", + "note": "a Linear OAuth access token" } ] } diff --git a/docs/decisions/ADR-016-pluggable-identity-and-auth.md b/docs/decisions/ADR-016-pluggable-identity-and-auth.md index 7deb17fe5..ff3b16ba2 100644 --- a/docs/decisions/ADR-016-pluggable-identity-and-auth.md +++ b/docs/decisions/ADR-016-pluggable-identity-and-auth.md @@ -9,8 +9,11 @@ > **2026-08-28 implementation note โ€” Phase 1 (Linear `ChannelCredential`) is built and live-verified > on a dev stack** ([#809](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/809)). -> Additive and context-gated (`enableLinearIdentityVault`, default off), with Secrets Manager retained -> as the fallback, so a deployment that does not opt in is byte-for-byte unchanged. The decision below +> Additive and context-gated (`enableLinearIdentityVault`), with Secrets Manager retained +> as the fallback. **Update:** the gate now defaults ON wherever AgentCore is deployed (which proves +> the region has AgentCore) and OFF otherwise; `enableLinearIdentityVault=true|false` overrides. +> Motivation: a Secrets Manager workspace left unused let its refresh token expire, failing every +> Linear trigger silently until a browser re-consent through the CLI's localhost callback. The decision below > stands; two implementation details deviate from the P1 text and are recorded in *Phasing* โ†’ P1. ## Context diff --git a/docs/design/CEDAR_HITL_GATES.md b/docs/design/CEDAR_HITL_GATES.md index 7c75fbe5d..2483d3920 100644 --- a/docs/design/CEDAR_HITL_GATES.md +++ b/docs/design/CEDAR_HITL_GATES.md @@ -388,6 +388,7 @@ security: - write_infrastructure # example: repo has its own stricter rule maxPreApprovalScope: "tool_type_session" # optional; caps what --pre-approve can grant approvalGateCap: 50 # optional; per-task lifetime cap on gates (1 โ‰ค N โ‰ค 500, default 50). See ยง3 decision #13. + approvalTimeoutSeconds: 1800 # optional; how long a person has to answer a request on this repo's tasks (30 โ‰ค N โ‰ค 3600, default 1800). A task's own approval_timeout_s wins. ``` **`approvalGateCap` sizing guidance:** @@ -482,7 +483,7 @@ forbid (principal, action == Agent::Action::"execute_bash", resource) || context.command like "*git push origin release/*" }; ``` -A force-push to any branch needs approval in 300s. A force-push to `main` or `prod` gives the user 600s with elevated severity. A non-force push to a protected branch (`main`/`prod`/`master`/`release/*`) also gates โ€” catches the case where an agent directly pushes rather than opening a PR. If a command matches both `force_push_any` and `force_push_main`, multi-match merging picks `min(300, 600) = 300s` and `max(medium, high) = high`. +A force-push to any branch needs approval within the task's approval window (30 minutes by default). A force-push to `main` or `prod` raises the severity. A non-force push to a protected branch (`main`/`prod`/`master`/`release/*`) also gates โ€” catches the case where an agent directly pushes rather than opening a PR. If a command matches both `force_push_any` and `force_push_main`, multi-match merging picks `min(300, 600) = 300s` and `max(medium, high) = high`. **Protect sensitive file paths** (soft-deny โ€” part of the built-in starter set): ```cedar @@ -2231,11 +2232,13 @@ Built-in policies shipped with the agent: **Hard-deny (absolute, cannot be disabled by blueprint)**: `rm_slash`, `write_git_internals`, `write_git_internals_nested`, `drop_table`. Absolute; no scope bypasses them; blueprint `disable:` cannot remove them (ยง5.1, finding #9). **Soft-deny starter set (require approval by default, may be disabled by blueprint)**: -- `force_push_any` โ€” `like "*git push --force*"` โ€” medium, 300s -- `push_to_protected_branch` โ€” pushes to `main`/`master`/`prod`/`release/*` (non-force) โ€” medium, 300s -- `force_push_main` โ€” force-push specifically to `main`/`prod` โ€” high, 600s -- `write_env_files` โ€” `like "*.env"` โ€” high, 600s -- `write_credentials` โ€” `like "*credentials*"` โ€” high, 300s +- `force_push_any` โ€” `like "*git push --force*"` โ€” medium, 3600s +- `push_to_protected_branch` โ€” pushes to `main`/`master`/`prod`/`release/*` (non-force) โ€” medium, 3600s +- `force_push_main` โ€” force-push specifically to `main`/`prod` โ€” high, 3600s +- `write_env_files` โ€” `like "*.env"` โ€” high, 3600s +- `write_credentials` โ€” `like "*credentials*"` โ€” high, 3600s + +Each built-in rule allows the 3600s maximum, so the task's window decides: 1800s by default, set per repo with the blueprint's `security.approvalTimeoutSeconds` or per task with `approval_timeout_s`. (Before #1066 the rules were 300s / 600s and the default 300s, which gave a person five minutes.) Users who want fully autonomous execution (no approval gates) pass `--pre-approve all_session --yes` at submit. Repos that want additional gates add them via `Blueprint.security.cedarPolicies.soft`. Repos that want a different policy set can override specific built-in **soft-deny** rules by `@rule_id` via the blueprint's `security.cedarPolicies.disable` list. The `disable:` mechanism is restricted: it may NOT include any built-in hard-deny rule_id, and the blueprint loader rejects such configurations at task start. diff --git a/docs/design/COMPUTE.md b/docs/design/COMPUTE.md index 79a8c6797..0eba180e0 100644 --- a/docs/design/COMPUTE.md +++ b/docs/design/COMPUTE.md @@ -121,7 +121,7 @@ Because a snapshot freezes its build-time environment, deployment-specific, non- Networking separates image build from execution: the build-only connector permits TCP 80 and 443 because the Dockerfile uses `apt-get`, while running MicroVMs retain 443-only egress through the platform VPC. Every launch explicitly passes the Lambda-managed `NO_INGRESS` connector; omission would select the service's public-ingress default. The P2 image declares and serves `/ready` and `/validate` at build time and `/run` and `/terminate` at runtime. The P3 image also serves `/suspend` and `/resume`. -**Approval-wait sleep (P3).** While a task waits for a human decision, the orchestrator can suspend its MicroVM: compute billing stops and memory and disk are preserved. It suspends only when the deployment enables `microvm_approval_suspend_enabled`, the live Parameter Store switch is on, the launched image version declares the lifecycle protocol, and enough of the gate remains after the task's `microvm_sleep_after_s` delay (default 60 s). It resumes inline when the decision is recorded, with the orchestrator poll as a backstop, and always 60 s before the original deadline. Approval windows stay bounded (300 s default, 3,600 s ceiling), so a suspended worker never outlives its gate. The guest declines an unsafe suspend with HTTP 200 because any other answer makes the service terminate the VM. See [ADR-021 P3 as delivered](../decisions/ADR-021-lambda-microvms-compute-backend.md#p3-as-delivered). +**Approval-wait sleep (P3).** While a task waits for a human decision, the orchestrator can suspend its MicroVM: compute billing stops and memory and disk are preserved. It suspends only when the deployment enables `microvm_approval_suspend_enabled`, the live Parameter Store switch is on, the launched image version declares the lifecycle protocol, and enough of the gate remains after the task's `microvm_sleep_after_s` delay (default 60 s). It resumes inline when the decision is recorded, with the orchestrator poll as a backstop, and always 60 s before the original deadline. Approval windows stay bounded (1,800 s default, 3,600 s ceiling), so a suspended worker never outlives its gate. The guest declines an unsafe suspend with HTTP 200 because any other answer makes the service terminate the VM. See [ADR-021 P3 as delivered](../decisions/ADR-021-lambda-microvms-compute-backend.md#p3-as-delivered). New MicroVM deployments place these resources in a nested stack (`--context microvm_nested_stack=true`, bootstrap 1.9.0 or later); existing flat installations keep `false` until migrated. diff --git a/docs/guides/LINEAR_SETUP_GUIDE.md b/docs/guides/LINEAR_SETUP_GUIDE.md index 726e9632a..964327911 100644 --- a/docs/guides/LINEAR_SETUP_GUIDE.md +++ b/docs/guides/LINEAR_SETUP_GUIDE.md @@ -21,8 +21,12 @@ One of two places, chosen automatically at setup time: | | When it's used | What's stored | |---|---|---| -| **AgentCore Identity vault** | The stack was deployed with `--context enableLinearIdentityVault=true` | Nothing long-lived. AgentCore holds the refresh token and mints short-lived access tokens on demand. | -| **Secrets Manager** | Otherwise โ€” including regions where AgentCore Identity isn't available | An OAuth token bundle in `bgagent-linear-oauth-`, refreshed and rotated by ABCA. | +| **AgentCore Identity vault** | **Default** whenever the stack deploys AgentCore (the standard deployment). A deployment without AgentCore (for example `compute_types=ecs`) can opt in with `--context enableLinearIdentityVault=true`, provided its region has AgentCore Identity | Nothing long-lived. AgentCore holds the refresh token and mints short-lived access tokens on demand. | +| **Secrets Manager** | Deployments without AgentCore, or `--context enableLinearIdentityVault=false` | An OAuth token bundle in `bgagent-linear-oauth-`, refreshed and rotated by ABCA only when ABCA uses Linear. | + +Prefer the vault. With Secrets Manager, a workspace that ABCA does not use for long enough can be left with an expired refresh token, and re-authorizing needs a browser that can reach the CLI's `localhost` callback. The vault's hosted consent page works from any machine. + +Existing vault deployments keep their resources and logical IDs, so turning the default on changes nothing for them. A Secrets Manager workspace on a stack that now has the vault keeps working until you re-run `bgagent linear setup `, which moves it to the vault. The vault can be configured with any selected backend. Lambda MicroVMs remains experimental; its image must include the current shared configuration contract. @@ -155,6 +159,17 @@ Apply the trigger label to an issue in that project. Within ~30 seconds the agen - **Check status** โ€” the issue's progress comments, or `bgagent list` / `bgagent status `. - **Cancel** โ€” `bgagent cancel `. Removing the label does *not* cancel a running task. +### Approval gates + +When a task on a Linear issue hits a [Cedar approval gate](../design/CEDAR_HITL_GATES.md), ABCA posts an **approval notice** on the issue: what the agent wants to run, why it is gated, and its decision deadline. When the gate resolves (approved, denied, timed out, or stranded), it posts one **outcome** comment. Each request gets exactly one notice and one outcome, even if events are redelivered. + +To decide from Linear, **reply to the notice comment** while signed in as the task owner: + +- `approve` โ€” approves this one action (the same as `bgagent approve ` with the default `this_call` scope). +- `deny` or `deny ` โ€” denies it, and passes the reason to the agent. `deny: ` and `deny - ` also work. + +ABCA acknowledges the decision in the same thread. Only the Linear user linked to the task's owner (through [inviting teammates](#inviting-teammates)) can decide. A reply from anyone else, or to a request that has already been decided or has expired, gets a short explanation in the thread and changes nothing. Replies from bots and apps, replies whose text no longer matches what Linear holds (for example, edited before ABCA read them), and any other comments in the thread are ignored. Broader scopes (`--scope`) are available only through the CLI and API. + ### Trigger labels | Label | What it does | Use it when | @@ -231,11 +246,15 @@ If you do these the other way round, every mention in the meantime opens a sessi | You do in Linear | ABCA does | |---|---| | @-mention bgagent on an issue, or delegate the issue to it | Acknowledges within seconds with a *thought*, then starts a coding task on the project's mapped repo. If the issue already has an ABCA pull request and your mention carries an instruction, it iterates on that PR instead. The session shows **Started coding task** or **Iterating on pull request**. | +| โ€” the task runs | Keeps the session's checklist current: *Understand the ticket*, *Set up the repository*, *Write the code*, *Open the pull request*, *Ready for your review* (an update to an existing PR has its own wording). The checklist only moves forward. | +| โ€” the agent works | Shows what it's doing right now as one line that the next one replaces ("Reading `src/app.ts`", "Running `npm test`"), the agent's own messages, and its setup steps (issue context gathered, repository cloned, your nudge picked up). At most 30 lasting entries per task; the one-line updates don't count. | | โ€” the agent opens a PR | Attaches the pull request to the session header and posts an **Opened pull request** action. | | โ€” a long run is in progress | Posts a short-lived "Still working" thought at most every 10 minutes, so the session never goes stale (Linear's idle limit is 30 minutes). | -| โ€” the task finishes | Posts one final activity carrying the same outcome, cost, turns and duration as the comment channel: a *response* on success, an *elicitation* if the run stopped to ask you a question, an *error* on failure. Linear turns it into the thread comment. | -| โ€” you're at your concurrency limit | Posts a "Queued" thought in the session. The task starts on its own when a slot frees up. | +| โ€” the task finishes | Posts one final activity carrying the same outcome, cost, turns and duration as the comment channel: a *response* on success, an *elicitation* if the run stopped to ask you a question, an *error* on failure. Its last line says whether you need to do anything. Linear turns it into the thread comment. A task that ends with a pull request moves the issue to *In Review*. | +| โ€” the agent hits an approval gate | Posts the request with **Approve** / **Deny** buttons and the time by which it is denied if nobody answers (30 minutes by default; see `security.approvalTimeoutSeconds`). Choose one, or reply `deny `. When the request matched a single rule there is also **Approve for this task**, so the agent doesn't ask again for that rule during the task. Only the task owner can decide; anyone else, or any other reply, gets the choice again. A decision made elsewhere (`bgagent approve`, a comment reply) or a timeout shows up as a note. | +| โ€” you're at your concurrency limit | Posts a "Queued" thought in the session, and "Still queued (N min so far)" every 15 minutes. The task starts on its own when a slot frees up. | | Reply inside the session while the task runs | Your message goes to the running agent as a nudge (the same guardrail screening, 2,000-character cap and per-minute limit as `bgagent nudge`). The agent picks it up at its next step. Only the task's owner can steer it. | +| Reply `approve` or `deny` when nothing is waiting | Says nothing is waiting and starts nothing, so a late answer after a timeout can't start new work. | | Reply after the task has finished | Starts a follow-up task. If the run stopped to ask a question, your reply resumes the original request with the answer. Otherwise it's a PR iteration if a PR exists, or new work from your message plus the issue. | | Click **Stop** in the session | Cancels the running task and shuts its agent down, like `bgagent cancel`, then confirms with a final response. Only the task's owner can stop it. | @@ -245,9 +264,9 @@ If you do these the other way round, every mention in the meantime opens a sessi **Who can act.** Every session request, `stop` included, needs a linked ABCA user ([Inviting teammates](#inviting-teammates)). An unlinked user is told to link their account and nothing runs. A refusal closes the session it was made in, unless that is the session a running task reports into; there it's a note, so someone else's run isn't marked finished or failed. A new task is attributed to whoever asked for it. Steering or stopping a *running* task follows the API's rule: only its owner can do it. -**Reactions.** A session task gets no ๐Ÿ‘€/โœ…/โŒ reactions on the issue, since the session shows that state. The issue still moves to *In Progress* and *In Review*. +**Reactions.** A session task gets no ๐Ÿ‘€/โœ…/โŒ reactions on the issue, since the session shows that state. The issue still moves to *In Progress* when work starts, and to *In Review* when the task ends with a pull request. -**Not yet supported in sessions:** image and file attachments from the issue description (use a label trigger for those), and Linear's *plan* checklist. +**Not yet supported in sessions:** image and file attachments from the issue description (use a label trigger for those). ## Adding another workspace @@ -331,6 +350,18 @@ If the app has been edited repeatedly through failed saves, creating a fresh app - Is the label spelled as configured? Matching is case-insensitive but must be the same word. - Check CloudWatch for `WebhookFn` and `WebhookProcessorFn`. Common: `Invalid Linear webhook signature`, `Linear workspace is not onboarded`, `Linear project is not onboarded`, `Linear actor has no linked platform user`. +### Linear stops responding and an "authorization revoked" alert arrives + +ABCA probes every registered workspace's grant every 12 hours, as well as whenever an event needs a token. The probe refreshes tokens that are about to expire, which keeps a grant alive even when nobody uses Linear for a while. If Linear rejects a grant, the workspace is marked `revoked` and one alert goes to the **OperationalAlerts** SNS topic (stack output `OperationalAlertsTopicArn`). Subscribe an email or chat endpoint to it, or deploy with `-c alertEmail=โ€ฆ`, because it ships with no subscribers. + +To recover, re-authorize the workspace: + +```bash +bgagent linear setup +``` + +The probe's summary is in the `WebhookProcessorFn` logs ("Linear grant health probe"), listing any workspace without a usable token. + ### Webhook signature verification fails repeatedly The stored signing secret doesn't match the subscription Linear is sending from โ€” usually because the webhook was configured in Linear without telling ABCA, or the secret was rotated: diff --git a/docs/guides/USER_GUIDE.md b/docs/guides/USER_GUIDE.md index 678168d05..77c77c3d1 100644 --- a/docs/guides/USER_GUIDE.md +++ b/docs/guides/USER_GUIDE.md @@ -668,7 +668,7 @@ Created: 2026-04-01T00:39:51.271Z | `--max-budget` | Maximum cost budget in USD (0.01โ€“100). Overrides per-repo Blueprint default. No default limit. | | `--idempotency-key` | Idempotency key for deduplication. | | `--trace` | Enable detailed tracing: raises progress preview cap to 4 KB and uploads full NDJSON trajectory to S3 on completion. Download with `bgagent trace download`. | -| `--approval-timeout` | Cedar HITL per-task approval timeout in seconds (default 300). A matching rule with its own `@approval_timeout_s` annotation still takes the minimum. See [Approval gates](#approval-gates-cedar-hitl). | +| `--approval-timeout` | Cedar HITL per-task approval timeout in seconds (default 1800, or the repo blueprint's `security.approvalTimeoutSeconds`). A matching rule with its own `@approval_timeout_s` annotation still takes the minimum. See [Approval gates](#approval-gates-cedar-hitl). | | `--microvm-sleep-after` | Seconds to wait for approval before putting a Lambda MicroVM to sleep (default 60; 0โ€“3600 accepted). Use `off` to keep it awake. Requires the deployment's automatic-sleep feature to be enabled; does not change approval deadlines or affect other compute backends. | | `--pre-approve` | Cedar HITL scope to approve up-front (repeatable). Scope forms: `all_session`, `tool_type:`, `tool_group:`, `bash_pattern:`, `write_path:`, `rule:`. Hard-deny rules are always enforced. | | `--wait` | Poll until the task reaches a terminal status. | @@ -905,7 +905,7 @@ When a rule marked `@tier("soft")` matches a tool call: 1. The agent stops before invoking the tool. 2. A row is atomically written to the approvals table and the task status flips to `AWAITING_APPROVAL`. 3. A progress event (`approval_requested`) is emitted so `bgagent watch` shows the gate in real time. -4. The task waits for your decision up to the rule's timeout (default 300 s, configurable per-rule and per-task). +4. The task waits for your decision up to the approval window (default 30 minutes; configurable per repo with the blueprint's `security.approvalTimeoutSeconds`, per task, and per rule, up to 1 hour). 5. On approval, the agent proceeds; on denial, the deny reason is best-effort injected back into the agent's context so it can adapt; on timeout, the gate is treated as a denial with `timed_out` as the reason. A decision is recorded at most once per request. Replaying approve/deny on the same `(task_id, request_id)` is idempotent. diff --git a/docs/src/content/docs/architecture/Cedar-hitl-gates.md b/docs/src/content/docs/architecture/Cedar-hitl-gates.md index be074348d..4133f6223 100644 --- a/docs/src/content/docs/architecture/Cedar-hitl-gates.md +++ b/docs/src/content/docs/architecture/Cedar-hitl-gates.md @@ -390,6 +390,7 @@ security: - write_infrastructure # example: repo has its own stricter rule maxPreApprovalScope: "tool_type_session" # optional; caps what --pre-approve can grant approvalGateCap: 50 # optional; per-task lifetime cap on gates (1 โ‰ค N โ‰ค 500, default 50). See ยง3 decision #13. + approvalTimeoutSeconds: 1800 # optional; how long a person has to answer a request on this repo's tasks (30 โ‰ค N โ‰ค 3600, default 1800). A task's own approval_timeout_s wins. ``` **`approvalGateCap` sizing guidance:** @@ -484,7 +485,7 @@ forbid (principal, action == Agent::Action::"execute_bash", resource) || context.command like "*git push origin release/*" }; ``` -A force-push to any branch needs approval in 300s. A force-push to `main` or `prod` gives the user 600s with elevated severity. A non-force push to a protected branch (`main`/`prod`/`master`/`release/*`) also gates โ€” catches the case where an agent directly pushes rather than opening a PR. If a command matches both `force_push_any` and `force_push_main`, multi-match merging picks `min(300, 600) = 300s` and `max(medium, high) = high`. +A force-push to any branch needs approval within the task's approval window (30 minutes by default). A force-push to `main` or `prod` raises the severity. A non-force push to a protected branch (`main`/`prod`/`master`/`release/*`) also gates โ€” catches the case where an agent directly pushes rather than opening a PR. If a command matches both `force_push_any` and `force_push_main`, multi-match merging picks `min(300, 600) = 300s` and `max(medium, high) = high`. **Protect sensitive file paths** (soft-deny โ€” part of the built-in starter set): ```cedar @@ -2233,11 +2234,13 @@ Built-in policies shipped with the agent: **Hard-deny (absolute, cannot be disabled by blueprint)**: `rm_slash`, `write_git_internals`, `write_git_internals_nested`, `drop_table`. Absolute; no scope bypasses them; blueprint `disable:` cannot remove them (ยง5.1, finding #9). **Soft-deny starter set (require approval by default, may be disabled by blueprint)**: -- `force_push_any` โ€” `like "*git push --force*"` โ€” medium, 300s -- `push_to_protected_branch` โ€” pushes to `main`/`master`/`prod`/`release/*` (non-force) โ€” medium, 300s -- `force_push_main` โ€” force-push specifically to `main`/`prod` โ€” high, 600s -- `write_env_files` โ€” `like "*.env"` โ€” high, 600s -- `write_credentials` โ€” `like "*credentials*"` โ€” high, 300s +- `force_push_any` โ€” `like "*git push --force*"` โ€” medium, 3600s +- `push_to_protected_branch` โ€” pushes to `main`/`master`/`prod`/`release/*` (non-force) โ€” medium, 3600s +- `force_push_main` โ€” force-push specifically to `main`/`prod` โ€” high, 3600s +- `write_env_files` โ€” `like "*.env"` โ€” high, 3600s +- `write_credentials` โ€” `like "*credentials*"` โ€” high, 3600s + +Each built-in rule allows the 3600s maximum, so the task's window decides: 1800s by default, set per repo with the blueprint's `security.approvalTimeoutSeconds` or per task with `approval_timeout_s`. (Before #1066 the rules were 300s / 600s and the default 300s, which gave a person five minutes.) Users who want fully autonomous execution (no approval gates) pass `--pre-approve all_session --yes` at submit. Repos that want additional gates add them via `Blueprint.security.cedarPolicies.soft`. Repos that want a different policy set can override specific built-in **soft-deny** rules by `@rule_id` via the blueprint's `security.cedarPolicies.disable` list. The `disable:` mechanism is restricted: it may NOT include any built-in hard-deny rule_id, and the blueprint loader rejects such configurations at task start. diff --git a/docs/src/content/docs/architecture/Compute.md b/docs/src/content/docs/architecture/Compute.md index 62296be74..55b3c3ca5 100644 --- a/docs/src/content/docs/architecture/Compute.md +++ b/docs/src/content/docs/architecture/Compute.md @@ -123,7 +123,7 @@ Because a snapshot freezes its build-time environment, deployment-specific, non- Networking separates image build from execution: the build-only connector permits TCP 80 and 443 because the Dockerfile uses `apt-get`, while running MicroVMs retain 443-only egress through the platform VPC. Every launch explicitly passes the Lambda-managed `NO_INGRESS` connector; omission would select the service's public-ingress default. The P2 image declares and serves `/ready` and `/validate` at build time and `/run` and `/terminate` at runtime. The P3 image also serves `/suspend` and `/resume`. -**Approval-wait sleep (P3).** While a task waits for a human decision, the orchestrator can suspend its MicroVM: compute billing stops and memory and disk are preserved. It suspends only when the deployment enables `microvm_approval_suspend_enabled`, the live Parameter Store switch is on, the launched image version declares the lifecycle protocol, and enough of the gate remains after the task's `microvm_sleep_after_s` delay (default 60 s). It resumes inline when the decision is recorded, with the orchestrator poll as a backstop, and always 60 s before the original deadline. Approval windows stay bounded (300 s default, 3,600 s ceiling), so a suspended worker never outlives its gate. The guest declines an unsafe suspend with HTTP 200 because any other answer makes the service terminate the VM. See [ADR-021 P3 as delivered](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend#p3-as-delivered). +**Approval-wait sleep (P3).** While a task waits for a human decision, the orchestrator can suspend its MicroVM: compute billing stops and memory and disk are preserved. It suspends only when the deployment enables `microvm_approval_suspend_enabled`, the live Parameter Store switch is on, the launched image version declares the lifecycle protocol, and enough of the gate remains after the task's `microvm_sleep_after_s` delay (default 60 s). It resumes inline when the decision is recorded, with the orchestrator poll as a backstop, and always 60 s before the original deadline. Approval windows stay bounded (1,800 s default, 3,600 s ceiling), so a suspended worker never outlives its gate. The guest declines an unsafe suspend with HTTP 200 because any other answer makes the service terminate the VM. See [ADR-021 P3 as delivered](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend#p3-as-delivered). New MicroVM deployments place these resources in a nested stack (`--context microvm_nested_stack=true`, bootstrap 1.9.0 or later); existing flat installations keep `false` until migrated. diff --git a/docs/src/content/docs/decisions/Adr-016-pluggable-identity-and-auth.md b/docs/src/content/docs/decisions/Adr-016-pluggable-identity-and-auth.md index 690838cd2..33bbaf1bd 100644 --- a/docs/src/content/docs/decisions/Adr-016-pluggable-identity-and-auth.md +++ b/docs/src/content/docs/decisions/Adr-016-pluggable-identity-and-auth.md @@ -11,8 +11,11 @@ title: "ADR-016: Pluggable identity and authentication" > **2026-08-28 implementation note โ€” Phase 1 (Linear `ChannelCredential`) is built and live-verified > on a dev stack** ([#809](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/809)). -> Additive and context-gated (`enableLinearIdentityVault`, default off), with Secrets Manager retained -> as the fallback, so a deployment that does not opt in is byte-for-byte unchanged. The decision below +> Additive and context-gated (`enableLinearIdentityVault`), with Secrets Manager retained +> as the fallback. **Update:** the gate now defaults ON wherever AgentCore is deployed (which proves +> the region has AgentCore) and OFF otherwise; `enableLinearIdentityVault=true|false` overrides. +> Motivation: a Secrets Manager workspace left unused let its refresh token expire, failing every +> Linear trigger silently until a browser re-consent through the CLI's localhost callback. The decision below > stands; two implementation details deviate from the P1 text and are recorded in *Phasing* โ†’ P1. ## Context diff --git a/docs/src/content/docs/using/Approval-gates-cedar-hitl.md b/docs/src/content/docs/using/Approval-gates-cedar-hitl.md index 35d859163..0856cf3e0 100644 --- a/docs/src/content/docs/using/Approval-gates-cedar-hitl.md +++ b/docs/src/content/docs/using/Approval-gates-cedar-hitl.md @@ -15,7 +15,7 @@ When a rule marked `@tier("soft")` matches a tool call: 1. The agent stops before invoking the tool. 2. A row is atomically written to the approvals table and the task status flips to `AWAITING_APPROVAL`. 3. A progress event (`approval_requested`) is emitted so `bgagent watch` shows the gate in real time. -4. The task waits for your decision up to the rule's timeout (default 300 s, configurable per-rule and per-task). +4. The task waits for your decision up to the approval window (default 30 minutes; configurable per repo with the blueprint's `security.approvalTimeoutSeconds`, per task, and per rule, up to 1 hour). 5. On approval, the agent proceeds; on denial, the deny reason is best-effort injected back into the agent's context so it can adapt; on timeout, the gate is treated as a denial with `timed_out` as the reason. A decision is recorded at most once per request. Replaying approve/deny on the same `(task_id, request_id)` is idempotent. diff --git a/docs/src/content/docs/using/Linear-setup-guide.md b/docs/src/content/docs/using/Linear-setup-guide.md index 1fb4f5110..9ef90e353 100644 --- a/docs/src/content/docs/using/Linear-setup-guide.md +++ b/docs/src/content/docs/using/Linear-setup-guide.md @@ -23,8 +23,12 @@ One of two places, chosen automatically at setup time: | | When it's used | What's stored | |---|---|---| -| **AgentCore Identity vault** | The stack was deployed with `--context enableLinearIdentityVault=true` | Nothing long-lived. AgentCore holds the refresh token and mints short-lived access tokens on demand. | -| **Secrets Manager** | Otherwise โ€” including regions where AgentCore Identity isn't available | An OAuth token bundle in `bgagent-linear-oauth-`, refreshed and rotated by ABCA. | +| **AgentCore Identity vault** | **Default** whenever the stack deploys AgentCore (the standard deployment). A deployment without AgentCore (for example `compute_types=ecs`) can opt in with `--context enableLinearIdentityVault=true`, provided its region has AgentCore Identity | Nothing long-lived. AgentCore holds the refresh token and mints short-lived access tokens on demand. | +| **Secrets Manager** | Deployments without AgentCore, or `--context enableLinearIdentityVault=false` | An OAuth token bundle in `bgagent-linear-oauth-`, refreshed and rotated by ABCA only when ABCA uses Linear. | + +Prefer the vault. With Secrets Manager, a workspace that ABCA does not use for long enough can be left with an expired refresh token, and re-authorizing needs a browser that can reach the CLI's `localhost` callback. The vault's hosted consent page works from any machine. + +Existing vault deployments keep their resources and logical IDs, so turning the default on changes nothing for them. A Secrets Manager workspace on a stack that now has the vault keeps working until you re-run `bgagent linear setup `, which moves it to the vault. The vault can be configured with any selected backend. Lambda MicroVMs remains experimental; its image must include the current shared configuration contract. @@ -157,6 +161,17 @@ Apply the trigger label to an issue in that project. Within ~30 seconds the agen - **Check status** โ€” the issue's progress comments, or `bgagent list` / `bgagent status `. - **Cancel** โ€” `bgagent cancel `. Removing the label does *not* cancel a running task. +### Approval gates + +When a task on a Linear issue hits a [Cedar approval gate](/sample-autonomous-cloud-coding-agents/architecture/cedar-hitl-gates), ABCA posts an **approval notice** on the issue: what the agent wants to run, why it is gated, and its decision deadline. When the gate resolves (approved, denied, timed out, or stranded), it posts one **outcome** comment. Each request gets exactly one notice and one outcome, even if events are redelivered. + +To decide from Linear, **reply to the notice comment** while signed in as the task owner: + +- `approve` โ€” approves this one action (the same as `bgagent approve ` with the default `this_call` scope). +- `deny` or `deny ` โ€” denies it, and passes the reason to the agent. `deny: ` and `deny - ` also work. + +ABCA acknowledges the decision in the same thread. Only the Linear user linked to the task's owner (through [inviting teammates](#inviting-teammates)) can decide. A reply from anyone else, or to a request that has already been decided or has expired, gets a short explanation in the thread and changes nothing. Replies from bots and apps, replies whose text no longer matches what Linear holds (for example, edited before ABCA read them), and any other comments in the thread are ignored. Broader scopes (`--scope`) are available only through the CLI and API. + ### Trigger labels | Label | What it does | Use it when | @@ -233,11 +248,15 @@ If you do these the other way round, every mention in the meantime opens a sessi | You do in Linear | ABCA does | |---|---| | @-mention bgagent on an issue, or delegate the issue to it | Acknowledges within seconds with a *thought*, then starts a coding task on the project's mapped repo. If the issue already has an ABCA pull request and your mention carries an instruction, it iterates on that PR instead. The session shows **Started coding task** or **Iterating on pull request**. | +| โ€” the task runs | Keeps the session's checklist current: *Understand the ticket*, *Set up the repository*, *Write the code*, *Open the pull request*, *Ready for your review* (an update to an existing PR has its own wording). The checklist only moves forward. | +| โ€” the agent works | Shows what it's doing right now as one line that the next one replaces ("Reading `src/app.ts`", "Running `npm test`"), the agent's own messages, and its setup steps (issue context gathered, repository cloned, your nudge picked up). At most 30 lasting entries per task; the one-line updates don't count. | | โ€” the agent opens a PR | Attaches the pull request to the session header and posts an **Opened pull request** action. | | โ€” a long run is in progress | Posts a short-lived "Still working" thought at most every 10 minutes, so the session never goes stale (Linear's idle limit is 30 minutes). | -| โ€” the task finishes | Posts one final activity carrying the same outcome, cost, turns and duration as the comment channel: a *response* on success, an *elicitation* if the run stopped to ask you a question, an *error* on failure. Linear turns it into the thread comment. | -| โ€” you're at your concurrency limit | Posts a "Queued" thought in the session. The task starts on its own when a slot frees up. | +| โ€” the task finishes | Posts one final activity carrying the same outcome, cost, turns and duration as the comment channel: a *response* on success, an *elicitation* if the run stopped to ask you a question, an *error* on failure. Its last line says whether you need to do anything. Linear turns it into the thread comment. A task that ends with a pull request moves the issue to *In Review*. | +| โ€” the agent hits an approval gate | Posts the request with **Approve** / **Deny** buttons and the time by which it is denied if nobody answers (30 minutes by default; see `security.approvalTimeoutSeconds`). Choose one, or reply `deny `. When the request matched a single rule there is also **Approve for this task**, so the agent doesn't ask again for that rule during the task. Only the task owner can decide; anyone else, or any other reply, gets the choice again. A decision made elsewhere (`bgagent approve`, a comment reply) or a timeout shows up as a note. | +| โ€” you're at your concurrency limit | Posts a "Queued" thought in the session, and "Still queued (N min so far)" every 15 minutes. The task starts on its own when a slot frees up. | | Reply inside the session while the task runs | Your message goes to the running agent as a nudge (the same guardrail screening, 2,000-character cap and per-minute limit as `bgagent nudge`). The agent picks it up at its next step. Only the task's owner can steer it. | +| Reply `approve` or `deny` when nothing is waiting | Says nothing is waiting and starts nothing, so a late answer after a timeout can't start new work. | | Reply after the task has finished | Starts a follow-up task. If the run stopped to ask a question, your reply resumes the original request with the answer. Otherwise it's a PR iteration if a PR exists, or new work from your message plus the issue. | | Click **Stop** in the session | Cancels the running task and shuts its agent down, like `bgagent cancel`, then confirms with a final response. Only the task's owner can stop it. | @@ -247,9 +266,9 @@ If you do these the other way round, every mention in the meantime opens a sessi **Who can act.** Every session request, `stop` included, needs a linked ABCA user ([Inviting teammates](#inviting-teammates)). An unlinked user is told to link their account and nothing runs. A refusal closes the session it was made in, unless that is the session a running task reports into; there it's a note, so someone else's run isn't marked finished or failed. A new task is attributed to whoever asked for it. Steering or stopping a *running* task follows the API's rule: only its owner can do it. -**Reactions.** A session task gets no ๐Ÿ‘€/โœ…/โŒ reactions on the issue, since the session shows that state. The issue still moves to *In Progress* and *In Review*. +**Reactions.** A session task gets no ๐Ÿ‘€/โœ…/โŒ reactions on the issue, since the session shows that state. The issue still moves to *In Progress* when work starts, and to *In Review* when the task ends with a pull request. -**Not yet supported in sessions:** image and file attachments from the issue description (use a label trigger for those), and Linear's *plan* checklist. +**Not yet supported in sessions:** image and file attachments from the issue description (use a label trigger for those). ## Adding another workspace @@ -333,6 +352,18 @@ If the app has been edited repeatedly through failed saves, creating a fresh app - Is the label spelled as configured? Matching is case-insensitive but must be the same word. - Check CloudWatch for `WebhookFn` and `WebhookProcessorFn`. Common: `Invalid Linear webhook signature`, `Linear workspace is not onboarded`, `Linear project is not onboarded`, `Linear actor has no linked platform user`. +### Linear stops responding and an "authorization revoked" alert arrives + +ABCA probes every registered workspace's grant every 12 hours, as well as whenever an event needs a token. The probe refreshes tokens that are about to expire, which keeps a grant alive even when nobody uses Linear for a while. If Linear rejects a grant, the workspace is marked `revoked` and one alert goes to the **OperationalAlerts** SNS topic (stack output `OperationalAlertsTopicArn`). Subscribe an email or chat endpoint to it, or deploy with `-c alertEmail=โ€ฆ`, because it ships with no subscribers. + +To recover, re-authorize the workspace: + +```bash +bgagent linear setup +``` + +The probe's summary is in the `WebhookProcessorFn` logs ("Linear grant health probe"), listing any workspace without a usable token. + ### Webhook signature verification fails repeatedly The stored signing secret doesn't match the subscription Linear is sending from โ€” usually because the webhook was configured in Linear without telling ABCA, or the secret was rotated: diff --git a/docs/src/content/docs/using/Using-the-cli.md b/docs/src/content/docs/using/Using-the-cli.md index c9051bc0c..3b0a59d38 100644 --- a/docs/src/content/docs/using/Using-the-cli.md +++ b/docs/src/content/docs/using/Using-the-cli.md @@ -114,7 +114,7 @@ Created: 2026-04-01T00:39:51.271Z | `--max-budget` | Maximum cost budget in USD (0.01โ€“100). Overrides per-repo Blueprint default. No default limit. | | `--idempotency-key` | Idempotency key for deduplication. | | `--trace` | Enable detailed tracing: raises progress preview cap to 4 KB and uploads full NDJSON trajectory to S3 on completion. Download with `bgagent trace download`. | -| `--approval-timeout` | Cedar HITL per-task approval timeout in seconds (default 300). A matching rule with its own `@approval_timeout_s` annotation still takes the minimum. See [Approval gates](/sample-autonomous-cloud-coding-agents/using/approval-gates-cedar-hitl). | +| `--approval-timeout` | Cedar HITL per-task approval timeout in seconds (default 1800, or the repo blueprint's `security.approvalTimeoutSeconds`). A matching rule with its own `@approval_timeout_s` annotation still takes the minimum. See [Approval gates](/sample-autonomous-cloud-coding-agents/using/approval-gates-cedar-hitl). | | `--microvm-sleep-after` | Seconds to wait for approval before putting a Lambda MicroVM to sleep (default 60; 0โ€“3600 accepted). Use `off` to keep it awake. Requires the deployment's automatic-sleep feature to be enabled; does not change approval deadlines or affect other compute backends. | | `--pre-approve` | Cedar HITL scope to approve up-front (repeatable). Scope forms: `all_session`, `tool_type:`, `tool_group:`, `bash_pattern:`, `write_path:`, `rule:`. Hard-deny rules are always enforced. | | `--wait` | Poll until the task reaches a terminal status. |