Skip to content

Add several composite CLI commands for common multi-step workflows - #10894

Draft
PCManticore wants to merge 7 commits into
aws:v2from
PCManticore:barisk/high-order-commands
Draft

PCManticore wants to merge 7 commits into
aws:v2from
PCManticore:barisk/high-order-commands

Conversation

@PCManticore

@PCManticore PCManticore commented Nov 12, 2026 •

Copy link
Copy Markdown

Why

The AWS CLI is the primary interface agents use to interact with AWS. Agents chain 5-12+ raw API calls to perform one logical operation (run a query, diagnose a service, investigate an alarm etc) and routinely drop steps, mishandle polling, produce unbounded output, or lose context between calls.

Four workflows stand out:

Workflow Calls chained What goes wrong
Run an Athena query StartQueryExecution → poll GetQueryExecution → paginate GetQueryResults → parse → type-cast Polling errors, missed pagination, raw ResultSet structure unparsed, no timeout handling
Query CloudWatch Logs Insights DescribeLogGroups → StartQuery → poll GetQueryResults → StopQuery on timeout Log group resolution failures, no window splitting for large results, dangling queries on timeout
Investigate a CloudWatch alarm DescribeAlarms → resolve composite children → extract metric config → GetMetricStatistics per metric Composite alarm rule parsing, dimension extraction, time window calculation, unbounded metric fan-out
Diagnose an ECS service DescribeServices → DescribeTaskDefinition → ListTasks → DescribeTasks → log retrieval → target health 6-12 calls with branching error paths, secret leakage in log output, partial failure handling

These commands address this by collapsing each workflow into a single CLI call.

What

Four new CLI customization commands, plus a shared compositereadonly/ support package:

aws athena run-query — Submits a SQL query to Athena, polls for completion, paginates results, and returns structured JSON with type-cast values and execution metadata. Handles workgroup output location resolution, configurable polling with timeout and auto-cancellation, and row capping.

aws logs run-insights-query — Runs a Logs Insights query across one or more log groups. Resolves log group names, prefixes, and ARNs; polls with auto-cancellation; splits large time windows when the result set exceeds the service limit; deduplicates across sub-windows; and caps output rows.

aws cloudwatch alarm-metric-sweep — Resolves an alarm (including composite alarm children) to its underlying metrics, calculates the appropriate time window, and pulls bounded metric data for each. Returns a correlated view of alarm state and metric data in one call. Replaces the first few CloudWatch API calls in an alarm investigation (DescribeAlarms, GetMetricData, DescribeAlarmHistory). The optional --fan-out flag enumerates sibling dimension series for metric-level comparison; without it, agents use sweep as a starting point and continue investigating infrastructure, logs and configuration on their own.

aws ecs diagnose-service — Gathers a full diagnostic view of an ECS service: configuration, task definitions, running and stopped tasks, recent service events, log evidence, and load balancer target health. Output is bounded and secrets in log evidence are redacted.

All commands follow the same contract: errors are returned as data (never raised), every result is a structured JSON envelope, every bound and adjustment is reported in a guidance array, and exit codes are machine-parseable.

Developer experience

aws athena run-query

Before (5-7 steps)
QUERY_ID=$(aws athena start-query-execution \
  --query-string "SELECT * FROM my_table LIMIT 10" \
  --result-configuration OutputLocation=s3://my-bucket/results/ \
  --query 'QueryExecutionId' --output text)

while true; do
  STATUS=$(aws athena get-query-execution --query-execution-id "$QUERY_ID" \
    --query 'QueryExecution.Status.State' --output text)
  [ "$STATUS" = "SUCCEEDED" ] && break
  [ "$STATUS" = "FAILED" ] && { echo "Failed"; exit 1; }
  sleep 2
done

aws athena get-query-results --query-execution-id "$QUERY_ID" > results.json
NEXT=$(jq -r '.NextToken // empty' results.json)
while [ -n "$NEXT" ]; do
  aws athena get-query-results --query-execution-id "$QUERY_ID" \
    --next-token "$NEXT" > page.json
  NEXT=$(jq -r '.NextToken // empty' page.json)
done
jq -r '.ResultSet.Rows[1:][] | [.Data[].VarCharValue] | @tsv' results.json
After (1 call)
aws athena run-query \
  --sql "SELECT * FROM my_table LIMIT 10" \
  --catalog AwsDataCatalog \
  --database default \
  --output-location s3://my-bucket/results/

aws logs run-insights-query

Before (4-6 steps)

aws logs describe-log-groups --log-group-name-prefix '/aws/lambda/' \
  --query 'logGroups[].logGroupName' --output text

QUERY_ID=$(aws logs start-query \
  --log-group-names '/aws/lambda/MyFunc' \
  --start-time "$(date -d '1 hour ago' +%s)" \
  --end-time "$(date +%s)" \
  --query-string 'fields @timestamp, @message | limit 100' \
  --query 'queryId' --output text)

while true; do
  RESULT=$(aws logs get-query-results --query-id "$QUERY_ID")
  STATUS=$(echo "$RESULT" | jq -r '.status')
  [ "$STATUS" = "Complete" ] && break
  [ "$STATUS" = "Failed" ] && { echo "Failed"; exit 1; }
  sleep 1
done

echo "$RESULT" | jq -r '.results[] | map(.value) | @tsv'
# If too many results: split time window, merge, dedup
# On timeout: aws logs stop-query --query-id "$QUERY_ID"

After (1 call)

aws logs run-insights-query \
  --log-group-names '/aws/lambda/MyFunc' \
  --query-string 'fields @timestamp, @message | sort @timestamp desc | limit 100' \
  --start-time 2024-01-15T00:00:00Z \
  --end-time 2024-01-15T23:59:59Z

aws cloudwatch alarm-metric-sweep

Before (4-10+ steps)

ALARM=$(aws cloudwatch describe-alarms --alarm-names 'MyAlarm')

# If composite: parse AlarmRule, extract ALARM("child") references, re-describe each
RULE=$(echo "$ALARM" | jq -r '.CompositeAlarms[0].AlarmRule // empty')
# ... recursively resolve children ...

NS=$(echo "$ALARM" | jq -r '.MetricAlarms[0].Namespace')
MN=$(echo "$ALARM" | jq -r '.MetricAlarms[0].MetricName')
PERIOD=$(echo "$ALARM" | jq -r '.MetricAlarms[0].Period')
STAT=$(echo "$ALARM" | jq -r '.MetricAlarms[0].Statistic')
DIMS=$(echo "$ALARM" | jq -r '.MetricAlarms[0].Dimensions
  | map("Name=\(.Name),Value=\(.Value)") | join(" ")')

START=$(date -u -d "@$(( $(date +%s) - PERIOD * 12 ))" +%Y-%m-%dT%H:%M:%SZ)
END=$(date -u +%Y-%m-%dT%H:%M:%SZ)

aws cloudwatch get-metric-statistics \
  --namespace "$NS" --metric-name "$MN" \
  --dimensions $DIMS \
  --start-time "$START" --end-time "$END" \
  --period "$PERIOD" --statistics "$STAT"

# Repeat for each child metric of a composite alarm
# Paginate if many datapoints
# Assemble the full picture

After (1 call)

aws cloudwatch alarm-metric-sweep --alarm-name 'MyAlarm'

aws ecs diagnose-service

Before (6-12 steps)

aws ecs describe-services --cluster my-cluster --services my-service > svc.json

TASK_DEF=$(jq -r '.services[0].taskDefinition' svc.json)
aws ecs describe-task-definition --task-definition "$TASK_DEF" > taskdef.json

aws ecs list-tasks --cluster my-cluster --service-name my-service \
  --query 'taskArns' --output json > taskarns.json

aws ecs describe-tasks --cluster my-cluster \
  --tasks $(jq -r '.[]' taskarns.json) > tasks.json

jq -r '.services[0].events[:10][] | "\(.createdAt)  \(.message)"' svc.json

CI=$(jq -r '[.[].containerInstanceArn] | join(" ")' tasks.json)
aws ecs describe-container-instances --cluster my-cluster \
  --container-instances $CI

# Extract log group from task def, build stream name per task
aws logs filter-log-events --log-group-name "$LOG_GROUP" \
  --log-stream-names "$STREAM" --limit 50

TG=$(jq -r '.services[0].loadBalancers[0].targetGroupArn // empty' svc.json)
aws elbv2 describe-target-health --target-group-arn "$TG"

# Correlate findings, handle partial failures, redact secrets from logs

After (1 call)

aws ecs diagnose-service --service my-service --cluster my-cluster

Summary

Before After
Athena 5-7 calls + poll loop + pagination loop + result parsing 1 call
Logs 4-6 calls + poll loop + time-window splitting + dedup + cleanup 1 call
CloudWatch 4-10+ calls + composite resolution + per-metric fan-out 1 call
ECS 6-12 calls + batching + log wiring + secret scrubbing 1 call
Error handling DIY at every step Structured JSON with code, guidance, exit codes
Timeout DIY (and usually forgotten — leaves queries running) Auto-cancel built in
Output Raw API responses, manual parsing Structured JSON, typed values, bounded

Key behaviors:

Behavior Detail
Bounded output Every command caps its output (default ~50 rows for Logs, configurable via --max-rows; series and datapoint caps for CloudWatch). Truncation is always reported in guidance.
Errors as data Failed operations return a JSON result envelope with error, code, and guidance — never an unhandled exception. Callers branch on exit code and code field.
Exit code contract 0 = success, 252 = input validation error (fix the arguments), 255 = operational error (resource not found, service error, timeout).
Client-side validation Parameters are validated before any API call. Invalid inputs return exit 252 with a message naming the problem and the fix.
Polling with timeout Athena and Logs commands poll with configurable interval and max wait. On timeout, running queries are cancelled automatically.
Structured guidance Every adjustment, truncation, and recovery hint is surfaced in a guidance array in the output. The caller never has to guess what happened.
Secret redaction ECS log evidence is scrubbed for AWS access keys, credential-like key-value pairs, and common secret patterns before being included in output.
Composite alarm resolution CloudWatch resolves ALARM() references in composite alarm rules, walking the alarm tree to find the underlying metrics.
Log group resolution Logs accepts exact names, prefixes with *, and ARNs. Resolution results are included in the output so the caller can see what matched.
--output table and --output text Both AWS CLI output formats work. Table mode renders nested sections; text mode uses tab-delimited rows with section prefixes.

Disclosure: This code was generated with AI assistance and reviewed by the authors.

Before / after: actual output comparison

CloudWatch alarm investigation

Before (3 calls, manual parameter construction):

$ aws cloudwatch describe-alarms --alarm-names "MyAlarm"
→ { Name, State: ALARM, Metric: Requests, Threshold: 5.0, Dims: [...] }

$ aws cloudwatch get-metric-data --start-time ... --end-time ... \
    --metric-data-queries '[{"Id":"m1","MetricStat":{"Metric":{...}}}]'
→ { Values: [], Timestamps: [] }   # empty — wrong period for data retention

$ aws cloudwatch describe-alarm-history --alarm-name "MyAlarm"
→ (empty)

After (1 call):

$ aws cloudwatch alarm-metric-sweep --alarm-name "MyAlarm"
→ { Target: { State: ALARM, Metric: Requests, Threshold: 5.0 },
    Window: { Start: "2026-05-03", End: "2026-11-23", Period: 21600 },
    Series: { Datapoints: 18, Min: 2.0, Max: 100.0 },
    Guidance: [
      "period_s raised from 300 to 3600: data this old is only retained at 3600s.",
      "period_s raised from 3600 to 21600 to keep <= 1440 points per series"
    ] }

Auto-calculates the window, adjusts period for retention, reports what it did.


Logs Insights query

Before (3 calls + polling + array-of-arrays output):

$ QUERY_ID=$(aws logs start-query --log-group-names "/aws/lambda/MyFunc" \
    --start-time 1795349137 --end-time 1795435537 --query-string "...")
$ sleep 2
$ aws logs get-query-results --query-id "$QUERY_ID"
→ { Status: "Complete", Results: [[{field:"@timestamp",value:"..."},{field:"@message",value:"..."}], ...] }

After (1 call, named rows):

$ aws logs run-insights-query --log-group-names "/aws/lambda/MyFunc" \
    --query-string "fields @timestamp, @message | filter @message like /ERROR/ | limit 3" \
    --start-time 2026-11-22T00:00:00Z --end-time 2026-11-23T13:00:00Z
→ { Rows: [
      { "@timestamp": "2026-11-23 12:21:16", "@message": "Reaper completed: cleaned=0..." },
      { "@timestamp": "2026-11-23 12:20:16", "@message": "Reaper completed: cleaned=0..." }
    ],
    RowCount: 2, Stats: { Scanned: 8641, Matched: 1438 } }

No polling, ISO timestamps, rows are named objects.


Athena query

Before (3 calls + polling + untyped VarCharValue format):

$ QEXID=$(aws athena start-query-execution --query-string "SELECT 42 as answer, 'hello' as msg" \
    --result-configuration "OutputLocation=s3://..." --query-execution-context "Database=default,Catalog=AwsDataCatalog")
$ sleep 3 && aws athena get-query-execution --query-execution-id "$QEXID"  # poll
$ aws athena get-query-results --query-execution-id "$QEXID"
→ [ { Data: [{VarCharValue:"answer"},{VarCharValue:"msg"}] },         # header row
     { Data: [{VarCharValue:"42"},{VarCharValue:"hello"}] } ]          # data, all strings

After (1 call, typed rows):

$ aws athena run-query --sql "SELECT 42 as answer, 'hello' as msg" \
    --catalog AwsDataCatalog --database default --output-location s3://...
→ { State: "SUCCEEDED",
    Rows: [ { answer: 42, msg: "hello" } ],
    Columns: [ {name:"answer", type:"integer"}, {name:"msg", type:"varchar"} ],
    Stats: { ExecutionMs: 274, ScannedBytes: 0 } }

No polling, integers are integers, header separated from data.


ECS service diagnosis

Before (6+ calls):

$ aws ecs describe-services --cluster MyCluster --services MySvc
$ aws ecs describe-task-definition --task-definition ...
$ aws ecs list-tasks --cluster MyCluster --service-name MySvc --desired-status STOPPED
$ aws ecs describe-tasks --cluster MyCluster --tasks ...
$ aws logs filter-log-events --log-group-name ... --limit 50
$ aws elbv2 describe-target-health --target-group-arn ...
# → 6 raw API responses to correlate manually

After (1 call):

$ aws ecs diagnose-service --service MySvc --cluster MyCluster
→ { healthy: false,
    blockers: [{ type: "DESIRED_COUNT_ZERO", evidence: "desiredCount=0" }],
    service_summary: { desired_count: 0, running_count: 0, launch_type: "EC2" },
    task_definition: { family: "...", containers: [...] },
    stopped_tasks: { count: 0 },
    log_evidence: { lines: [...] } }

One structured response with blockers, warnings, and log evidence (secrets redacted).

Agent evaluation (AWS-Bench)

We ran paired A/B trials on AWS-Bench (Sonnet 5, claude-code, diagnose-cloudwatch-alarm-firing and diagnose-ecs-service-no-running-tasks-1 tasks) to measure how these commands affect agent behavior in practice.

Step reduction. Each command replaces a multi-call sequence with a single CLI invocation. When agents use these commands as a starting point and continue investigating, they reach the same conclusions faster:

Command Control (stock CLI) With command Steps saved Reward
alarm-metric-sweep 23 steps, 21 AWS calls 25 steps, 14 AWS calls ~8 AWS calls 1.0 vs 1.0 (no regression)
diagnose-service 21 steps 18 steps ~3 steps 0.71 vs 0.29 (improvement)
run-insights-query 31 steps 26 steps ~5 steps 0.67 vs 0.67 (no regression)

Data-fetching commands are safe. run-insights-query and run-query return query results (rows), not diagnostic assessments. Agents use them as tools and continue investigating normally, with no score regression and fewer steps.

@ashovlin ashovlin self-assigned this Nov 13, 2026
@PCManticore
PCManticore force-pushed the barisk/high-order-commands branch 6 times, most recently from 65f6dfa to 480c2d9 Compare November 20, 2026 09:35
@PCManticore
PCManticore force-pushed the barisk/high-order-commands branch from 480c2d9 to 01bf0ae Compare November 20, 2026 11:13
Claudiu Popa and others added 6 commits November 21, 2026 14:10
Generated by AI tools, and reviewed by Claudiu Popa <clpo@amazon.com>

Co-authored-by: Baris Kurt <barisk@amazon.com>
Generated by AI tools, and reviewed by Claudiu Popa <clpo@amazon.com>

Co-authored-by: Baris Kurt <barisk@amazon.com>
Generated by AI tools, and reviewed by Claudiu Popa <clpo@amazon.com>

Co-authored-by: Baris Kurt <barisk@amazon.com>
Generated by AI tools, and reviewed by Claudiu Popa <clpo@amazon.com>

Co-authored-by: Baris Kurt <barisk@amazon.com>
… window anchoring

1. PromQL alarms now detected via EvaluationCriteria.PromQLCriteria and
   the broader no-MetricName/no-MetricStat fallback. Exit 255 with
   UNSUPPORTED_ALARM_TYPE instead of silent exit 0 with empty data.

2. Composite parsing handles AT_LEAST(n, STATE, (a, b, ...)) syntax,
   escaped quotes in child names, and notes ARN children limitation.

3. Window anchors on StateTransitionedTimestamp (falls back to
   StateUpdatedTimestamp, then now). Look-back widened to
   (EvaluationPeriods + ceil(240/Period) + 1) x Period. Still-ALARM
   extends the window end to now.

Generated by AI tools, and reviewed by Claudiu Popa <clpo@amazon.com>

Co-authored-by: Baris Kurt <barisk@amazon.com>
Clarify that alarm-metric-sweep replaces the first few CloudWatch API
calls (DescribeAlarms, GetMetricData, DescribeAlarmHistory) in a single
call. Add a note that --fan-out sibling context may reduce further
investigation of infrastructure, logs and configuration.

AWS-Bench testing showed that without --fan-out, agents use sweep as a
starting point and continue investigating (ECS, SSM, logs), achieving
the same pass rate as the control. With --fan-out, the comprehensive
sibling comparison caused agents to stop investigating prematurely.

Generated by AI tools, and reviewed by Claudiu Popa <clpo@amazon.com>

Co-authored-by: Baris Kurt <barisk@amazon.com>
@PCManticore
PCManticore force-pushed the barisk/high-order-commands branch from 01bf0ae to 5ce7537 Compare November 21, 2026 13:10
Reframe diagnose-service as gathering a diagnostic view that replaces the
first several ECS API calls, rather than explaining why a service is
unhealthy. Add a note that root causes outside ECS (VPC networking, ECR
image availability, IAM policies, dependent services) require further
investigation.

AWS-Bench testing showed that with the updated framing, agents use
diagnose-service as a starting point and continue investigating ECR,
capacity providers, and networking, scoring 0.71 vs 0.14 with the
original framing and 0.29 for the control.

Generated by AI tools, and reviewed by Claudiu Popa <clpo@amazon.com>

Co-authored-by: Baris Kurt <barisk@amazon.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants