From ba803ed712de91c487ff074cbdefa7d93a89bf8c Mon Sep 17 00:00:00 2001 From: bgagent Date: Tue, 24 Nov 2026 21:18:56 -0600 Subject: [PATCH 01/11] fix(cli): write secret files through a temporary file and a rename writeSecretFile truncated the file and then wrote it. A refreshed token is saved this way, and a second bgagent process that read credentials.json in between got an empty or partial file and reported a valid login as corrupt. `bgagent login`, which the message advises, did not help, and the next parallel run could fail the same way. The content now goes to a temporary file beside the target, created exclusively with mode 0600 under a name of its own, and a rename puts it in place: a reader gets the old file or the new one. The function is shared, so invite files, pending Linear consents and `replay --output` are written the same way. A device, a FIFO and a symbolic link are still written in place, because a rename would replace the node or the link. A regular file that can be written but not replaced now fails where it used to be written in place: a file in a directory the user cannot write to, and a file name too long to take the temporary suffix. Closes #1080 --- cli/src/config.ts | 28 ++++++++++--- cli/test/config.test.ts | 93 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 5 deletions(-) diff --git a/cli/src/config.ts b/cli/src/config.ts index 1ffc112ae..ac64f7129 100644 --- a/cli/src/config.ts +++ b/cli/src/config.ts @@ -17,6 +17,7 @@ * SOFTWARE. */ +import * as crypto from 'crypto'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; @@ -110,13 +111,30 @@ export function clearCredentials(): void { fs.rmSync(credentialsPath(), { force: true }); } -/** Write a file that only its owner may read, whether it is new or already there. */ +/** + * Write a file that only its owner may read, whether it is new or already there. + * Another bgagent process may be reading it, so the content goes to a temporary file + * that replaces the target in one step: a reader gets the old file or the new one, + * never a truncated one (#1080). + */ export function writeSecretFile(file: string, content: string): void { + const target = fs.lstatSync(file, { throwIfNoEntry: false }); + if (!target || target.isFile()) { + // Created exclusively, under a name that cannot be guessed: a path the user chose may + // be in a directory that others can write to, and a link planted there is not followed. + const temp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`; + try { + fs.writeFileSync(temp, content, { mode: SECRET_FILE_MODE, flag: 'wx' }); + fs.renameSync(temp, file); + } finally { + fs.rmSync(temp, { force: true }); + } + return; + } + // A device such as /dev/null, a FIFO or a symbolic link is written in place: a rename + // would replace the node or the link itself. writeFileSync only honors `mode` when + // CREATING the file, so chmod what the path resolves to, if that is a regular file. fs.writeFileSync(file, content, { mode: SECRET_FILE_MODE }); - // writeFileSync only honors `mode` when CREATING the file; overwriting a - // pre-existing loose-permissions file leaves its bits untouched. chmod - // makes the 0600 intent durable across rewrites. Regular files only: a - // path the user chose may be a device such as /dev/null. if (fs.statSync(file).isFile()) { fs.chmodSync(file, SECRET_FILE_MODE); } diff --git a/cli/test/config.test.ts b/cli/test/config.test.ts index 1d96d28b5..e80114615 100644 --- a/cli/test/config.test.ts +++ b/cli/test/config.test.ts @@ -119,4 +119,97 @@ describe('config', () => { expect(fs.statSync(p).mode % 0o1000).toBe(0o600); }); }); + + // One bgagent process saves a refreshed token while others read the file (#1080). + describe('writing the credentials file', () => { + const OLD = { id_token: 'old-id', refresh_token: 'old-refresh', token_expiry: '2026-01-01T00:00:00.000Z' }; + const NEW = { id_token: 'new-id', refresh_token: 'new-refresh', token_expiry: '2026-02-01T00:00:00.000Z' }; + // `import * as fs` is a read-only view of the module, here and in config.ts: a spy goes on the module itself. + const nodeFs = jest.requireActual('fs'); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + test('replaces the file in one step, so a reader gets the old login or the new one', () => { + saveCredentials(OLD); + const rename = fs.renameSync; + const atRename: unknown[] = []; + jest.spyOn(nodeFs, 'renameSync').mockImplementationOnce((from, to) => { + // A rename is one step only within a file system: the new file waits beside the old one, + // whole and owner-only, while a reader still gets the old login. + atRename.push({ + read: loadCredentials(), + from: path.dirname(String(from)), + staged: JSON.parse(fs.readFileSync(from, 'utf-8')), + mode: fs.statSync(from).mode % 0o1000, + }); + rename(from, to); + }); + + saveCredentials(NEW); + + expect(atRename).toEqual([{ read: OLD, from: tmpDir, staged: NEW, mode: 0o600 }]); + expect(loadCredentials()).toEqual(NEW); + expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); + }); + + test('keeps the old file and leaves no temporary file when the replacement fails', () => { + saveCredentials(OLD); + jest.spyOn(nodeFs, 'renameSync').mockImplementationOnce(() => { throw new Error('rename failed'); }); + + expect(() => saveCredentials(NEW)).toThrow('rename failed'); + + expect(loadCredentials()).toEqual(OLD); + expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); + }); + + test('refuses a temporary name that is taken instead of writing through it', () => { + // A path the user chose can be in a directory that others may write to: a link + // planted under the temporary name must not send the secret where it points. + const victim = path.join(tmpDir, 'victim'); + fs.writeFileSync(victim, 'untouched'); + const write = fs.writeFileSync; + jest.spyOn(nodeFs, 'writeFileSync').mockImplementationOnce((file, data, options) => { + fs.symlinkSync(victim, String(file)); + write(file, data, options); + }); + + expect(() => saveCredentials(NEW)).toThrow('EEXIST'); + + expect(fs.readFileSync(victim, 'utf-8')).toBe('untouched'); + }); + + test('gives every save a temporary file of its own, so two can run at once', () => { + // The process id alone does not tell two saves apart: containers that share the + // directory can give the same one to both. + const rename = fs.renameSync; + const renames = jest.spyOn(nodeFs, 'renameSync').mockImplementationOnce((from, to) => { + // Another save, start to finish, while this one waits to rename. + saveCredentials(OLD); + rename(from, to); + }); + + saveCredentials(NEW); + + expect(renames).toHaveBeenCalledTimes(2); + expect(loadCredentials()).toEqual(NEW); + expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); + }); + + test('writes through a symbolic link instead of replacing it', () => { + // A dotfiles setup keeps credentials.json elsewhere and links to it. + const link = path.join(tmpDir, 'credentials.json'); + const elsewhere = path.join(tmpDir, 'elsewhere.json'); + fs.writeFileSync(elsewhere, '{}'); + fs.chmodSync(elsewhere, 0o644); + fs.symlinkSync(elsewhere, link); + + saveCredentials(NEW); + + expect(fs.lstatSync(link).isSymbolicLink()).toBe(true); + expect(JSON.parse(fs.readFileSync(elsewhere, 'utf-8'))).toEqual(NEW); + expect(fs.statSync(elsewhere).mode % 0o1000).toBe(0o600); + }); + }); }); From e3b176fa27f15257962f526e1954e87dee4475ac Mon Sep 17 00:00:00 2001 From: bgagent Date: Tue, 24 Nov 2026 22:21:38 -0600 Subject: [PATCH 02/11] ci: remove the deploy and integ workflows and the manual integ task Both workflows started after every build and did no work. deploy.yml could deploy only for a `deploy` label or a dispatch input, and the repository has no such label. integ.yml waited for an approval of the `deploy` environment; its test step last ran on 2026-11-17 and failed. The emulator-backed tests are the integration check that CI runs, and no workflow uses an AWS account any more. build.yml loses what fed the two: the `deploy` dispatch input, the steps that wrote cdk/cdk.context.json (stack name, github:* tags, the AZ override of AGENTCORE_AVAILABILITY_ZONES) and the upload of cdk.out and of the deploy intent. Its one-value matrix stays, because it names the required check `build (agentcore)`. The manual path goes with them: the integ task of cdk/mise.toml, the smoke app under cdk/test/integ, its two test suites, the ignore patterns for it in the jest configuration and in their copy in contracts/coverage-thresholds.json, and the two dependencies that served it, integ-runner and integ-tests-alpha. Nothing ran the task any more, and no run of it in CI had completed since the workflow's call of it was repaired (PR 1048). No automated test of a deployed stack exists now. The secret scan loses the path exemption for integ-runner snapshot directories, which matched nothing any more. Tests, comments and documents that described the pipeline say what is true now. ADR-013 records the change and drops the accepted risk of fork code running with the deploy role, which ended with the integ workflow. --- .github/workflows/build.yml | 230 +------------ .github/workflows/deploy.yml | 317 ----------------- .github/workflows/emulator.yml | 4 +- .github/workflows/integ.yml | 325 ------------------ .github/workflows/security-pr.yml | 4 +- .gitignore | 12 - .gitleaks.toml | 3 +- cdk/mise.toml | 26 -- cdk/package.json | 8 +- cdk/scripts/preflight-log-delivery.ts | 13 +- cdk/src/constructs/agentcore-azs.ts | 13 +- cdk/test/constructs/agentcore-azs.test.ts | 4 +- cdk/test/integ/integ.task-api-smoke.ts | 231 ------------- cdk/test/main.test.ts | 6 +- cdk/test/scripts/deploy-workflow.test.ts | 129 ------- cdk/test/scripts/integ-stack-names.test.ts | 59 ---- cdk/test/scripts/integ-workflow.test.ts | 91 ----- .../scripts/preflight-log-delivery.test.ts | 17 +- cdk/test/scripts/workflow-installs.test.ts | 10 +- contracts/coverage-thresholds.json | 6 +- docs/abca-plugin/skills/deploy/SKILL.md | 2 +- .../ADR-013-tiered-validation-pyramid.md | 23 +- docs/design/CI_BUILD_PERFORMANCE.md | 3 +- docs/design/OBSERVABILITY.md | 6 +- docs/guides/DEPLOYMENT_GUIDE.md | 74 +--- docs/guides/QUICK_START.mdx | 2 +- .../docs/architecture/Ci-build-performance.md | 3 +- .../docs/architecture/Observability.md | 6 +- .../Adr-013-tiered-validation-pyramid.md | 23 +- .../docs/getting-started/Deployment-guide.md | 74 +--- .../docs/getting-started/Quick-start.mdx | 2 +- knip.json | 2 +- scripts/aws-emulator/README.md | 2 +- yarn.lock | 32 -- 34 files changed, 108 insertions(+), 1654 deletions(-) delete mode 100644 .github/workflows/deploy.yml delete mode 100644 .github/workflows/integ.yml delete mode 100644 cdk/test/integ/integ.task-api-smoke.ts delete mode 100644 cdk/test/scripts/deploy-workflow.test.ts delete mode 100644 cdk/test/scripts/integ-stack-names.test.ts delete mode 100644 cdk/test/scripts/integ-workflow.test.ts diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 94fcf4996..b8bca9fa2 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -5,15 +5,7 @@ on: # report inside the merge queue. Without this trigger, marking `build` a required # check would deadlock the queue (the check never reports). See issue #327. merge_group: {} - workflow_dispatch: - inputs: - deploy: - description: "Deploy after build (- = no deploy)" - type: choice - default: "-" - options: - - "-" - - agentcore + workflow_dispatch: {} permissions: actions: none attestations: none @@ -58,6 +50,9 @@ jobs: && 'ubuntu-latest-4-cores') || 'ubuntu-latest' }} + # The one-value matrix names this job `build (agentcore)`, the check that the + # ruleset of `main` requires. Without it the check is `build`: the required + # one never reports and nothing merges. strategy: matrix: compute_type: [agentcore] @@ -96,168 +91,6 @@ jobs: with: fetch-depth: 1 # shallow clone persist-credentials: false - - name: Resolve github:* tag values - id: tags - env: - EVENT_NAME: ${{ github.event_name }} - GH_SHA: ${{ github.sha }} - GH_REF_NAME: ${{ github.ref_name }} - GH_REF_TYPE: ${{ github.ref_type }} - GH_HEAD_REF: ${{ github.head_ref }} - GH_BASE_REF: ${{ github.base_ref }} - MG_HEAD_SHA: ${{ github.event.merge_group.head_sha }} - MG_BASE_REF: ${{ github.event.merge_group.base_ref }} - MG_HEAD_REF: ${{ github.event.merge_group.head_ref }} - PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} - PR_NUMBER: ${{ github.event.pull_request.number }} - run: | - case "$EVENT_NAME" in - merge_group) - echo "sha=${MG_HEAD_SHA}" >> "$GITHUB_OUTPUT" - echo "ref=${MG_BASE_REF}" >> "$GITHUB_OUTPUT" - echo "ref-type=branch" >> "$GITHUB_OUTPUT" - echo "head-ref=${MG_HEAD_REF}" >> "$GITHUB_OUTPUT" - echo "base-ref=${MG_BASE_REF}" >> "$GITHUB_OUTPUT" - PR_NUM=$(echo "$MG_HEAD_REF" | grep -oP 'pr-\K[0-9]+' || echo "") - echo "pr-number=${PR_NUM}" >> "$GITHUB_OUTPUT" - ;; - pull_request|pull_request_target) - echo "sha=${PR_HEAD_SHA}" >> "$GITHUB_OUTPUT" - echo "ref=${GH_HEAD_REF}" >> "$GITHUB_OUTPUT" - echo "ref-type=branch" >> "$GITHUB_OUTPUT" - echo "head-ref=${GH_HEAD_REF}" >> "$GITHUB_OUTPUT" - echo "base-ref=${GH_BASE_REF}" >> "$GITHUB_OUTPUT" - echo "pr-number=${PR_NUMBER}" >> "$GITHUB_OUTPUT" - ;; - push) - echo "sha=${GH_SHA}" >> "$GITHUB_OUTPUT" - echo "ref=${GH_REF_NAME}" >> "$GITHUB_OUTPUT" - echo "ref-type=${GH_REF_TYPE}" >> "$GITHUB_OUTPUT" - echo "head-ref=" >> "$GITHUB_OUTPUT" - echo "base-ref=" >> "$GITHUB_OUTPUT" - echo "pr-number=" >> "$GITHUB_OUTPUT" - ;; - *) - echo "sha=${GH_SHA}" >> "$GITHUB_OUTPUT" - echo "ref=${GH_REF_NAME}" >> "$GITHUB_OUTPUT" - echo "ref-type=${GH_REF_TYPE}" >> "$GITHUB_OUTPUT" - echo "head-ref=" >> "$GITHUB_OUTPUT" - echo "base-ref=" >> "$GITHUB_OUTPUT" - echo "pr-number=" >> "$GITHUB_OUTPUT" - ;; - esac - - name: Resolve stack name - id: naming - env: - EVENT_NAME: ${{ github.event_name }} - COMPUTE_TYPE: ${{ matrix.compute_type }} - GH_SHA: ${{ github.sha }} - GH_REF_NAME: ${{ github.ref_name }} - PR_NUMBER: ${{ steps.tags.outputs.pr-number }} - run: | - sanitize() { - local result - result=$(echo "$1" | tr '[:upper:]' '[:lower:]' | tr '/_.' '-' | sed 's/[^a-z0-9-]//g; s/--*/-/g' | cut -c1-60 | sed 's/^-*//; s/-$//') - # CloudFormation requires stack names to start with a letter - if [[ -z "$result" || ! "$result" =~ ^[a-z] ]]; then - result="s-${result}" - fi - echo "$result" - } - - case "$EVENT_NAME" in - push) - REF=$(sanitize "$GH_REF_NAME") - STACK_NAME="${REF}-${COMPUTE_TYPE}" - ;; - pull_request|pull_request_target) - if [[ ! "$PR_NUMBER" =~ ^[0-9]+$ ]]; then - echo "::error::Invalid PR number: '$PR_NUMBER'" - exit 1 - fi - STACK_NAME="pr${PR_NUMBER}-${COMPUTE_TYPE}" - ;; - merge_group) - if [[ -n "$PR_NUMBER" && "$PR_NUMBER" =~ ^[0-9]+$ ]]; then - STACK_NAME="mg${PR_NUMBER}-${COMPUTE_TYPE}" - else - STACK_NAME="${COMPUTE_TYPE}-${GH_SHA:0:7}" - fi - ;; - workflow_dispatch) - REF=$(sanitize "$GH_REF_NAME") - STACK_NAME="${REF}-${COMPUTE_TYPE}" - ;; - *) - STACK_NAME="${COMPUTE_TYPE}-${GH_SHA:0:7}" - ;; - esac - - echo "stack_name=$STACK_NAME" >> "$GITHUB_OUTPUT" - echo "Stack name: $STACK_NAME" - - name: Generate CDK context - env: - COMPUTE_TYPE: ${{ matrix.compute_type }} - STACK_NAME: ${{ steps.naming.outputs.stack_name }} - TAG_SHA: ${{ steps.tags.outputs.sha }} - TAG_REF: ${{ steps.tags.outputs.ref }} - TAG_REF_TYPE: ${{ steps.tags.outputs.ref-type }} - TAG_ACTOR: ${{ github.actor }} - TAG_HEAD_REF: ${{ steps.tags.outputs.head-ref }} - TAG_BASE_REF: ${{ steps.tags.outputs.base-ref }} - TAG_PR_NUMBER: ${{ steps.tags.outputs.pr-number }} - TAG_RUN_ID: ${{ github.run_id }} - TAG_RUN_ATTEMPT: ${{ github.run_attempt }} - TAG_EVENT: ${{ github.event_name }} - TAG_WORKFLOW: ${{ github.workflow }} - TAG_REPOSITORY: ${{ github.repository }} - # AgentCore-supported AZ pin for the deployed stack. The assembly this - # step feeds is synthesized WITHOUT credentials (env-agnostic), so - # auto-pin cannot run and this override is the only way the pipeline - # can keep the Runtime ENIs out of unsupported zones. Set the repo/env - # variable AGENTCORE_AVAILABILITY_ZONES to a JSON array of zone NAMES - # whose zone IDs are AgentCore-supported in the deploy account, e.g. - # ["us-east-1b","us-east-1c"]. Unset => not pinned (synth warns). - # See docs/guides/DEPLOYMENT_GUIDE.md "AgentCore unsupported Availability Zones". - AGENTCORE_AZS: ${{ vars.AGENTCORE_AVAILABILITY_ZONES }} - run: | - jq -n \ - --arg compute_type "$COMPUTE_TYPE" \ - --arg stackName "$STACK_NAME" \ - --arg agentcore_azs "$AGENTCORE_AZS" \ - --arg sha "$TAG_SHA" \ - --arg ref "$TAG_REF" \ - --arg ref_type "$TAG_REF_TYPE" \ - --arg actor "$TAG_ACTOR" \ - --arg head_ref "$TAG_HEAD_REF" \ - --arg base_ref "$TAG_BASE_REF" \ - --arg pr_number "$TAG_PR_NUMBER" \ - --arg run_id "$TAG_RUN_ID" \ - --arg run_attempt "$TAG_RUN_ATTEMPT" \ - --arg event "$TAG_EVENT" \ - --arg workflow "$TAG_WORKFLOW" \ - --arg repository "$TAG_REPOSITORY" \ - '{ - "compute_type": $compute_type, - "stackName": $stackName, - "github:sha": $sha, - "github:ref": $ref, - "github:ref-type": $ref_type, - "github:actor": $actor, - "github:head-ref": $head_ref, - "github:base-ref": $base_ref, - "github:pr-number": $pr_number, - "github:run-id": $run_id, - "github:run-attempt": $run_attempt, - "github:event": $event, - "github:workflow": $workflow, - "github:repository": $repository, - "github:clean": "true" - } - + (if $agentcore_azs == "" then {} - else {"agentcore:availabilityZones": ($agentcore_azs | fromjson)} end)' \ - > cdk/cdk.context.json - cat cdk/cdk.context.json - name: Install mise uses: jdx/mise-action@d5574b52816a478f9d4e6529a3f6ff17a8a36785 # v5.2.8 with: @@ -403,61 +236,6 @@ jobs: # every file that looks like coverage, e.g. contracts/coverage-thresholds.json. disable_search: true fail_ci_if_error: false - - name: Upload CDK artifact (${{ matrix.compute_type }}) - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: cdk-${{ matrix.compute_type }}-out - path: | - cdk/cdk.out/ - cdk/cdk.context.json - - name: Write deploy intent - env: - EVENT_NAME: ${{ github.event_name }} - GH_REF_NAME: ${{ github.ref_name }} - DISPATCH_DEPLOY: ${{ inputs.deploy }} - COMPUTE_TYPE: ${{ matrix.compute_type }} - # Keep in sync with matrix.compute_type above, inputs.deploy.options, - # and deploy.yml ALLOWED_COMPUTE_TYPES - ALLOWED_COMPUTE_TYPES: "agentcore" - run: | - # exit (not return) — no recovery path; invalid dispatch input must abort the step - validate_compute_type() { - local type="$1" - for allowed in $ALLOWED_COMPUTE_TYPES; do - [[ "$type" == "$allowed" ]] && return 0 - done - echo "::error::Invalid compute_type: '$type'. Allowed: $ALLOWED_COMPUTE_TYPES" - exit 1 - } - - case "$EVENT_NAME" in - push) - if [[ "$GH_REF_NAME" == "main" ]]; then - INTENT="$COMPUTE_TYPE" - else - INTENT="-" - fi - ;; - workflow_dispatch) - if [[ "$DISPATCH_DEPLOY" != "-" ]]; then - validate_compute_type "$DISPATCH_DEPLOY" - fi - INTENT="$DISPATCH_DEPLOY" - ;; - pull_request|pull_request_target) - INTENT="labels" - ;; - *) - INTENT="-" - ;; - esac - jq -n --arg deploy "$INTENT" '{"deploy":$deploy}' > deploy-intent.json - echo "Deploy intent: $INTENT" - - name: Upload deploy intent - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: deploy-intent - path: deploy-intent.json - name: Find mutations id: self_mutation run: |- diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml deleted file mode 100644 index 974a8eb37..000000000 --- a/.github/workflows/deploy.yml +++ /dev/null @@ -1,317 +0,0 @@ -name: deploy -on: - # zizmor: ignore[dangerous-triggers] — intentional; workflow_run is required - # for OIDC id-token on PR builds. Mitigations: env-var-only untrusted input, - # least-privilege permissions per job, deploy environment approval gate. - workflow_run: - workflows: [build] - types: [completed] -permissions: {} -jobs: - resolve-targets: - if: >- - github.event.workflow_run.conclusion == 'success' && - github.event.workflow_run.head_repository.full_name == github.repository - runs-on: ubuntu-latest - permissions: - actions: read - pull-requests: read - outputs: - matrix: ${{ steps.targets.outputs.matrix }} - has_targets: ${{ steps.targets.outputs.has_targets }} - run_id: ${{ github.event.workflow_run.id }} - steps: - - name: Download deploy intent - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - name: deploy-intent - run-id: ${{ github.event.workflow_run.id }} - github-token: ${{ github.token }} - - - name: Resolve deploy targets - id: targets - env: - GH_TOKEN: ${{ github.token }} - REPO: ${{ github.repository }} - PR_NUMBER_FROM_EVENT: ${{ github.event.workflow_run.pull_requests[0].number }} - HEAD_SHA: ${{ github.event.workflow_run.head_sha }} - # Single source of truth for this workflow; keep in sync with - # build.yml matrix.compute_type and workflow_dispatch.inputs.deploy.options - ALLOWED_COMPUTE_TYPES: "agentcore" - run: | - ALL_TYPES=$(printf '%s\n' $ALLOWED_COMPUTE_TYPES | jq -Rc . | jq -sc .) - - resolve_pr_number() { - if [[ -n "$PR_NUMBER_FROM_EVENT" ]]; then - echo "$PR_NUMBER_FROM_EVENT" - return - fi - gh api "repos/$REPO/commits/$HEAD_SHA/pulls" --jq '.[0].number // empty' 2>/dev/null || true - } - PR_NUMBER=$(resolve_pr_number) - - # return (not exit) — callers handle failure gracefully (skip type or set empty matrix) - validate_compute_type() { - local type="$1" - for allowed in $ALLOWED_COMPUTE_TYPES; do - [[ "$type" == "$allowed" ]] && return 0 - done - echo "::error::Invalid compute_type: '$type'. Allowed: $ALLOWED_COMPUTE_TYPES" - return 1 - } - - filter_valid_types() { - local input_json="$1" - local valid_json="[]" - for type in $(echo "$input_json" | jq -r '.[]'); do - if validate_compute_type "$type" 2>/dev/null; then - valid_json=$(echo "$valid_json" | jq -c --arg t "$type" '. + [$t]') - else - echo "::warning::Ignoring invalid compute_type from label: '$type'" - fi - done - echo "$valid_json" - } - - INTENT=$(jq -r '.deploy' deploy-intent.json) - echo "Deploy intent from build: $INTENT" - - case "$INTENT" in - -) - echo "matrix=[]" >> "$GITHUB_OUTPUT" - echo "has_targets=false" >> "$GITHUB_OUTPUT" - ;; - labels) - if [[ -z "$PR_NUMBER" ]]; then - echo "::warning::Could not resolve PR number from event or head_sha" - echo "matrix=[]" >> "$GITHUB_OUTPUT" - echo "has_targets=false" >> "$GITHUB_OUTPUT" - exit 0 - fi - - LABELS=$(gh api "repos/$REPO/pulls/$PR_NUMBER" --jq '[.labels[].name]') - - if echo "$LABELS" | jq -e '[.[] | select(startswith("deploy:"))] | length > 0' > /dev/null 2>&1; then - RAW_TYPES=$(echo "$LABELS" | jq -c '[.[] | select(startswith("deploy:")) | ltrimstr("deploy:")]') - VALIDATED=$(filter_valid_types "$RAW_TYPES") - COUNT=$(echo "$VALIDATED" | jq 'length') - if [[ "$COUNT" -gt 0 ]]; then - echo "matrix=$VALIDATED" >> "$GITHUB_OUTPUT" - echo "has_targets=true" >> "$GITHUB_OUTPUT" - else - echo "::warning::All deploy: labels were invalid" - echo "matrix=[]" >> "$GITHUB_OUTPUT" - echo "has_targets=false" >> "$GITHUB_OUTPUT" - fi - elif echo "$LABELS" | jq -e 'index("deploy")' > /dev/null 2>&1; then - echo "matrix=$ALL_TYPES" >> "$GITHUB_OUTPUT" - echo "has_targets=true" >> "$GITHUB_OUTPUT" - else - echo "matrix=[]" >> "$GITHUB_OUTPUT" - echo "has_targets=false" >> "$GITHUB_OUTPUT" - fi - ;; - *) - if ! validate_compute_type "$INTENT"; then - echo "matrix=[]" >> "$GITHUB_OUTPUT" - echo "has_targets=false" >> "$GITHUB_OUTPUT" - exit 1 - fi - echo "matrix=[\"$INTENT\"]" >> "$GITHUB_OUTPUT" - echo "has_targets=true" >> "$GITHUB_OUTPUT" - ;; - esac - - # Surfaces CloudFormation changes in the step summary BEFORE the deploy - # approval gate. Uses a read-only IAM role (no deploy/mutate permissions). - # Configure the 'diff' environment with no required reviewers so it auto-runs; - # gate it later if read-access to stack templates needs approval. - diff: - needs: resolve-targets - if: needs.resolve-targets.outputs.has_targets == 'true' - runs-on: ubuntu-latest - environment: diff - strategy: - matrix: - compute_type: ${{ fromJson(needs.resolve-targets.outputs.matrix) }} - permissions: - id-token: write - contents: read - actions: read - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - - name: Download CDK artifact (${{ matrix.compute_type }}) - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - name: cdk-${{ matrix.compute_type }}-out - path: cdk/ - run-id: ${{ needs.resolve-targets.outputs.run_id }} - github-token: ${{ github.token }} - - - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 - with: - role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} - aws-region: ${{ vars.AWS_REGION }} - - - name: Setup Node.js - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: 22.x - - # Yarn 1 installs this repository and ignores Yarn Berry's --immutable. Its - # own flag, --frozen-lockfile, fails when a dependency of the root - # package.json is not in yarn.lock. It does not notice a changed - # `resolutions` entry or workspace manifest: "Fail on lockfile drift" in - # build.yml catches those. - - name: Install dependencies - run: yarn install --frozen-lockfile - - - name: CDK Diff (full) - env: - COMPUTE_TYPE: ${{ matrix.compute_type }} - run: | - # --method=template: read-only comparison against deployed template; - # no change-set creation, no S3 asset publishing, no deploy role needed. - npx cdk diff --app cdk/cdk.out --all --method=template --no-color 2>&1 | tee cdk-diff-full.txt || true - - - name: CDK Diff (security only) - env: - COMPUTE_TYPE: ${{ matrix.compute_type }} - run: | - echo "## Security Changes (\`$COMPUTE_TYPE\`)" >> "$GITHUB_STEP_SUMMARY" - echo "" >> "$GITHUB_STEP_SUMMARY" - npx cdk diff --app cdk/cdk.out --all --method=template --security-only --no-color 2>&1 | tee cdk-diff-security.txt - if [ -s cdk-diff-security.txt ]; then - echo '```' >> "$GITHUB_STEP_SUMMARY" - cat cdk-diff-security.txt >> "$GITHUB_STEP_SUMMARY" - echo '```' >> "$GITHUB_STEP_SUMMARY" - else - echo "No security-relevant changes detected." >> "$GITHUB_STEP_SUMMARY" - fi - - # Log-delivery migration state, surfaced BEFORE the approval gate. - # - # `mise //cdk:deploy` runs this preflight automatically, but this pipeline calls - # `npx cdk deploy` directly (see the Deploy job) and so inherits none of that task's - # steps. Without this, a pipeline stack still on the pre-#339 library's delivery - # logical ids would roll back mid-update with `AlreadyExists` and nothing anywhere - # would have said why — and the approver would have had no way to know. - # - # --check-only NEVER deletes; it reports and exits 2 when a migration is needed. - # continue-on-error because this is information for the approver, not a gate: the - # job holds the read-only diff role, and a missing `cloudformation:ListStackResources` - # on it must not block the diff that the approval decision depends on. - - name: Log-delivery migration check (read-only) - continue-on-error: true - env: - COMPUTE_TYPE: ${{ matrix.compute_type }} - run: | - echo "## Log-delivery migration (\`$COMPUTE_TYPE\`)" >> "$GITHUB_STEP_SUMMARY" - echo "" >> "$GITHUB_STEP_SUMMARY" - set +e - node --experimental-strip-types cdk/scripts/preflight-log-delivery.ts \ - --check-only 2>&1 | tee preflight-log-delivery.txt - status=${PIPESTATUS[0]} - set -e - echo '```' >> "$GITHUB_STEP_SUMMARY" - cat preflight-log-delivery.txt >> "$GITHUB_STEP_SUMMARY" - echo '```' >> "$GITHUB_STEP_SUMMARY" - if [ "$status" = "2" ]; then - { - echo "" - echo "> [!WARNING]" - echo "> This stack needs the one-time log-delivery migration. Deploying without" - echo "> it fails mid-update with \`AlreadyExists\` and rolls back. This pipeline" - echo "> does **not** migrate automatically — run the documented step first:" - echo "> \`STACK_NAME= mise //cdk:deploy\`, or the manual sequence in" - echo "> docs/design/OBSERVABILITY.md (\"AgentCore log delivery\")." - } >> "$GITHUB_STEP_SUMMARY" - elif [ "$status" != "0" ]; then - echo "" >> "$GITHUB_STEP_SUMMARY" - echo "_Could not determine migration state (exit $status) — see the step log._" \ - >> "$GITHUB_STEP_SUMMARY" - fi - - - name: Upload diff artifacts - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: cdk-diff-${{ matrix.compute_type }} - path: | - cdk-diff-full.txt - cdk-diff-security.txt - preflight-log-delivery.txt - - deploy: - needs: [resolve-targets, diff] - if: needs.resolve-targets.outputs.has_targets == 'true' - runs-on: ubuntu-latest - environment: deploy - concurrency: - group: deploy-${{ matrix.compute_type }} - cancel-in-progress: false - strategy: - matrix: - compute_type: ${{ fromJson(needs.resolve-targets.outputs.matrix) }} - max-parallel: 3 - permissions: - id-token: write - contents: read - actions: read - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - - name: Download CDK artifact (${{ matrix.compute_type }}) - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - name: cdk-${{ matrix.compute_type }}-out - path: cdk/ - run-id: ${{ needs.resolve-targets.outputs.run_id }} - github-token: ${{ github.token }} - - - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 - with: - role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} - aws-region: ${{ vars.AWS_REGION }} - - - name: Install mise - uses: jdx/mise-action@d5574b52816a478f9d4e6529a3f6ff17a8a36785 # v5.2.8 - with: - version: 2026.10.25 # exact mise release for every workflow (#890); bump by PR - cache: true - - - name: Setup Node.js - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: 22.x - - # Yarn 1 installs this repository and ignores Yarn Berry's --immutable. Its - # own flag, --frozen-lockfile, fails when a dependency of the root - # package.json is not in yarn.lock. It does not notice a changed - # `resolutions` entry or workspace manifest: "Fail on lockfile drift" in - # build.yml catches those. - - name: Install dependencies - run: yarn install --frozen-lockfile - - - name: Deploy - env: - COMPUTE_TYPE: ${{ matrix.compute_type }} - # --require-approval never: CDK hard-fails in non-TTY CI without this - # (throws "terminal (TTY) is not attached"). The approval mechanism is the - # GitHub 'deploy' environment gate above — a human must approve before this - # job starts. The 'diff' job surfaces all CloudFormation and security changes - # in the step summary (visible before approval), and the full diff is - # downloadable as an artifact. Defense in depth: - # 1. diff environment (read-only role) → surfaces changes pre-approval - # 2. deploy environment (required reviewers) → human gate - # 3. fork guard (line 14) → blocks untrusted repositories - # 4. OIDC federation → no stored credentials, request-scoped tokens - run: npx cdk deploy --app cdk/cdk.out --all --require-approval never diff --git a/.github/workflows/emulator.yml b/.github/workflows/emulator.yml index 90d032848..6ce2f1a41 100644 --- a/.github/workflows/emulator.yml +++ b/.github/workflows/emulator.yml @@ -8,8 +8,8 @@ name: emulator # job name ("Emulator integration tests") to the ruleset; it already runs on merge_group, # which a required check must do or the merge queue deadlocks (#327). # -# Kept out of build.yml on purpose: deploy.yml and integ.yml start from `workflow_run` on -# build and need its conclusion to be `success`. +# A workflow of its own and not a step of the build job, on purpose: that job is the required +# check `build (agentcore)`, and a red run of this advisory tier must not turn it red. on: pull_request: {} merge_group: {} diff --git a/.github/workflows/integ.yml b/.github/workflows/integ.yml deleted file mode 100644 index d3eb3e254..000000000 --- a/.github/workflows/integ.yml +++ /dev/null @@ -1,325 +0,0 @@ -name: integ - -# Surface the fork and commit under test in the run list and the `deploy` -# environment approval prompt. For workflow_run, GitHub attributes the run to the -# base repo and github.sha is base main, so without this the approver cannot see -# which fork/commit they are authorizing to run with the deploy role — they would -# have to open the resolve job logs. Empty on workflow_dispatch (no workflow_run -# event), which GitHub renders as a bare "integ —"; the manual path is main-only. -run-name: >- - integ — ${{ github.event.workflow_run.head_repository.full_name }}@${{ github.event.workflow_run.head_sha }} - -# Phase-0 deploy-then-verify integration tests (issue #236). integ-runner -# deploys a trimmed Task API stack into the shared account behind -# secrets.AWS_ROLE_TO_ASSUME, runs the create-and-persist smoke assertions, then -# tears the stack down. -# -# Trigger model mirrors deploy.yml: build.yml completes -> workflow_run picks it -# up in the trusted base-repo context (secrets/OIDC available even for fork PRs) -# -> we resolve whether the PR touches cdk/** or agent/** -> an admin approves -# the `deploy` environment gate (reused — same gate and role as deploy.yml) -> -# deploy/assert/destroy runs against the shared account -> a commit status -# `integ-smoke` is posted back to the PR head. -# -# `integ-smoke` is NOT a required status check: the ruleset for `main` requires -# only `build (agentcore)` and `Secrets, deps, and workflow scan`. The status -# informs reviewers; it does not block merge. -# -# Local dev path is unchanged: run `mise //cdk:integ` with your own AWS creds. -# -# Nightly schedule was intentionally dropped (previously 07:00 UTC) — the per-PR -# path plus manual dispatch is the agreed coverage; this is not an oversight. -on: - # zizmor: ignore[dangerous-triggers] — intentional; workflow_run is required so - # fork PRs can run against the shared account (a fork `pull_request` job gets no - # secrets/OIDC). Mitigations: build-success guard, path-filter, fork - # `safe-to-test` label gate, `deploy` environment approval gate (admin reviews - # fork test code before it runs with the deploy role), status-only tokens per - # job. - workflow_run: - workflows: [build] - types: [completed] - workflow_dispatch: {} - -permissions: {} - -jobs: - # Decides whether this PR needs the integ run (touches cdk/** or agent/**) and - # posts the `integ-smoke` status. Always runs on a successful build so - # docs/cli-only PRs get an immediate green (skipped) status instead of none. - resolve: - # Manual dispatch is restricted to main (defence in depth — the `deploy` - # environment approval is the primary gate). PR runs come via workflow_run. - if: >- - (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') || - (github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success') - runs-on: ubuntu-latest - permissions: - statuses: write - pull-requests: read - outputs: - applicable: ${{ steps.decide.outputs.applicable }} - # Load-bearing name: this value is an immutable commit SHA - # (github.event.workflow_run.head_sha), and the checkout below pins to it. - # CodeQL's untrusted-checkout heuristic classifies a checkout `ref` by the - # field name — a name matching /(head|branch|ref)/ is treated as a mutable - # ref (false-positive TOCTOU alert), while /(sha|commit)/ is treated as an - # immutable SHA. Keep this `commit_sha`; renaming it back to `head_sha` - # reintroduces CodeQL alert #35 even though the value is unchanged. - commit_sha: ${{ steps.decide.outputs.commit_sha }} - head_repo: ${{ steps.decide.outputs.head_repo }} - # The PR under test (set only when integ applies); keys the integ job's - # concurrency group so runs of different PRs never cancel each other. - pr_number: ${{ steps.decide.outputs.pr_number }} - steps: - - name: Resolve applicability and post pending status - id: decide - env: - GH_TOKEN: ${{ github.token }} - REPO: ${{ github.repository }} - EVENT_NAME: ${{ github.event_name }} - # Empty for workflow_dispatch. - PR_NUMBER_FROM_EVENT: ${{ github.event.workflow_run.pull_requests[0].number }} - WF_HEAD_SHA: ${{ github.event.workflow_run.head_sha }} - WF_HEAD_REPO: ${{ github.event.workflow_run.head_repository.full_name }} - run: | - set -euo pipefail - - # workflow_dispatch: no PR context — run against the dispatched ref - # (the job's own checkout defaults). Mark applicable, skip status post. - if [[ "$EVENT_NAME" == "workflow_dispatch" ]]; then - echo "applicable=true" >> "$GITHUB_OUTPUT" - echo "commit_sha=${GITHUB_SHA}" >> "$GITHUB_OUTPUT" - echo "head_repo=${REPO}" >> "$GITHUB_OUTPUT" - echo "Manual dispatch — running integ against ${GITHUB_SHA}." - exit 0 - fi - - HEAD_SHA="$WF_HEAD_SHA" - echo "commit_sha=${HEAD_SHA}" >> "$GITHUB_OUTPUT" - echo "head_repo=${WF_HEAD_REPO}" >> "$GITHUB_OUTPUT" - - # Track whether we've posted a terminal integ-smoke status. If the job - # dies (failed API call, runner crash) before reaching one, the EXIT - # trap posts `error` so the status resolves instead of staying pending - # forever. - STATUS_POSTED="" - - post_status() { - # $1=state $2=description - gh api -X POST "repos/$REPO/statuses/$HEAD_SHA" \ - -f context=integ-smoke \ - -f state="$1" \ - -f description="$2" \ - -f target_url="${{ github.server_url }}/$REPO/actions/runs/${{ github.run_id }}" \ - >/dev/null - STATUS_POSTED="yes" - } - - on_exit() { - rc=$? - # Only meaningful in the workflow_run (PR) context and only if we have - # a SHA to post against and haven't already posted a terminal status. - if [[ $rc -ne 0 && -z "$STATUS_POSTED" && -n "${HEAD_SHA:-}" ]]; then - gh api -X POST "repos/$REPO/statuses/$HEAD_SHA" \ - -f context=integ-smoke \ - -f state=error \ - -f description="resolve step failed before gating" \ - -f target_url="${{ github.server_url }}/$REPO/actions/runs/${{ github.run_id }}" \ - >/dev/null 2>&1 || true - fi - } - trap on_exit EXIT - - resolve_pr_number() { - if [[ -n "$PR_NUMBER_FROM_EVENT" ]]; then - echo "$PR_NUMBER_FROM_EVENT" - return - fi - gh api "repos/$REPO/commits/$HEAD_SHA/pulls" --jq '.[0].number // empty' 2>/dev/null || true - } - PR_NUMBER=$(resolve_pr_number) - - if [[ -z "$PR_NUMBER" ]]; then - echo "::warning::No PR resolved for $HEAD_SHA — nothing to gate; skipping." - echo "applicable=false" >> "$GITHUB_OUTPUT" - exit 0 - fi - - # Fork-PR safety: only run fork-authored code after a maintainer has - # applied the `safe-to-test` label (defence in depth on top of the - # `deploy` environment approval). If it's absent, leave the status - # pending and don't run — re-trigger once the label is added. - if [[ "$WF_HEAD_REPO" != "$REPO" ]]; then - if ! LABELS=$(gh api "repos/$REPO/issues/$PR_NUMBER/labels" --jq '.[].name'); then - echo "::error::Failed to read labels for PR #$PR_NUMBER." - exit 1 - fi - if ! echo "$LABELS" | grep -qx 'safe-to-test'; then - post_status pending "awaiting safe-to-test label on fork PR" - echo "applicable=false" >> "$GITHUB_OUTPUT" - echo "Fork PR #$PR_NUMBER lacks safe-to-test label — not running." - exit 0 - fi - fi - - # Path-filter must happen here (not on.pull_request.paths) because the - # trigger is workflow_run. Fail loud on API error: a failed or truncated - # /files response must NOT fall through to a false-green skip. With - # `set -e`, an assignment inside an `if !` condition does not trip - # errexit, so we handle the failure explicitly and let the EXIT trap - # post `error`. - if ! CHANGED=$(gh api "repos/$REPO/pulls/$PR_NUMBER/files" --paginate --jq '.[].filename'); then - echo "::error::Failed to list changed files for PR #$PR_NUMBER." - exit 1 - fi - if echo "$CHANGED" | grep -Eq '^(cdk|agent)/'; then - post_status pending "awaiting admin approval / running" - echo "applicable=true" >> "$GITHUB_OUTPUT" - echo "pr_number=$PR_NUMBER" >> "$GITHUB_OUTPUT" - echo "PR #$PR_NUMBER touches cdk/** or agent/** — integ applies." - else - post_status success "skipped — no cdk/** or agent/** changes" - echo "applicable=false" >> "$GITHUB_OUTPUT" - echo "PR #$PR_NUMBER has no cdk/** or agent/** changes — integ skipped (green)." - fi - - # The admin-gated deploy -> assert -> destroy. The `deploy` environment's - # required reviewers (coding-agents-admin / coding-agents-maintainers) are the - # approval gate; while it waits, the integ-smoke status stays pending (merge is - # not blocked: the status is not required). Reuses deploy.yml's - # environment/role — no separate integ role. - integ: - needs: resolve - if: needs.resolve.outputs.applicable == 'true' - name: CDK integ smoke (Task API) - runs-on: ubuntu-latest - environment: deploy - # One integ deploy at a time per PR. A concurrency group holds one running and - # one waiting job, and a newer job cancels the waiting one even with - # cancel-in-progress: false. With a single shared group, every run waiting for - # the `deploy` approval was cancelled as soon as another PR's build finished - # (#1046). Per PR, only a newer commit of the same PR supersedes a waiting run. - # Stack names are run-unique (`int--`, see below), so runs of - # different PRs do not collide; how many run at once is bounded by the - # `deploy` approval. Manual dispatches (main only) share one group. - # The group is on this job, not on the workflow: at workflow level a run - # waiting for the `deploy` approval held the group and every later run was - # cancelled before `resolve` could post a status. - concurrency: - group: cdk-integ-${{ needs.resolve.outputs.pr_number || 'dispatch' }} - cancel-in-progress: false - timeout-minutes: 45 - permissions: - id-token: write - contents: read - env: - CI: "true" - steps: - - name: Checkout PR head (incl. forks) - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - # Approving the `deploy` environment authorizes this fork-authored test - # code to run with the deploy role — the approver MUST review - # cdk/test/integ/** changes before approving. - repository: ${{ needs.resolve.outputs.head_repo }} - ref: ${{ needs.resolve.outputs.commit_sha }} - persist-credentials: false - - - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 - with: - role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} - # Fall back to us-east-1 if the repo variable is unset, so the action - # never runs region-less (which would fail credential resolution). - aws-region: ${{ vars.AWS_REGION || 'us-east-1' }} - - - name: Install mise - uses: jdx/mise-action@d5574b52816a478f9d4e6529a3f6ff17a8a36785 # v5.2.8 - with: - version: 2026.10.25 # exact mise release for every workflow (#890); bump by PR - cache: true - - - name: Setup Node.js - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: 22.x - - # Yarn 1 installs this repository and ignores Yarn Berry's --immutable. Its - # own flag, --frozen-lockfile, fails when a dependency of the root - # package.json is not in yarn.lock. It does not notice a changed - # `resolutions` entry or workspace manifest: "Fail on lockfile drift" in - # build.yml catches those. - - name: Install dependencies - run: yarn install --frozen-lockfile - - # Teardown: integ-runner forces `cdk destroy` on success and failure (via - # the CDK bootstrap roles, which hold the CloudFormation permissions). No - # raw-CLI safety net here: the GitHub OIDC role has no - # cloudformation:DeleteStack/DescribeStacks, so such a step can only fail - # (#566). If a cancelled/crashed run strands the stack, reclaim is the - # stranded-stack cleanup owned by #400/#72 — and the run-unique name below - # means a stranded stack never blocks a later run. - # - # INTEG_STACK_NAME maps the stack to the commit under test plus the run - # number (`int--`), replacing the single fixed - # `backgroundagent-integ` name. The run number makes same-commit re-runs - # distinct; the `int-` prefix marks it ephemeral for #72's sweep. HEAD_SHA - # is the resolved PR head (or dispatched ref) and RUN_NUMBER is a positive - # integer, so both are already lowercase-alphanumeric — no sanitizing - # needed to stay CloudFormation-valid. - # - # The log of this step first shows integ-runner's snapshot check listing - # the test as NEW and counting it as failed. No snapshot is committed, so - # that is expected on every run and is not a test failure: the task says - # so in the log, and the deploy-then-verify run under "Test Results" - # decides the step (#569). - - name: Run integ tests (deploy → assert → destroy) - env: - HEAD_SHA: ${{ needs.resolve.outputs.commit_sha }} - RUN_NUMBER: ${{ github.run_number }} - run: | - set -euo pipefail - export INTEG_STACK_NAME="int-${HEAD_SHA:0:12}-${RUN_NUMBER}" - echo "Integ stack name: $INTEG_STACK_NAME" - mise //cdk:integ - - # Post the final integ-smoke status back to the PR head so the check flips from - # pending to success/failure. Skipped for workflow_dispatch (no PR to gate). - report: - needs: [resolve, integ] - if: >- - always() && - needs.resolve.result == 'success' && - needs.resolve.outputs.applicable == 'true' && - github.event_name == 'workflow_run' - runs-on: ubuntu-latest - permissions: - statuses: write - steps: - - name: Post final integ-smoke status - env: - GH_TOKEN: ${{ github.token }} - REPO: ${{ github.repository }} - HEAD_SHA: ${{ needs.resolve.outputs.commit_sha }} - INTEG_RESULT: ${{ needs.integ.result }} - run: | - set -euo pipefail - if [[ "$INTEG_RESULT" == "success" ]]; then - STATE=success - DESC="deploy → assert → destroy passed" - elif [[ "$INTEG_RESULT" == "cancelled" ]]; then - # Not a test result: superseded by a newer commit of this PR, or - # cancelled by hand. Leave it visibly unfinished, not failed (#1046). - STATE=pending - DESC="cancelled before it finished; re-run integ for this commit" - else - STATE=failure - DESC="integ run ${INTEG_RESULT}" - fi - gh api -X POST "repos/$REPO/statuses/$HEAD_SHA" \ - -f context=integ-smoke \ - -f state="$STATE" \ - -f description="$DESC" \ - -f target_url="${{ github.server_url }}/$REPO/actions/runs/${{ github.run_id }}" \ - >/dev/null diff --git a/.github/workflows/security-pr.yml b/.github/workflows/security-pr.yml index 816613de6..b47309fe5 100644 --- a/.github/workflows/security-pr.yml +++ b/.github/workflows/security-pr.yml @@ -153,8 +153,8 @@ jobs: if: ${{ !cancelled() }} run: mise run security:gh-actions - # Nothing else builds the agent image before merge (deploy and integ build - # it afterwards), so a broken Dockerfile or lockfile used to pass every + # Nothing else builds the agent image before merge (security.yml builds it + # only weekly), so a broken Dockerfile or lockfile used to pass every # check (#235). Build it here when a file that defines the image differs # between the base commit and this checkout: the Dockerfile, .dockerignore # and the four files the Dockerfile copies by name. Of the directories it diff --git a/.gitignore b/.gitignore index 6d974c96b..01f8cee21 100644 --- a/.gitignore +++ b/.gitignore @@ -67,18 +67,6 @@ cdk.out/ cdk.context.json /assets/ -# integ-runner snapshots: these bundle every Lambda handler asset (~100 MB) and -# are regenerated on each run. CI always deploys-then-verifies (integ-runner -# --force) rather than diffing a committed snapshot, so the snapshot is a build -# artifact, not source. Also catch integ-runner's temp synth dir. -/cdk/test/integ/*.snapshot/ -/cdk/test/integ/cdk-integ.out.*/ - -# ────────────────────────────────────────────── -# CI artifacts (generated during build) -# ────────────────────────────────────────────── -deploy-intent.json - # ────────────────────────────────────────────── # Build outputs (compiled TS → JS) # ────────────────────────────────────────────── diff --git a/.gitleaks.toml b/.gitleaks.toml index bd360196f..94872dfb2 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -64,7 +64,7 @@ keywords = [ ] [[rules.allowlists]] -description = "AWS-published placeholder IDs, localstack default, and lockfiles/snapshots." +description = "AWS-published placeholder IDs, localstack default, and lockfiles." regexes = [ '''123456789012''', '''000000000000''', @@ -72,7 +72,6 @@ regexes = [ '''444455556666''', ] paths = [ - '''(.*/)?test/.*\.snapshot/.*''', '''(.*/)?CHANGELOG\.md$''', '''(.*/)?yarn\.lock$''', '''(.*/)?package-lock\.json$''', diff --git a/cdk/mise.toml b/cdk/mise.toml index 25b51757c..c4f7596d5 100644 --- a/cdk/mise.toml +++ b/cdk/mise.toml @@ -144,16 +144,6 @@ run = "npx tsx scripts/preflight-bootstrap.ts {{arg(name='cdkargs', var=true, re [tasks.deploy] description = "cdk deploy (pass args after --)" -# The pipeline does not run this task. The deploy job of .github/workflows/deploy.yml runs -# `npx cdk deploy` on the assembly that build.yml synthesized, so nothing listed here -# happens there unless the workflow has a step of its own for it (#843): -# :clean:disk local only: it deletes cdk.out, which the pipeline deploys. -# //web:bundle done by the build: synth:quiet depends on it. -# preflight-bootstrap not run by the pipeline (#127). -# preflight-log-delivery reported, not applied: the diff job runs it with --check-only. -# A new entry of `depends` or `run` needs the same decision. -# test/scripts/deploy-workflow.test.ts fails until the entry is recorded there. -# # Reclaim disk first — the agent-image Docker build + CDK asset bundling need # several GB of working space, and uv/Docker caches accumulate across runs. # The operator console stack packages web/dist, so bundle it first. @@ -215,22 +205,6 @@ description = "cdk diff (pass args after --)" depends = ["//web:bundle"] run = "npx cdk diff {{arg(name='cdkargs', var=true, required=false)}}" -[tasks.integ] -description = "CDK deploy-then-verify integration tests (integ-runner). Needs AWS creds for the shared integ account." -depends = [":compile"] -run = [ - "mkdir -p $TMPDIR", - # integ-runner checks snapshots before it deploys, and no option skips that (#569). - # A snapshot left by an earlier local run is compared for real, so the echo does not - # call the check meaningless. mise appends the arguments after `--` to the last - # command, so the echo stays ahead of integ-runner. - "echo 'integ: no snapshot is committed, so on a fresh checkout (every CI run) the snapshot check of integ-runner lists each test as NEW and counts it as failed. That is expected and is not a test failure: --force deploys and verifies every test regardless, and that run is reported under Test Results.'", - # No --update-on-failed: .snapshot/ is gitignored, so there is no committed - # snapshot to diff against or update. --force re-runs the deploy-then-verify - # unconditionally, which is what we want in CI. - "npx integ-runner --language typescript --directory test/integ --force", -] - [tasks.bundle] description = "No-op bundle step for cdk/cdk.json (NodejsFunction bundles at synth time)" run = "node -e \"process.exit(0)\"" diff --git a/cdk/package.json b/cdk/package.json index 97fe923d8..3e873e127 100644 --- a/cdk/package.json +++ b/cdk/package.json @@ -50,8 +50,6 @@ "ws": "^8.22.2" }, "devDependencies": { - "@aws-cdk/integ-runner": "2.206.1", - "@aws-cdk/integ-tests-alpha": "2.276.0-alpha.0", "@cdklabs/eslint-plugin": "^2", "@eslint/js": "10.0.1", "@stylistic/eslint-plugin": "^5", @@ -112,12 +110,10 @@ } }, "coveragePathIgnorePatterns": [ - "/node_modules/", - "/test/integ/" + "/node_modules/" ], "testPathIgnorePatterns": [ - "/node_modules/", - "/test/integ/" + "/node_modules/" ], "watchPathIgnorePatterns": [ "/node_modules/" diff --git a/cdk/scripts/preflight-log-delivery.ts b/cdk/scripts/preflight-log-delivery.ts index 7df35fc55..0bd63a531 100644 --- a/cdk/scripts/preflight-log-delivery.ts +++ b/cdk/scripts/preflight-log-delivery.ts @@ -203,12 +203,11 @@ function resolveStackName(argv: readonly string[]): { stackName: string; source: // Persisted context — what `cdk deploy` would read when no flag is given. try { - // BOTH context files. `cdk.context.json` matters more than it looks: this repo's - // `cdk.json` carries no `context` block at all, so reading only that file made this - // branch dead code — while `.github/workflows/build.yml` writes `stackName` into - // `cdk.context.json` for every pipeline stack (`pr-`). The CI path - // therefore resolved to the default and would have inspected, and deleted from, a - // different stack than the one being deployed. + // BOTH context files, because `cdk deploy` reads both. `cdk.context.json` matters + // more than it looks: this repo's `cdk.json` sets no `stackName`, so with that file + // alone this branch was dead code, and a deploy whose `stackName` is in + // `cdk.context.json` resolved to the default here. The preflight would have + // inspected, and deleted from, a different stack than the one being deployed. // Bare filenames, so the display name IS the path — no `file.replace('../', '')`, // which CodeQL flags as js/incomplete-sanitization (alert #43, HIGH) because a // single-occurrence replace on a path is the shape of broken traversal sanitization. @@ -226,7 +225,7 @@ function resolveStackName(argv: readonly string[]): { stackName: string; source: try { cfg = JSON.parse(readFileSync(new URL(name, contextDir), 'utf8')); } catch { - // An absent context file is the normal case (cdk.context.json is generated, and cdk.json has no context block here), not a failure; the next source is tried and 'default' is the documented floor + // An absent context file is the normal case (cdk.context.json is generated, and cdk.json sets no stackName here), not a failure; the next source is tried and 'default' is the documented floor continue; } // `cdk.context.json` is a flat map; `cdk.json` nests under `context`. diff --git a/cdk/src/constructs/agentcore-azs.ts b/cdk/src/constructs/agentcore-azs.ts index fe0b10df1..a8dd8555d 100644 --- a/cdk/src/constructs/agentcore-azs.ts +++ b/cdk/src/constructs/agentcore-azs.ts @@ -90,14 +90,13 @@ export const AGENTCORE_SUPPORTED_AZ_IDS_SNAPSHOT_DATE = '2026-08-11'; * CDK context key whose value (a JSON array of AZ **names**, e.g. * `["us-east-1b", "us-east-1c"]`) overrides the auto-selected zones. * - * This is the ONLY mechanism that works for an env-agnostic assembly (the - * CI-built artifact `deploy.yml` ships), because auto-pin needs a bound account - * to resolve the name -> zone-ID mapping. Set it in `cdk/cdk.json` `context`, - * through the pipeline's "Generate CDK context" step, or via - * `-c 'agentcore:availabilityZones=["us-east-1b","us-east-1c"]'` at synth time. + * This is the ONLY mechanism that works for an env-agnostic assembly (one + * synthesized without credentials), because auto-pin needs a bound account + * to resolve the name -> zone-ID mapping. Set it in `cdk/cdk.json` `context` or + * via `-c 'agentcore:availabilityZones=["us-east-1b","us-east-1c"]'` at synth time. * - * Note `cdk/cdk.context.json` is gitignored AND regenerated by `build.yml`, so - * it is not a durable place to set this for pipeline deploys. + * Note `cdk/cdk.context.json` is gitignored, so it is not a durable place to + * set this. */ export const AGENTCORE_AZS_CONTEXT_KEY = 'agentcore:availabilityZones'; diff --git a/cdk/test/constructs/agentcore-azs.test.ts b/cdk/test/constructs/agentcore-azs.test.ts index 782d34e2c..e3c79550f 100644 --- a/cdk/test/constructs/agentcore-azs.test.ts +++ b/cdk/test/constructs/agentcore-azs.test.ts @@ -280,9 +280,9 @@ describe('resolveAgentCoreAzs', () => { expect(resolveCallerAccount).not.toHaveBeenCalled(); }); - it('honors the override BEFORE the env-agnostic guard (the CI/CD path)', async () => { + it('honors the override BEFORE the env-agnostic guard', async () => { // Reordering these two checks would silently disable the only pinning - // mechanism the pipeline artifact has. + // mechanism an assembly synthesized without credentials has. const result = await resolveAgentCoreAzs({ node: nodeWithContext({ [AGENTCORE_AZS_CONTEXT_KEY]: ['us-east-1b', 'us-east-1c'] }), account: undefined, diff --git a/cdk/test/integ/integ.task-api-smoke.ts b/cdk/test/integ/integ.task-api-smoke.ts deleted file mode 100644 index 0a25428a2..000000000 --- a/cdk/test/integ/integ.task-api-smoke.ts +++ /dev/null @@ -1,231 +0,0 @@ -/** - * 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. - */ - -/* - * Phase-0 deploy-then-verify smoke test for issue #236. - * - * integ-runner deploys a TRIMMED stack (Task API + the two DynamoDB tables it - * needs) into a real AWS account, then asserts the create-task happy path - * end-to-end: mint a Cognito token, POST /tasks, and confirm the record - * persisted as SUBMITTED. The stack deliberately OMITS the orchestrator and the - * AgentCore runtime/memory, so no agent ever runs — the task simply persists. - * That keeps the test cheap, deterministic, and (critically) free of the - * account-unique AgentCore name collision with the live `backgroundagent-dev` - * stack in the target account. Poll-to-terminal / real agent runs are Phase 1. - */ - -import { randomBytes } from 'node:crypto'; -import { ExpectedResult, IntegTest } from '@aws-cdk/integ-tests-alpha'; -import { App, CfnOutput, PhysicalName, RemovalPolicy, Stack } from 'aws-cdk-lib'; -import type { Construct } from 'constructs'; -import { TaskApi } from '../../src/constructs/task-api'; -import { TaskEventsTable } from '../../src/constructs/task-events-table'; -import { TaskStatus } from '../../src/constructs/task-status'; -import { TaskTable } from '../../src/constructs/task-table'; - -/** - * Trimmed stack: Task API backed by the task + events tables, with no - * onboarding gate (no repoTable) and no orchestrator wiring. A submitted task - * therefore persists at SUBMITTED and is never advanced. - */ -class TaskApiSmokeStack extends Stack { - public readonly taskApi: TaskApi; - public readonly taskTable: TaskTable; - - constructor(scope: Construct, id: string) { - // Environment-agnostic on purpose. integ-runner deploys into whatever - // account/region the active AWS credentials resolve to (the shared account - // that also hosts the live backgroundagent-dev stack). An - // explicit env here would force the IntegTest DeployAssert stack (created - // below without one) into a cross-region reference it cannot - // resolve (CrossRegionReferencesRequireExplicitRegion) when it reads this - // stack's UserPool / API outputs in the assertions below. - super(scope, id, { - description: 'ABCA Phase-0 integ smoke stack (Task API + tables, no orchestrator/agent)', - }); - - // Explicit physical name so the DeployAssert stack (environment-agnostic) - // can read the table cross-environment in the getItem assertion below. - // Without it CDK throws CannotUseCrossEnvironment at synth. - this.taskTable = new TaskTable(this, 'TaskTable', { - tableName: PhysicalName.GENERATE_IF_NEEDED, - removalPolicy: RemovalPolicy.DESTROY, - pointInTimeRecovery: false, - }); - - const taskEventsTable = new TaskEventsTable(this, 'TaskEventsTable', { - removalPolicy: RemovalPolicy.DESTROY, - pointInTimeRecovery: false, - }); - - // No repoTable → onboarding gate disabled (all repos accepted). - // No orchestratorFunctionArn → create-task does not async-invoke anything. - this.taskApi = new TaskApi(this, 'TaskApi', { - taskTable: this.taskTable.table, - taskEventsTable: taskEventsTable.table, - removalPolicy: RemovalPolicy.DESTROY, - }); - - new CfnOutput(this, 'ApiUrl', { value: this.taskApi.api.url }); - new CfnOutput(this, 'UserPoolId', { value: this.taskApi.userPool.userPoolId }); - new CfnOutput(this, 'AppClientId', { value: this.taskApi.appClientId }); - new CfnOutput(this, 'TaskTableName', { value: this.taskTable.table.tableName }); - } -} - -// Stack name is run-unique in CI (`int--`, set by -// integ.yml) so a stranded stack from a cancelled/crashed run never collides -// with — or blocks — a later run under one fixed name. Falls back to a stable -// local name so the `mise //cdk:integ` dev path is unchanged. The `int-` prefix -// keeps it letter-led and the rest is lowercase-alphanumeric + hyphens, so the -// name is CloudFormation-valid. -const app = new App(); -const stackName = process.env.INTEG_STACK_NAME || 'backgroundagent-integ-local'; -const stack = new TaskApiSmokeStack(app, stackName); - -const integ = new IntegTest(app, 'TaskApiSmoke', { - testCases: [stack], - // Left to IntegTest, the assertion stack is named after its construct path alone. Every run would use - // that one name, and two runs in the shared account would work on the same stack. - assertionStack: new Stack(app, `${stackName}-assert`), - // Force teardown on success and failure so a failed assertion never strands - // the stack (and its billable resources) in the shared integ account. - cdkCommandOptions: { - destroy: { args: { force: true } }, - }, -}); - -// A throwaway user the assertions authenticate as. The pool disables -// self-signup, so create + confirm it administratively, then mint a token via -// the USER_PASSWORD_AUTH flow the app client enables. -// -// The password is generated per-synth (not hardcoded) so no credential-shaped -// literal lives in source. It satisfies the Cognito default policy (>=8 chars, -// upper + lower + digit + symbol) by construction: a fixed symbol/case scaffold -// plus 18 bytes of randomness. The user and its pool are destroyed on teardown, -// so the value never outlives a single run. -const username = 'integ-smoke@example.com'; -const password = `Aa1!${randomBytes(18).toString('base64url')}`; - -// Service name MUST be the AWS SDK v2 form 'CognitoIdentityServiceProvider'. -// The assertion provider's normalizeServiceName() lowercases the string and -// resolves it through a v2→v3 client map; only the v2 key maps to the real -// package '@aws-sdk/client-cognito-identity-provider'. Passing the v3-style -// 'CognitoIdentityProvider' falls through unmapped and the provider Lambda -// fails at runtime trying to require the nonexistent -// '@aws-sdk/client-cognitoidentityprovider'. -const cognitoService = 'CognitoIdentityServiceProvider'; - -const createUser = integ.assertions.awsApiCall(cognitoService, 'adminCreateUser', { - UserPoolId: stack.taskApi.userPool.userPoolId, - Username: username, - MessageAction: 'SUPPRESS', - TemporaryPassword: password, -}); - -const setPassword = integ.assertions.awsApiCall(cognitoService, 'adminSetUserPassword', { - UserPoolId: stack.taskApi.userPool.userPoolId, - Username: username, - Password: password, - Permanent: true, -}); - -const auth = integ.assertions.awsApiCall(cognitoService, 'initiateAuth', { - AuthFlow: 'USER_PASSWORD_AUTH', - ClientId: stack.taskApi.appClientId, - AuthParameters: { USERNAME: username, PASSWORD: password }, -}); - -// POST /tasks with the minted ID token. No repoTable means the repo string is -// accepted without an onboarding check; the task persists at SUBMITTED. -// -// NOTE: no inline `.expect()` here. Reading `body.data.task_id` below via -// getAttString() flips this call's `flattenResponse` to true, so its response -// is returned as dotted leaf keys (apiCallResponse.body.data.task_id, …) with -// no nested `apiCallResponse` object. The provider's assertion path then reads -// `result.apiCallResponse` (undefined for a flattened call) and any nested -// objectLike expectation fails with "Expected type object but received -// undefined". HttpApiCall.assertAtPath is a no-op in this alpha, so we cannot -// assert-at-path either. The create is instead verified transitively: the GET -// below returns 200 + SUBMITTED for the returned task_id, and the DynamoDB -// getItem confirms the persisted row — a stronger check than a bare 201. -const createTask = integ.assertions.httpApiCall(`${stack.taskApi.api.url}tasks`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - // Raw ID token, no "Bearer " prefix — matches the API's Cognito authorizer. - 'Authorization': auth.getAttString('AuthenticationResult.IdToken'), - }, - body: JSON.stringify({ - repo: 'aws-samples/sample-autonomous-cloud-coding-agents', - task_description: 'integ smoke: create-and-persist only, no agent run', - max_turns: 1, - }), -}); - -// GET /tasks/{id} returns the persisted record via the API. -const getTask = integ.assertions.httpApiCall( - `${stack.taskApi.api.url}tasks/${createTask.getAttString('body.data.task_id')}`, - { - method: 'GET', - headers: { Authorization: auth.getAttString('AuthenticationResult.IdToken') }, - }, -); -getTask.expect( - ExpectedResult.objectLike({ - status: 200, - body: { data: { status: TaskStatus.SUBMITTED } }, - }), -); - -// Verify the user_id linkage directly in DynamoDB — the API's TaskDetail -// response intentionally omits user_id, so assert it at the source. The value -// is the Cognito sub (unknown at synth time). -// -// The `.+` regex only confirms user_id persisted as a NON-EMPTY string; it does -// not (and cannot, at synth time) check that the value equals this caller's sub. -// The real identity binding is proven transitively by the chain above: the -// authenticated GET /tasks/{id} returns 200 for the same task_id the POST -// created, which means the row was written under, and is readable by, the token -// we minted. This getItem just guards against a regression that writes a blank -// or missing user_id. -const getItem = integ.assertions.awsApiCall('DynamoDB', 'getItem', { - TableName: stack.taskTable.table.tableName, - Key: { task_id: { S: createTask.getAttString('body.data.task_id') } }, -}); -getItem.assertAtPath('Item.user_id.S', ExpectedResult.stringLikeRegexp('.+')); - -// Negative path: an unauthenticated POST /tasks must be rejected by the API's -// Cognito authorizer (401) before any record is created. No getAttString is -// read off this call, so flattenResponse stays false and the inline .expect() -// works against the nested apiCallResponse. -const unauthPost = integ.assertions.httpApiCall(`${stack.taskApi.api.url}tasks`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - repo: 'aws-samples/sample-autonomous-cloud-coding-agents', - task_description: 'this request should be rejected (no auth)', - max_turns: 1, - }), -}); -unauthPost.expect(ExpectedResult.objectLike({ status: 401 })); - -// Chain the calls so they execute in order: create user → set password → auth → -// POST → GET → DynamoDB read → unauthenticated POST (must 401). -createUser.next(setPassword).next(auth).next(createTask).next(getTask).next(getItem).next(unauthPost); diff --git a/cdk/test/main.test.ts b/cdk/test/main.test.ts index 9e80c776a..f970a7000 100644 --- a/cdk/test/main.test.ts +++ b/cdk/test/main.test.ts @@ -82,9 +82,9 @@ describe('buildApp — AgentCore AZ wiring', () => { expect(new Set(azs)).toEqual(new Set(['us-east-1a', 'us-east-1b'])); }); - it('pins from the context override on the env-agnostic (pipeline) path', async () => { - // The assembly deploy.yml ships is synthesized without credentials, so the - // override is the only mechanism available there. + it('pins from the context override on the env-agnostic path', async () => { + // An assembly synthesized without credentials has no account to read the + // zone mapping from, so the override is the only mechanism available there. const built = await buildApp({ account: undefined, region: undefined, diff --git a/cdk/test/scripts/deploy-workflow.test.ts b/cdk/test/scripts/deploy-workflow.test.ts deleted file mode 100644 index fcd32aae1..000000000 --- a/cdk/test/scripts/deploy-workflow.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -/** - * 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 pipeline does not run the `deploy` task of `cdk/mise.toml`. The `deploy` job of `deploy.yml` runs `npx cdk deploy` on -// the assembly that `build.yml` synthesized, so a step added to the task does not run there and nothing says so (#843). - -import * as fs from 'node:fs'; -import * as path from 'node:path'; -import * as yaml from 'js-yaml'; - -const ROOT = path.resolve(__dirname, '../../..'); -const WORKFLOW_FILE = '.github/workflows/deploy.yml'; - -const read = (file: string): string => fs.readFileSync(path.join(ROOT, file), 'utf-8'); - -interface PipelineStep { - readonly job: string; - readonly run: string; -} - -// Where mise puts the arguments after `--`. The table records it with each command, because mise also runs a default -// written in it and whatever follows it. -const ARGS = "{{arg(name='cdkargs', var=true, required=false)}}"; - -/** The comment on `[tasks.deploy]` gives the reason for each entry. */ -const PIPELINE: readonly (readonly [entry: string, step?: PipelineStep])[] = [ - [':clean:disk'], - ['//web:bundle'], - [`npx tsx scripts/preflight-bootstrap.ts ${ARGS}`], - [`node --experimental-strip-types scripts/preflight-log-delivery.ts ${ARGS}`, { job: 'diff', run: 'cdk/scripts/preflight-log-delivery.ts --check-only' }], - [`npx cdk deploy ${ARGS}`, { job: 'deploy', run: 'npx cdk deploy --app cdk/cdk.out' }], -]; - -const isComment = (line: string): boolean => line.trimStart().startsWith('#'); - -const MISE = read('cdk/mise.toml').split('\n'); - -function taskLines(): string[] { - const start = MISE.indexOf('[tasks.deploy]'); - if (start < 0) { - throw new Error('cdk/mise.toml has no task deploy'); - } - const body = MISE.slice(start + 1); - const end = body.findIndex((line) => line.startsWith('[')); - return body.slice(0, end < 0 ? undefined : end); -} - -const TASK = taskLines().filter((line) => line !== '' && !isComment(line)).join('\n'); - -// A sub-table (`[tasks.deploy.env]`) gives the task keys outside its table. TOML reads a header with indentation, with -// spaces around its keys or with quoted keys as the same header. -const SUB_TABLES = MISE.filter((line) => /^\s*\[+\s*(tasks|"tasks"|'tasks')\s*\.\s*(deploy|"deploy"|'deploy')\s*\./.test(line)); - -const STRING_ARRAY = /^(\w+) = \[((?:\s*"[^"\n]*",?)*)\s*\]$/gm; - -const strings = (key: string): string[] => [...TASK.matchAll(STRING_ARRAY)] - .filter(([, name]) => name === key) - .flatMap(([, , array]) => [...array.matchAll(/"([^"\n]*)"/g)].map((match) => match[1])); - -interface Workflow { - jobs: Record; -} - -const WORKFLOW = yaml.load(read(WORKFLOW_FILE)) as Workflow; - -const scripts = (job: string): string[] => (WORKFLOW.jobs[job]?.steps ?? []) - .flatMap((step) => step.run ?? []) - .map((script) => script.split('\n').filter((line) => !isComment(line)).join('\n').replace(/\s*\\\n\s*/g, ' ')); - -const preflights = (text: string): string[] => text.match(/preflight[\w:-]*/g) ?? []; - -describe('the deploy task and the deploy workflow', () => { - test('every dependency and command of the task is recorded with its step in the pipeline', () => { - // A description, then arrays of double-quoted strings (written `[...]` here), are all this test - // reads. A literal string, a task reference or another key could be a step it does not see. - expect([...TASK.replace(STRING_ARRAY, '$1 = [...]').split('\n'), ...SUB_TABLES]).toEqual([ - expect.stringMatching(/^description = "[^"\n]*"$/), - 'depends = [...]', - 'run = [...]', - ]); - // On a failure: decide what the pipeline does for the entry that differs, then record it in - // PIPELINE (with its step in deploy.yml, or without one) and in the comment on [tasks.deploy]. - expect([...strings('depends'), ...strings('run')]).toEqual(PIPELINE.map(([entry]) => entry)); - }); - - test('the comment on the task names the workflow and this test', () => { - const lines = taskLines(); - // Above the commands: a comment below them belongs to the next table. - const note = lines.slice(0, lines.findIndex((line) => line.startsWith('run = '))).filter(isComment).join('\n'); - - expect(note).toContain(WORKFLOW_FILE); - expect(note).toContain(path.relative(path.join(ROOT, 'cdk'), __filename)); - }); - - const recorded = PIPELINE.flatMap(([, step]) => step ?? []); - - test.each(recorded)('exactly one step of the $job job of the workflow runs `$run`', ({ job, run }) => { - expect(scripts(job).filter((script) => script.includes(run))).toHaveLength(1); - }); - - // The other direction, for the checks of the task, which carry `preflight` in the names of their scripts and tasks. - // It holds what the table says of the bootstrap preflight, that the pipeline does not run it (#127). - test('a step of the workflow runs only the preflights that the table records for it', () => { - const unrecorded = Object.keys(WORKFLOW.jobs).flatMap((job) => scripts(job).flatMap((script) => { - const inTable = recorded.filter((step) => step.job === job && script.includes(step.run)).flatMap((step) => preflights(step.run)); - return preflights(script).filter((name) => !inTable.includes(name)).map((name) => `${name} in the ${job} job`); - })); - - // On a failure: a step of the workflow runs a check of the task, and the table records no such - // step. Record it in PIPELINE, and what the pipeline does in the comment on [tasks.deploy]. - expect(unrecorded).toEqual([]); - }); -}); diff --git a/cdk/test/scripts/integ-stack-names.test.ts b/cdk/test/scripts/integ-stack-names.test.ts deleted file mode 100644 index aea0ff14f..000000000 --- a/cdk/test/scripts/integ-stack-names.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -/** - * 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. - */ - -// CI runs share one AWS account and can run at the same time, so the names of both stacks that integ-runner deploys -// come from INTEG_STACK_NAME, which integ.yml sets. A stack with one fixed name is deployed and destroyed by every run. - -import { execFileSync } from 'node:child_process'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { CloudAssembly } from 'aws-cdk-lib/cx-api'; - -const CDK_ROOT = path.resolve(__dirname, '../..'); -const INTEG_APP = path.join(CDK_ROOT, 'test/integ/integ.task-api-smoke.ts'); -const SYNTH_TIMEOUT_MS = 120_000; - -function stackNames(integStackName?: string): string[] { - const outdir = fs.mkdtempSync(path.join(os.tmpdir(), 'abca-integ-names-')); - try { - const { INTEG_STACK_NAME: _inherited, ...env } = process.env; - // `new App()` synthesizes into CDK_OUTDIR when the process exits. The child inherits - // CDK_CONTEXT_JSON from the jest setup file, so it bundles no Lambda code. - execFileSync(process.execPath, ['-r', 'ts-node/register/transpile-only', INTEG_APP], { - cwd: CDK_ROOT, - env: { ...env, CDK_OUTDIR: outdir, ...(integStackName ? { INTEG_STACK_NAME: integStackName } : {}) }, - stdio: 'pipe', - timeout: SYNTH_TIMEOUT_MS, - }); - return new CloudAssembly(outdir).stacksRecursively.map((stack) => stack.stackName).sort(); - } finally { - fs.rmSync(outdir, { recursive: true, force: true }); - } -} - -describe('integ smoke app', () => { - test('names every stack of a CI run from INTEG_STACK_NAME', () => { - expect(stackNames('int-0a1b2c3d4e5f-42')).toEqual(['int-0a1b2c3d4e5f-42', 'int-0a1b2c3d4e5f-42-assert']); - }, SYNTH_TIMEOUT_MS); - - test('keeps one stable name per stack on the local path', () => { - expect(stackNames()).toEqual(['backgroundagent-integ-local', 'backgroundagent-integ-local-assert']); - }, SYNTH_TIMEOUT_MS); -}); diff --git a/cdk/test/scripts/integ-workflow.test.ts b/cdk/test/scripts/integ-workflow.test.ts deleted file mode 100644 index bddcbc053..000000000 --- a/cdk/test/scripts/integ-workflow.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -/** - * 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. - */ - -/** - * Tests for the command the `integ` job in `.github/workflows/integ.yml` runs, and - * for the `integ` task of `cdk/mise.toml` behind it. - * - * mise appends whatever follows `mise //cdk:integ --` to the task's last command, - * `integ-runner`, which exits 1 on an option it does not declare. The job sits - * behind the `deploy` approval gate, so a command that cannot start goes unseen - * until someone approves a run. The workflow test fails, without AWS access, as - * soon as the workflow gives the task anything or runs it a second time; an option - * that is meant to be passed has to be allowed here first. - * - * Same placement rationale as `check-constants-sync.test.ts`: `cdk/test/` is the - * Jest tree that can reach the repository root. - */ - -import * as fs from 'node:fs'; -import * as path from 'node:path'; - -const WORKFLOW = fs.readFileSync(path.resolve(__dirname, '../../../.github/workflows/integ.yml'), 'utf-8'); - -/** What each invocation writes after the task name, continuation lines included. */ -const AFTER_TASK = [...WORKFLOW.matchAll(/^[^#\n]*mise \/\/cdk:integ((?:.*\\\n)*.*)$/gm)].map((match) => match[1]); - -const MISE = fs.readFileSync(path.resolve(__dirname, '../../mise.toml'), 'utf-8').split('\n'); - -function taskCommands(): string[] { - const start = MISE.indexOf('[tasks.integ]'); - const body = MISE.slice(start + 1); - const end = body.findIndex((line) => line.startsWith('[')); - const table = body.slice(0, end < 0 ? undefined : end); - const first = table.indexOf('run = ['); - const last = table.indexOf(']', first); - if (start < 0 || first < 0 || last < 0) { - throw new Error('cdk/mise.toml has no [tasks.integ] with a `run = [` list'); - } - return table.slice(first + 1, last) - .map((line) => line.trim()) - .filter((line) => line !== '' && !line.startsWith('#')) - .map((line) => { - try { - return JSON.parse(line.replace(/,$/, '')) as string; - } catch { - throw new Error(`cdk/mise.toml [tasks.integ]: this test reads one double-quoted string per line, not ${line}`); - } - }); -} - -describe('integ workflow', () => { - test('runs the integ task once, with nothing after it', () => { - expect(AFTER_TASK).toEqual(['']); - }); -}); - -describe('integ task', () => { - // No snapshot is committed, so integ-runner lists every test as NEW and counts it as failed before it deploys anything. - // In the job log that reads as a failed run (#569). - test('says that a NEW snapshot is not a test failure, then runs integ-runner with --force', () => { - const [notice, runner] = taskCommands().slice(-2); - - // One single-quoted literal without apostrophe, backslash or brace. sh prints it as written, and mise's template - // engine finds nothing to render. Anything else could stop the task ahead of the deploy. - expect(notice).toMatch(/^echo 'integ: [^'\\{}]*'$/); - // The lines it is about, in the words integ-runner prints, and what it says of them. - for (const phrase of ['snapshot check', 'NEW', 'failed', 'not a test failure', '--force', 'Test Results']) { - expect(notice).toContain(phrase); - } - // mise appends the arguments after `--` to the last command only, and what the - // notice says about --force holds only while that command passes the flag. - expect(runner.split(' ').slice(0, 2)).toEqual(['npx', 'integ-runner']); - expect(runner.split(' ')).toContain('--force'); - }); -}); diff --git a/cdk/test/scripts/preflight-log-delivery.test.ts b/cdk/test/scripts/preflight-log-delivery.test.ts index 46e0d0491..95016c0c9 100644 --- a/cdk/test/scripts/preflight-log-delivery.test.ts +++ b/cdk/test/scripts/preflight-log-delivery.test.ts @@ -136,10 +136,10 @@ function runPreflight(opts: { // Context files come from the scratch root via ABCA_PREFLIGHT_CONTEXT_DIR, NOT the real // `cdk/` directory. Two reasons, both learned the hard way: // - // - whether a real `cdk.context.json` exists is an ENVIRONMENT fact. Locally it usually - // does not; CI's `build.yml` writes `{"stackName":"pr-"}` into it before - // the test job. Reading it made every test expecting the DEFAULT stack resolve to the - // pipeline's stack — green locally, two failures in CI. + // - whether a real `cdk.context.json` exists, and what it holds, is an ENVIRONMENT fact: + // the CDK CLI keeps its lookups there, and a `stackName` can be set in it. Reading it + // made every test expecting the DEFAULT stack resolve to that stack — green on a + // checkout without the file, two failures on one that had it. // - the real file is CDK's lookup cache, shared with every suite jest runs in PARALLEL. // Writing or deleting it from here raced the stack-synth tests: 73 failures, from a // cached availability-zone lookup disappearing mid-synth. @@ -389,12 +389,11 @@ describe('preflight-log-delivery', () => { expect(r.stderr).toContain('no physical id'); }); - test('resolves the stack from cdk.context.json — the file the CI pipeline writes', () => { + test('resolves the stack from cdk.context.json, which `cdk deploy` reads too', () => { // Mutation-caught gap: removing `cdk.context.json` from the resolution chain left the - // whole suite green. It is the load-bearing source in CI — `build.yml` writes - // `stackName` there for every pipeline stack (`pr-`), and this repo's - // `cdk.json` has NO `context` block at all, so reading only `cdk.json` meant the - // pipeline resolved to the default and would have inspected the wrong stack. + // whole suite green. `cdk deploy` takes `stackName` from that file as well, and this + // repo's `cdk.json` sets none, so reading only `cdk.json` meant that a deploy whose + // stack is named there resolved to the default here and inspected the wrong stack. const r = runPreflight({ listResponse: LIBRARY_IDS, cdkContext: { stackName: 'pr705-agentcore' }, diff --git a/cdk/test/scripts/workflow-installs.test.ts b/cdk/test/scripts/workflow-installs.test.ts index 9dbd3a799..8c7af8296 100644 --- a/cdk/test/scripts/workflow-installs.test.ts +++ b/cdk/test/scripts/workflow-installs.test.ts @@ -39,16 +39,20 @@ const installs = (file: string): Install[] => fs.readFileSync(path.join(ROOT, fi return at < 0 ? [] : [{ file, command: line.slice(at) }]; }); -const WORKFLOW_INSTALLS = fs.readdirSync(path.join(ROOT, WORKFLOWS)) +const WORKFLOW_FILES = fs.readdirSync(path.join(ROOT, WORKFLOWS)) .filter((name) => /\.ya?ml$/.test(name)) .sort() - .flatMap((name) => installs(`${WORKFLOWS}/${name}`)); + .map((name) => `${WORKFLOWS}/${name}`); + +const WORKFLOW_INSTALLS = WORKFLOW_FILES.flatMap(installs); const MISE_INSTALLS = ['mise.toml', 'cdk/mise.toml', 'cli/mise.toml', 'docs/mise.toml', 'web/mise.toml'].flatMap(installs); describe('workflow steps that run `yarn install` themselves', () => { + // No workflow has such a step at present, so the rule is for the next one. + // The first assertion shows that the workflows were listed: without it the rule would pass on an empty list. test('pass --frozen-lockfile, the flag Yarn 1 reads, and nothing else', () => { - expect(WORKFLOW_INSTALLS).not.toHaveLength(0); + expect(WORKFLOW_FILES).toContain(BUILD); expect(WORKFLOW_INSTALLS.filter(({ command }) => command !== 'yarn install --frozen-lockfile')).toEqual([]); }); }); diff --git a/contracts/coverage-thresholds.json b/contracts/coverage-thresholds.json index d263e1185..4cbf51001 100644 --- a/contracts/coverage-thresholds.json +++ b/contracts/coverage-thresholds.json @@ -13,8 +13,7 @@ "scripts/generate-bootstrap-template.ts" ], "coveragePathIgnorePatterns": [ - "/node_modules/", - "/test/integ/" + "/node_modules/" ], "coverageThreshold": { "global": { @@ -25,8 +24,7 @@ } }, "testPathIgnorePatterns": [ - "/node_modules/", - "/test/integ/" + "/node_modules/" ] }, "cli": { diff --git a/docs/abca-plugin/skills/deploy/SKILL.md b/docs/abca-plugin/skills/deploy/SKILL.md index fa35407da..699e18493 100644 --- a/docs/abca-plugin/skills/deploy/SKILL.md +++ b/docs/abca-plugin/skills/deploy/SKILL.md @@ -48,7 +48,7 @@ Deploy and update with `bgagent setup`. It reads the stack's deployed features, - **Never pass `--accept-data-loss`.** If setup refuses because the change would delete state-bearing resources (tables, secrets, buckets), stop. Tell the user what would be removed, and ask them to run `node lib/bin/bgagent.js setup` themselves in a terminal, where they confirm by typing the stack name. 3. To change code without changing features, run the same command with the stack's current features. -Use `mise //cdk:deploy -- --require-approval never` only when the user asks for it explicitly (for example, to reproduce CI). It applies `abca.deployment.json` if that file exists, and otherwise deploys every optional feature. +Use `mise //cdk:deploy -- --require-approval never` only when the user asks for it explicitly. It applies `abca.deployment.json` if that file exists, and otherwise deploys every optional feature. After a successful deployment, retrieve and display stack outputs: ```bash diff --git a/docs/decisions/ADR-013-tiered-validation-pyramid.md b/docs/decisions/ADR-013-tiered-validation-pyramid.md index 8cb0f9404..9f77d658e 100644 --- a/docs/decisions/ADR-013-tiered-validation-pyramid.md +++ b/docs/decisions/ADR-013-tiered-validation-pyramid.md @@ -2,14 +2,14 @@ **Status:** proposed **Date:** 2026-05-19 -**Last-updated:** 2026-11-21 +**Last-updated:** 2026-11-24 ## Context The current validation architecture has two operational tiers: - **Pre-commit hooks** — formatting, secrets scan, and the lint and drift checks of the staged files -- **Remote CI** (5–20 min) — full build, test, synth, security scans, deploy verification +- **Remote CI** (5–20 min) — full build, test, synth, security scans, deploy verification (CI no longer deploys; see the note under Tier 3) The gap between these tiers is significant. When an agent (or human) makes a change that passes pre-commit but fails in CI, the feedback loop is: @@ -33,7 +33,7 @@ The root cause: there is no **Tier 2** — a local, fast, high-fidelity validati |------|------|-----------------|-----| | Pre-commit (Tier 0) | No fixed budget: by what is staged (measured times under Tier 0 below) | Formatting, secrets, lint and drift checks of the staged files | None — works well | | mise build (Tier 1) | 30–90s | Compile, unit tests, CDK synth, docs sync, linting | Wired as a pre-push gate (prek `pre-push` hooks run tests + security); the `mise run build` superset is available on demand | -| Remote CI (Tier 3) | 5–20 min | Full matrix, security, E2E, deploy | Authoritative but slow | +| Remote CI (Tier 3) | 5–20 min | The full build (lint, type checks, tests, synth, docs) and the security scans; the Tier 2a tests as an advisory check | Authoritative but slow. Makes no AWS call: nothing is deployed or verified in a real account | | **Local integration (Tier 2)** | About half a minute for phase 2a, on a laptop | Phase 2a only: how real handler, CLI and agent code behaves against emulated DynamoDB, S3, Secrets Manager, Cognito, STS and CloudWatch Logs | Phase 2a is an advisory check, not a required one; phases 2b–2d do not exist | ### Agentic-first motivation @@ -133,21 +133,9 @@ Progressive build-out: - Documentation mutation check (fail if Starlight mirrors are stale) - The Tier 0 file checks (whitespace, end of file, conflict markers, YAML/JSON syntax) over all tracked files (`mise run check:hygiene`, part of `mise run build`) and shellcheck over every shell script (`mise run check:shell`, also part of `mise run build`): a commit made without the hooks skips Tier 0 -Status: **Implemented** (GitHub Actions). This remains the authoritative gate for merge. +Status: **Implemented** (GitHub Actions), except the items that need an AWS account (see the note below). This remains the authoritative gate for merge. -> **Deployed runtime E2E — Phase 0 landed (issue #236).** `@aws-cdk/integ-tests-alpha` + `integ-runner` provide deploy-then-verify coverage: `mise //cdk:integ` deploys a trimmed Task API stack to a real account, asserts the create-and-persist happy path (task persists at `SUBMITTED`), then tears it down. In CI (`.github/workflows/integ.yml`) it is triggered per-PR via `workflow_run` only when the diff touches `cdk/**` or `agent/**` (docs/cli-only PRs get an immediate green skip), runs behind the reused `deploy` environment's admin-approval gate so it never assumes the deploy role unattended, and posts an `integ-smoke` status that is not required: the ruleset for `main` requires only `build (agentcore)` and `Secrets, deps, and workflow scan`, so the status informs reviewers and does not block merge. Because it is path-filtered and admin-gated it does not slow non-infra PRs. `workflow_dispatch` is retained for manual runs against `main`. Phase 1 (full lifecycle / real agent runs) and Phase 2 (channels) are follow-ups. - -#### Residual risk acceptance — fork PR integ execution - -The deployed E2E gate runs **fork-authored test code** (`cdk/test/integ/**`) against the shared AWS account. This is intentional: a fork `pull_request` job gets no secrets/OIDC, so the `workflow_run` trigger is the only way to give fork PRs the same deploy-verify coverage that branch PRs get. The accepted risk is that fork code executes with the shared `GitHub` deploy role (reused from `deploy.yml`), which is capable of CloudFormation operations in the shared account. - -Mitigations layered against that risk: - -- **Two human gates before fork code runs.** The `resolve` job requires a maintainer-applied `safe-to-test` label on fork PRs, and the `integ` job requires explicit approval of the `deploy` GitHub environment (required reviewers: `coding-agents-admin` / `coding-agents-maintainers`, self-review prevented). The approver MUST review `cdk/test/integ/**` changes before approving. -- **Environment reuse over a dedicated role.** Phase 0 reuses `deploy.yml`'s existing `deploy` environment and `GitHub` deploy role rather than provisioning a separate least-privilege role — the environment and its OIDC trust are already configured, so no account-side IAM change is needed to go live. The tradeoff is that integ (including approved fork code) runs with the full deploy role; the human gates above and forced teardown below are the compensating controls. Scoping a dedicated least-privilege integ role remains an option a maintainer can adopt later if the blast radius is judged too wide. -- **Status-only tokens and forced teardown.** Each job gets minimal `permissions`; the report path only posts commit statuses, and teardown runs `if: always()` with a fail-loud `wait` so a stranded stack surfaces rather than leaking billable resources. - -Residual risk after these mitigations (a malicious fork PR that passes maintainer review and operates strictly within the scoped stacks) is **accepted** for Phase 0. +> **Nothing is deployed to AWS from CI.** No workflow uses an AWS account, so the items of this list that need one (CDK diff against deployed stack, multi-account deployment verification, E2E tests against real AWS services) do not run in CI. The ruleset for `main` requires `build (agentcore)` and `Secrets, deps, and workflow scan`; the `emulator` workflow runs the Tier 2a tests beside them as an advisory check. No automated test of a deployed stack exists: the Phase 0 smoke of deployed runtime E2E (issue #236, `mise //cdk:integ`: a trimmed Task API stack deployed to a real account, asserted and torn down) was removed with the workflow that ran it. A deployed stack is checked by hand only: the live acceptance of the Lambda MicroVM backend (`scripts/microvm-acceptance.sh`) and `bgagent platform doctor`. Deployed runtime E2E, from Phase 0 on, is a follow-up. ### Enforcement model @@ -240,3 +228,4 @@ Escape hatches must be explicit (noted in PR description, not silent). - 2026-11-15 — Phase 2a is implemented, on the AWS Emulator instead of LocalStack, as an advisory check (`mise run test:integration` and the `emulator` workflow). Replaced the estimate that it would eliminate "60%+ of CI-only failures" with what was measured, added the graduation criteria this ADR asks for, and stated that phase 2c needs a real AWS account because the emulator cannot show a missing permission (decision otherwise unchanged). - 2026-11-20 — Tier 0 also runs the type check of cdk, cli and web when one of their TypeScript files is staged (#260). The build runs the same checks and stays the gate (decision unchanged). - 2026-11-21 — Tier 0 also runs shellcheck when a shell script is staged (#278). The build and the security suite run the same check over every shell script (decision unchanged). +- 2026-11-24 — The `deploy` and `integ` workflows were removed as unused; the Tier 2a tests are the integration check that CI runs. CI now makes no AWS call: Tier 3 no longer deploys, compares against a deployed stack or tests in a real account. The manual task `mise //cdk:integ` and its smoke test went with the `integ` workflow: nothing ran it any more, and no run of it in CI had completed since the workflow's call of it was repaired (#1048). Removed the section "Residual risk acceptance — fork PR integ execution": the risk it accepted, fork-authored test code running with the deploy role, ended with the `integ` workflow (decision unchanged). diff --git a/docs/design/CI_BUILD_PERFORMANCE.md b/docs/design/CI_BUILD_PERFORMANCE.md index 35a00728f..dc31a5ba1 100644 --- a/docs/design/CI_BUILD_PERFORMANCE.md +++ b/docs/design/CI_BUILD_PERFORMANCE.md @@ -138,7 +138,7 @@ build (agentcore) (needs: build-shard) # single required context; always r # fails if any shard failed ``` -- The matrix job (`build-shard`) runs `jest --shard=${{ matrix.shard }}/N` and uploads its `cdk.out` / coverage artifacts. +- The matrix job (`build-shard`) runs `jest --shard=${{ matrix.shard }}/N` and uploads its coverage artifact. - The aggregate job keeps the `compute_type: [agentcore]` matrix so it emits the required **`build (agentcore)`** context (one stable name regardless of shard count). Its gate must use GitHub's documented pattern: **`if: ${{ always() }}` on the job, with the pass/fail decision moved into a step.** `contains()` is **not** one of GitHub's four status-check functions (`success()`, `always()`, `cancelled()`, `failure()`), so a bare `if: ${{ contains(needs.*.result, 'failure') }}` silently becomes `success() && contains(needs.*.result, 'failure')` — a contradiction that **never runs on either outcome**, admitting failing shards once it is the required context: ```yaml @@ -160,7 +160,6 @@ build (agentcore) (needs: build-shard) # single required context; always r ### Open design questions for the implementer - **Synth + non-test tasks:** `//cli:*`, `//docs:build`, `//agent:quality` finish early (~74–83s) and are easy to keep off the critical path. **`//cdk:synth:quiet` is different** — at +142s it is the *next binding constraint* (see [How the time is spent](#how-the-time-is-spent)), so wherever it runs (aggregate job, a dedicated job, or shard 1) it, not the sharded suite, sets the new floor. Decide its placement deliberately and measure against ~142s, not the suite. -- **Artifact strategy:** the deploy pipeline consumes `cdk-agentcore-out`. Sharding test execution should not change synth output; ensure exactly one job still produces the deploy artifact. - **Shard balance:** `--shard` partitions by file count, not by runtime. A few heavy suites (full `App` + cdk-nag synth) can skew one shard. If imbalance is material, consider ordering/grouping heavy suites or a runtime-aware splitter; measure first. ## Measurement protocol diff --git a/docs/design/OBSERVABILITY.md b/docs/design/OBSERVABILITY.md index 1e641e870..dcfe63969 100644 --- a/docs/design/OBSERVABILITY.md +++ b/docs/design/OBSERVABILITY.md @@ -501,7 +501,7 @@ Fresh deployments need nothing here. A stack whose live delivery resources alrea A stack still on older ids has to converge, and because the create-before-delete collision above applies, the old resources must be gone before the new ones are created. -**`mise //cdk:deploy` handles this automatically** (the CI pipeline reports it but does not migrate — see the deployment guide's known-issues entry)**.** The deploy task runs a preflight (`cdk/scripts/preflight-log-delivery.ts`) that reads the stack's own resource list and, only when it finds delivery resources under the retired pinned ids (a `CDKSource` or `CdkLogGroup` segment in the logical id), deletes exactly those before the deploy proceeds. It deletes by the physical ids CloudFormation reports for *this stack*, so other delivery configurations in the account — even on a shared account — are unreachable by construction. Already-migrated stacks and fresh installs pass through untouched, so the preflight is safe to leave on every deploy. +**`mise //cdk:deploy` handles this automatically.** The deploy task runs a preflight (`cdk/scripts/preflight-log-delivery.ts`) that reads the stack's own resource list and, only when it finds delivery resources under the retired pinned ids (a `CDKSource` or `CdkLogGroup` segment in the logical id), deletes exactly those before the deploy proceeds. It deletes by the physical ids CloudFormation reports for *this stack*, so other delivery configurations in the account — even on a shared account — are unreachable by construction. Already-migrated stacks and fresh installs pass through untouched, so the preflight is safe to leave on every deploy. **Which stacks are affected is a property of deployed state, not of the stack's name.** The legacy ids are the *previous library's* naming, not a product of the pin table: `#339` (`9a58797c`, 2026-06-13) switched the stack from `@aws-cdk/aws-bedrock-agentcore-alpha` to `aws-cdk-lib/aws-bedrockagentcore`, and the pin table only landed seven weeks later in `#695` (`4357c353`, 2026-08-03). The alpha generated the `RuntimeCDKSource…` / `RuntimeCdkLogGroup…` shapes; `aws-cdk-lib` generates `RuntimeApplicationLogsDeliverySource`. @@ -530,7 +530,7 @@ ABCA_SKIP_LOG_DELIVERY_PREFLIGHT=1 mise //cdk:deploy **A non-default stack needs the name given twice, and the two are not interchangeable.** `cdk deploy` selects its stack from `stackName` CDK *context*, while the preflight reads `STACK_NAME` (or `--stack-name`, or `stackName` in `cdk.json` context). Arguments after `--` are appended to the `cdk deploy` command and never reach a mise `depends` task, so `-c stackName=x` alone leaves the preflight on its default target — and `STACK_NAME=x` alone leaves the *deploy* on its default target. Setting only one is how you end up migrating one stack while deploying another. -This is now closed rather than merely documented: the preflight runs as the first command of the `deploy` task, so the arguments after `--` reach it and `cdk deploy` alike, and `--profile` / `--region` are forwarded to its own AWS calls. It also reads `cdk.context.json` (the file the CI pipeline writes `stackName` into), not just `cdk.json`. +This is now closed rather than merely documented: the preflight runs as the first command of the `deploy` task, so the arguments after `--` reach it and `cdk deploy` alike, and `--profile` / `--region` are forwarded to its own AWS calls. It also reads `cdk.context.json`, not just `cdk.json`. If the stack name still resolves from the built-in default *while arguments were supplied*, the preflight refuses to delete rather than guess — the case that would otherwise migrate one stack's delivery resources while deploying another, leaving the first one's agent logging dark until it is deployed itself. Every run prints the stack, where the name came from, and the account and region it resolved to: @@ -562,7 +562,7 @@ Agent sessions run for up to 8 hours. CDK deployments replace Lambda functions, - **Drain before deploy** - Pre-deploy check for active tasks. Warn or block if tasks are running. - **Durable execution resilience** - Lambda Durable Functions checkpoints are stored externally. A replaced Lambda can resume from its last checkpoint. - **Consistency recovery** - If a deploy interrupts a running orchestrator, the `ConcurrencyReconciler` Lambda (every 15 minutes) corrects the concurrency counter. (This is distinct from the stranded-task reconciler, a separate Lambda that runs every 5 minutes to fail tasks whose pipeline never started.) The stuck task alarm fires and triggers manual finalization. -- **Blue-green deployment** - CI/CD pipeline uses blue-green for the orchestrator Lambda, with automatic rollback if error rates increase. +- **Blue-green deployment (planned, not implemented)** - Blue-green for the orchestrator Lambda, with automatic rollback if error rates increase. No workflow deploys ABCA today. ## Account prerequisites diff --git a/docs/guides/DEPLOYMENT_GUIDE.md b/docs/guides/DEPLOYMENT_GUIDE.md index d5c51b763..b2af72cb5 100644 --- a/docs/guides/DEPLOYMENT_GUIDE.md +++ b/docs/guides/DEPLOYMENT_GUIDE.md @@ -25,7 +25,7 @@ Without `compute_types`, legacy `compute_type=ecs` or `compute_type=lambda-micro `networkTopology=inline` is the default. Use `networkTopology=split` for a new environment to put the VPC, subnets, endpoints, flow logs and DNS firewall in `${stackName}-network`. The application stack retains its name, data stores, compute resources and shared Task API. It depends on network exports, so CDK deploys the network first. The complete VPC/subnet/security-group export set stays present across compute-backend changes. Keep the same topology context on subsequent synth, diff and deploy commands. -Every local and pipeline synthesis enforces a **490-resource ceiling per parent or nested template**, including operator configurations outside the census. CDK fails synthesis with the stack name, resource count and ceiling when a template exceeds it. `@aws-cdk/core:stackResourceLimit` accepts a stricter integer from 1 to 490, as either a JSON number or CLI string; it cannot raise the production ceiling. +Every synthesis, local or in the CI build, enforces a **490-resource ceiling per parent or nested template**, including operator configurations outside the census. CDK fails synthesis with the stack name, resource count and ceiling when a template exceeds it. `@aws-cdk/core:stackResourceLimit` accepts a stricter integer from 1 to 490, as either a JSON number or CLI string; it cannot raise the production ceiling. The budget covers complete configurations, including multiple backends, Gateway, Registry, the Linear vault, managed MicroVM images, alert email, a fork Blueprint, explicit three-zone pins and expanded model allowlists. With the approval, maintenance and MicroVM subsystems in nested stacks, every sampled combination fits inline (the widest is all three backends with every option, on two zones with the default model allowlist); split reduces the application template further. The budget guard never changes topology automatically. The [offline census](./DEVELOPER_GUIDE.md#stack-decomposition-and-synthesis-budgets) reports counts for each supported profile. @@ -165,7 +165,7 @@ Before it runs `cdk deploy`, `mise //cdk:deploy` compares the outputs of the `CD `mise //cdk:preflight` runs the same check on its own. It is read-only. It needs the AWS CLI on `PATH` and no permission beyond `cloudformation:DescribeStacks`. Arguments after `--` are those of the deploy (`--profile`, `--region`, `-c compute_types=...`), plus `--json` for CI. -The compute backends the preflight checks are those of the `compute_types` (or `compute_type`) context, from `-c` arguments and `cdk/cdk.json`. A backend that only the `compute` list of a [deployment profile](#profile-file-and-precedence) selects is not checked. A bare `cdk deploy` and the GitHub Actions pipeline do not run the preflight. +The compute backends the preflight checks are those of the `compute_types` (or `compute_type`) context, from `-c` arguments and `cdk/cdk.json`. A backend that only the `compute` list of a [deployment profile](#profile-file-and-precedence) selects is not checked. A bare `cdk deploy` does not run the preflight. | Result | When | What to do | |---|---|---| @@ -236,11 +236,11 @@ The wizard works in this order: - Your confirmation replaces CDK's own IAM approval prompt; the change summary says how many IAM roles and policies are included. - On success it configures the CLI from the stack outputs and prints next steps, in the same command form you launched setup with. A new installation lists storing a GitHub token, creating a user, signing in and onboarding a repository. Any Slack, Linear or Jira feature added by this run lists its own setup command. If the CLI was previously signed in to another stack's user pool, the cached tokens are removed; run `bgagent login` again. On failure it names the failed component and CloudFormation's reason, and keeps your selection so you can rerun. -`--no-deploy` writes the profile without a diff. If it removes a stateful feature from an existing stack, it asks for the same data-loss confirmation, because the next `mise //cdk:deploy` or CI deploy applies the removal with no wizard in the loop. +`--no-deploy` writes the profile without a diff. If it removes a stateful feature from an existing stack, it asks for the same data-loss confirmation, because the next `mise //cdk:deploy` applies the removal with no wizard in the loop. -Commit `abca.deployment.json`. Each additional deployment from the same checkout gets its own `abca.deployment..json`, so deploying one never changes another's features. Synthesis uses only the file matching `-c stackName=…`: the default stack `backgroundagent-dev` uses `abca.deployment.json`, and any other stack without its own file keeps the legacy topology rather than inheriting the default stack's features. +Commit `abca.deployment.json`. Each additional deployment from the same checkout gets its own `abca.deployment..json`, so deploying one never changes another's features. Synthesis uses only the file matching `-c stackName=…`: the default stack `backgroundagent-dev` uses `abca.deployment.json`, and any other stack without its own file keeps the legacy topology rather than inheriting the default stack's features. Every synthesis reads the profile, including `mise //cdk:synth`, `mise //cdk:deploy` and the CI build. -Deployments in one account share only the CDK bootstrap, with one exception: Bedrock model-invocation logging is an account-wide setting, configured by whichever deployment was deployed last. Every synthesis reads it, including `mise //cdk:synth`, `mise //cdk:deploy` and the CI build, so local and pipeline deployments match. +Deployments in one account share only the CDK bootstrap, with one exception: Bedrock model-invocation logging is an account-wide setting, configured by whichever deployment was deployed last. ### Profile file and precedence @@ -279,7 +279,7 @@ CLI commands for an omitted feature (for example `bgagent slack setup`) fail wit ### Regional availability -`contracts/deployment-capabilities.json` records the services each capability needs, the Regions that support it, and the source and date of the last verification. Its `compute` section lists the compute backends in the same way; Lambda MicroVMs is the only Region-limited one. `source` and `lastVerified` describe core and the features only: the Lambda MicroVMs Regions come from the launch list of [ADR-021](../decisions/ADR-021-lambda-microvms-compute-backend.md#regional-availability-enforcement) (2026-06-22). CDK synthesis enforces the catalog for a concrete Region, so a CI or manual deploy fails before CloudFormation runs, not only in the wizard. Environment-agnostic synthesis is not checked. +`contracts/deployment-capabilities.json` records the services each capability needs, the Regions that support it, and the source and date of the last verification. Its `compute` section lists the compute backends in the same way; Lambda MicroVMs is the only Region-limited one. `source` and `lastVerified` describe core and the features only: the Lambda MicroVMs Regions come from the launch list of [ADR-021](../decisions/ADR-021-lambda-microvms-compute-backend.md#regional-availability-enforcement) (2026-06-22). CDK synthesis enforces the catalog for a concrete Region, so a deploy made without the wizard also fails before CloudFormation runs. Environment-agnostic synthesis is not checked. A Region listed in the catalog has the required services; the list says nothing more. It includes `us-gov-west-1` for the core platform, but ABCA's least-privilege bootstrap, which `bgagent setup` installs when the account and Region have no `CDKToolkit` stack, covers the commercial `aws` partition only and cannot deploy ABCA in another one. See [DEPLOYMENT_ROLES.md](../design/DEPLOYMENT_ROLES.md#using-these-policies). @@ -434,44 +434,19 @@ At public US East (N. Virginia) first-tier list rates verified in August 2026, t ## Reference -## CI/CD pipeline (`deploy.yml`) +## Continuous integration -The repository includes a two-stage CI/CD pipeline: +No workflow of this repository deploys ABCA or uses an AWS account. A deployment is made from a checkout, with your own credentials: run [`bgagent setup`](#choosing-features-with-bgagent-setup), or `mise //cdk:deploy` on an account you have [bootstrapped](#bootstrap-with-least-privilege). -### Stage 1: Build (`build.yml`) +Three workflows check the code of every pull request and merge-queue entry: -Triggers on every pull request and merge-queue entry, and on manual dispatch. Runs `mise run build` (what it covers is listed under [Pull request](../../CONTRIBUTING.md#5-pull-request) in CONTRIBUTING.md) and uploads the synthesized `cdk.out/` together with a `deploy-intent` artifact. The intent file declares whether a deploy should happen and for which compute types. +| Workflow | What it runs | Required to merge | +|----------|--------------|-------------------| +| `build` | `mise run build`; [Pull request](../../CONTRIBUTING.md#5-pull-request) in CONTRIBUTING.md lists what it covers. Its CDK synthesis runs without credentials, and the output is not deployed | Yes | +| `security-pr` | The secret, static-analysis (Semgrep), dependency and workflow scans, and a build of the agent image when a file that defines it changed | Yes | +| `emulator` | The integration tests: ABCA's real handler, CLI and agent code against the AWS Emulator in a container, with no AWS account. [scripts/aws-emulator/README.md](../../scripts/aws-emulator/README.md) says where a green run can be trusted | No | -### Stage 2: Deploy (`deploy.yml`) - -Triggers via `workflow_run` when `build.yml` completes successfully. The pipeline: - -1. **Skips fork PRs** — `head_repository.full_name == github.repository` prevents forks from entering the deploy flow. This is a security measure: an untrusted fork could modify `build.yml` to produce a deploy-intent artifact, which would otherwise prompt maintainers for approval unnecessarily. -2. **Downloads `deploy-intent.json`** from the triggering build run. -3. **Resolves targets** — Determines which compute types to deploy: - - `intent: "-"` → no-op (most PRs) - - `intent: "labels"` → reads PR labels against an allowlist - - `intent: ""` → deploys the specified type (e.g., `agentcore`) -4. **Requires approval** — The `deploy` job uses a GitHub Environment with required reviewers. Approvals are logged and the self-review rule prevents unilateral deploys. -5. **Deploys via OIDC** — Assumes an IAM role via GitHub OIDC federation (no long-lived credentials). The role is scoped to the `cdk deploy` action with least-privilege policies per [DEPLOYMENT_ROLES.md](../design/DEPLOYMENT_ROLES.md). - -### Security controls - -| Control | Purpose | -|---------|---------| -| Fork exclusion (`head_repository` check) | Prevents fork PRs from triggering deploy approval prompts | -| Environment approval | Human gate before any deploy reaches AWS | -| OIDC federation | No stored AWS credentials; tokens are request-scoped | -| Compute type allowlist | Only pre-approved types can be deployed | -| Non-cancellable concurrency | Deploy can't be interrupted mid-flight | - -### For administrators - -- **Enable deploys**: Set the `deploy` Environment in repo settings with required reviewers. -- **Configure OIDC**: Set `AWS_ROLE_TO_ASSUME` secret and `AWS_REGION` variable. -- **Allowlist compute types**: Edit `ALLOWED_COMPUTE_TYPES` in `deploy.yml`. -- **Deploy via PR label**: Add the `deploy:` label to a PR (e.g., `deploy:agentcore`). -- **Delete a leftover integ assertion stack**: An integ run (`integ.yml`) names its assertion stack after the run, `int---assert`. It does not delete a stack named `TaskApiSmokeDefaultTestDeployAssert413BE3D6`, which is the assertion stack of every run whose checkout is from before that name (#400). If one is left, delete it while no integ run is in progress, in the account and Region of those runs, with `aws cloudformation delete-stack --stack-name TaskApiSmokeDefaultTestDeployAssert413BE3D6`. +These checks do not show that a deployment works: only a deployment exercises IAM permissions, CloudFormation and the AgentCore runtime. ## Known deployment issues @@ -516,9 +491,7 @@ STACK_NAME= mise //cdk:preflight:log-delivery -- --check-only **Resolution:** None needed if you deploy with `mise //cdk:deploy`. The preflight is the first command of that task, so it detects the legacy resources on the live stack and applies the one-time migration — deleting exactly those resources, scoped to that stack, in the same account and region as the deploy, because the task forwards its own arguments to it. -**The GitHub Actions pipeline does not migrate automatically.** Its deploy job calls `cdk deploy` directly and so inherits none of that task's steps. What it does do is *report*: the read-only **diff** job runs the preflight with `--check-only` and writes the result into the job summary, so a stack needing migration is visible in the run summary before the approval gate rather than discovered as a rollback afterwards. Migrate it with `STACK_NAME= mise //cdk:deploy`, or the manual sequence below, then re-run the pipeline. - -A bare `cdk deploy` (no mise, no pipeline) does **not** run the preflight. On that path, or after the rollback above, run the check command shown under *Affects* and then follow the manual steps in [Observability — AgentCore log delivery](../design/OBSERVABILITY.md#agentcore-log-delivery). +A bare `cdk deploy` (no mise) does **not** run the preflight. On that path, or after the rollback above, run the check command shown under *Affects* and then follow the manual steps in [Observability — AgentCore log delivery](../design/OBSERVABILITY.md#agentcore-log-delivery). ### Task list keeps its old order while a new index is built (#51) @@ -561,23 +534,14 @@ In that call, `ModelInvocationLogging` writes the stack's log group and role to | Path | Auto-pinned? | What you must do | |------|--------------|------------------| | Local `cdk deploy` / `mise //cdk:deploy` (credentials resolve at synth) | Yes — for regions in the built-in map | Nothing, unless synth reports an `[AgentCore AZs]` error | -| CI/CD (`build.yml` → `deploy.yml`) | **No** — the assembly is synthesized credential-less | Set the `AGENTCORE_AVAILABILITY_ZONES` repo/environment variable (below) | +| A pre-built assembly (`cdk deploy --app cdk.out`) that was synthesized without credentials | **No** — synth has no account to read the zone mapping from | Set the context override (below) where the assembly is synthesized | | Any region absent from the built-in map | No | Set the context override (below) | **Auto-pin (local deploys).** With a concrete account and region, synth confirms the credentials belong to that account (`sts:GetCallerIdentity`), reads the account's zone name-to-ID mapping (`ec2:DescribeAvailabilityZones`), and pins the VPC to the first two AZ *names* — sorted, so the pin is stable across synths — whose zone IDs are AgentCore-supported. Two zones matches `AgentVpc`'s default `maxAzs`, so enabling this does not widen an already-working topology. If auto-pin is attempted and cannot finish — lookup denied or throttled, credentials pointing at a different account, or fewer than two supported zones — synth **fails** with an `[AgentCore AZs]` error rather than quietly falling back. That is deliberate: a silent fallback produces a template that looks pinned but is not, which is the failure this section exists to prevent. Fix the cause or set the override. -**CI/CD deploys are not auto-pinned.** Auto-pin needs a bound account at synth time and the pipeline has none: `build.yml` synthesizes `cdk.out` without credentials (env-agnostic) and `deploy.yml` deploys that pre-built assembly (`--app cdk/cdk.out`). Two consequences worth being explicit about: - -- Passing `-c 'agentcore:availabilityZones=...'` to `cdk deploy` **has no effect on the pipeline path** — the template is already synthesized by then. Context only matters at synth. -- `cdk/cdk.context.json` is **not** a durable place to set this: it is gitignored, and `build.yml` regenerates the whole file. - -Instead, set the repo (or environment) variable **`AGENTCORE_AVAILABILITY_ZONES`** to a JSON array of zone names. `build.yml`'s "Generate CDK context" step folds it into the context that the uploaded assembly is synthesized with, and an unset variable simply leaves the stack unpinned (synth logs an `[AgentCore AZs]` warning): - -``` -AGENTCORE_AVAILABILITY_ZONES = ["us-east-1b","us-east-1c"] -``` +**An assembly synthesized without credentials is not auto-pinned.** Auto-pin needs a bound account at synth time. A synth without credentials (env-agnostic) has none: it leaves the stack unpinned and logs an `[AgentCore AZs]` warning. That is the case when one step synthesizes `cdk.out` without credentials and a later one deploys it with `cdk deploy --app cdk.out`. Set the override where the assembly is synthesized: passing `-c 'agentcore:availabilityZones=...'` to that `cdk deploy` **has no effect**, because the template is already synthesized by then. **Choosing the values.** @@ -587,7 +551,7 @@ AGENTCORE_AVAILABILITY_ZONES = ["us-east-1b","us-east-1c"] --query 'AvailabilityZones[].[ZoneName,ZoneId]' --output text ``` 2. Pick at least two zone **names** (column 1) whose **zone IDs** (column 2) appear in the AgentCore-supported set for that region. -3. Set the value — the pipeline variable above, or for a local synth either `cdk/cdk.json` `context`: +3. Set the value — either in `cdk/cdk.json` `context`: ```json { "context": { "agentcore:availabilityZones": ["us-east-1b", "us-east-1c"] } } ``` diff --git a/docs/guides/QUICK_START.mdx b/docs/guides/QUICK_START.mdx index 428b7b221..7461ebbb6 100644 --- a/docs/guides/QUICK_START.mdx +++ b/docs/guides/QUICK_START.mdx @@ -73,7 +73,7 @@ Other guides write the short form `bgagent `. If you prefer it, define > **Note:** `mise run build` includes CDK synthesis, which queries AWS for availability zones. Your active AWS credentials must have at least `ec2:DescribeAvailabilityZones` permission, or the build will fail. If you use named profiles, make sure `AWS_PROFILE` is set before running the build — the CDK CLI does not forward `--profile` to the app process, so an unexported profile can leave synth reading a different account. > -> A local deploy uses that same call to pin the VPC to AgentCore-supported zones, and synth fails with an `[AgentCore AZs]` error if it cannot confirm them. Deploys through the CI/CD pipeline are **not** auto-pinned (the assembly is synthesized without credentials) and need the `AGENTCORE_AVAILABILITY_ZONES` variable instead — see [Known deployment issues](./DEPLOYMENT_GUIDE.md#agentcore-unsupported-availability-zones). +> A local deploy uses that same call to pin the VPC to AgentCore-supported zones, and synth fails with an `[AgentCore AZs]` error if it cannot confirm them — see [Known deployment issues](./DEPLOYMENT_GUIDE.md#agentcore-unsupported-availability-zones). ## Step 2 - Prepare a repository diff --git a/docs/src/content/docs/architecture/Ci-build-performance.md b/docs/src/content/docs/architecture/Ci-build-performance.md index eaa5c4e18..e9596c57a 100644 --- a/docs/src/content/docs/architecture/Ci-build-performance.md +++ b/docs/src/content/docs/architecture/Ci-build-performance.md @@ -140,7 +140,7 @@ build (agentcore) (needs: build-shard) # single required context; always r # fails if any shard failed ``` -- The matrix job (`build-shard`) runs `jest --shard=${{ matrix.shard }}/N` and uploads its `cdk.out` / coverage artifacts. +- The matrix job (`build-shard`) runs `jest --shard=${{ matrix.shard }}/N` and uploads its coverage artifact. - The aggregate job keeps the `compute_type: [agentcore]` matrix so it emits the required **`build (agentcore)`** context (one stable name regardless of shard count). Its gate must use GitHub's documented pattern: **`if: ${{ always() }}` on the job, with the pass/fail decision moved into a step.** `contains()` is **not** one of GitHub's four status-check functions (`success()`, `always()`, `cancelled()`, `failure()`), so a bare `if: ${{ contains(needs.*.result, 'failure') }}` silently becomes `success() && contains(needs.*.result, 'failure')` — a contradiction that **never runs on either outcome**, admitting failing shards once it is the required context: ```yaml @@ -162,7 +162,6 @@ build (agentcore) (needs: build-shard) # single required context; always r ### Open design questions for the implementer - **Synth + non-test tasks:** `//cli:*`, `//docs:build`, `//agent:quality` finish early (~74–83s) and are easy to keep off the critical path. **`//cdk:synth:quiet` is different** — at +142s it is the *next binding constraint* (see [How the time is spent](#how-the-time-is-spent)), so wherever it runs (aggregate job, a dedicated job, or shard 1) it, not the sharded suite, sets the new floor. Decide its placement deliberately and measure against ~142s, not the suite. -- **Artifact strategy:** the deploy pipeline consumes `cdk-agentcore-out`. Sharding test execution should not change synth output; ensure exactly one job still produces the deploy artifact. - **Shard balance:** `--shard` partitions by file count, not by runtime. A few heavy suites (full `App` + cdk-nag synth) can skew one shard. If imbalance is material, consider ordering/grouping heavy suites or a runtime-aware splitter; measure first. ## Measurement protocol diff --git a/docs/src/content/docs/architecture/Observability.md b/docs/src/content/docs/architecture/Observability.md index 3ab699169..efec11c8a 100644 --- a/docs/src/content/docs/architecture/Observability.md +++ b/docs/src/content/docs/architecture/Observability.md @@ -503,7 +503,7 @@ Fresh deployments need nothing here. A stack whose live delivery resources alrea A stack still on older ids has to converge, and because the create-before-delete collision above applies, the old resources must be gone before the new ones are created. -**`mise //cdk:deploy` handles this automatically** (the CI pipeline reports it but does not migrate — see the deployment guide's known-issues entry)**.** The deploy task runs a preflight (`cdk/scripts/preflight-log-delivery.ts`) that reads the stack's own resource list and, only when it finds delivery resources under the retired pinned ids (a `CDKSource` or `CdkLogGroup` segment in the logical id), deletes exactly those before the deploy proceeds. It deletes by the physical ids CloudFormation reports for *this stack*, so other delivery configurations in the account — even on a shared account — are unreachable by construction. Already-migrated stacks and fresh installs pass through untouched, so the preflight is safe to leave on every deploy. +**`mise //cdk:deploy` handles this automatically.** The deploy task runs a preflight (`cdk/scripts/preflight-log-delivery.ts`) that reads the stack's own resource list and, only when it finds delivery resources under the retired pinned ids (a `CDKSource` or `CdkLogGroup` segment in the logical id), deletes exactly those before the deploy proceeds. It deletes by the physical ids CloudFormation reports for *this stack*, so other delivery configurations in the account — even on a shared account — are unreachable by construction. Already-migrated stacks and fresh installs pass through untouched, so the preflight is safe to leave on every deploy. **Which stacks are affected is a property of deployed state, not of the stack's name.** The legacy ids are the *previous library's* naming, not a product of the pin table: `#339` (`9a58797c`, 2026-06-13) switched the stack from `@aws-cdk/aws-bedrock-agentcore-alpha` to `aws-cdk-lib/aws-bedrockagentcore`, and the pin table only landed seven weeks later in `#695` (`4357c353`, 2026-08-03). The alpha generated the `RuntimeCDKSource…` / `RuntimeCdkLogGroup…` shapes; `aws-cdk-lib` generates `RuntimeApplicationLogsDeliverySource`. @@ -532,7 +532,7 @@ ABCA_SKIP_LOG_DELIVERY_PREFLIGHT=1 mise //cdk:deploy **A non-default stack needs the name given twice, and the two are not interchangeable.** `cdk deploy` selects its stack from `stackName` CDK *context*, while the preflight reads `STACK_NAME` (or `--stack-name`, or `stackName` in `cdk.json` context). Arguments after `--` are appended to the `cdk deploy` command and never reach a mise `depends` task, so `-c stackName=x` alone leaves the preflight on its default target — and `STACK_NAME=x` alone leaves the *deploy* on its default target. Setting only one is how you end up migrating one stack while deploying another. -This is now closed rather than merely documented: the preflight runs as the first command of the `deploy` task, so the arguments after `--` reach it and `cdk deploy` alike, and `--profile` / `--region` are forwarded to its own AWS calls. It also reads `cdk.context.json` (the file the CI pipeline writes `stackName` into), not just `cdk.json`. +This is now closed rather than merely documented: the preflight runs as the first command of the `deploy` task, so the arguments after `--` reach it and `cdk deploy` alike, and `--profile` / `--region` are forwarded to its own AWS calls. It also reads `cdk.context.json`, not just `cdk.json`. If the stack name still resolves from the built-in default *while arguments were supplied*, the preflight refuses to delete rather than guess — the case that would otherwise migrate one stack's delivery resources while deploying another, leaving the first one's agent logging dark until it is deployed itself. Every run prints the stack, where the name came from, and the account and region it resolved to: @@ -564,7 +564,7 @@ Agent sessions run for up to 8 hours. CDK deployments replace Lambda functions, - **Drain before deploy** - Pre-deploy check for active tasks. Warn or block if tasks are running. - **Durable execution resilience** - Lambda Durable Functions checkpoints are stored externally. A replaced Lambda can resume from its last checkpoint. - **Consistency recovery** - If a deploy interrupts a running orchestrator, the `ConcurrencyReconciler` Lambda (every 15 minutes) corrects the concurrency counter. (This is distinct from the stranded-task reconciler, a separate Lambda that runs every 5 minutes to fail tasks whose pipeline never started.) The stuck task alarm fires and triggers manual finalization. -- **Blue-green deployment** - CI/CD pipeline uses blue-green for the orchestrator Lambda, with automatic rollback if error rates increase. +- **Blue-green deployment (planned, not implemented)** - Blue-green for the orchestrator Lambda, with automatic rollback if error rates increase. No workflow deploys ABCA today. ## Account prerequisites diff --git a/docs/src/content/docs/decisions/Adr-013-tiered-validation-pyramid.md b/docs/src/content/docs/decisions/Adr-013-tiered-validation-pyramid.md index 143e8c1b5..d4780a582 100644 --- a/docs/src/content/docs/decisions/Adr-013-tiered-validation-pyramid.md +++ b/docs/src/content/docs/decisions/Adr-013-tiered-validation-pyramid.md @@ -4,14 +4,14 @@ title: "ADR-013: Tiered validation pyramid for agentic-first development" **Status:** proposed **Date:** 2026-05-19 -**Last-updated:** 2026-11-21 +**Last-updated:** 2026-11-24 ## Context The current validation architecture has two operational tiers: - **Pre-commit hooks** — formatting, secrets scan, and the lint and drift checks of the staged files -- **Remote CI** (5–20 min) — full build, test, synth, security scans, deploy verification +- **Remote CI** (5–20 min) — full build, test, synth, security scans, deploy verification (CI no longer deploys; see the note under Tier 3) The gap between these tiers is significant. When an agent (or human) makes a change that passes pre-commit but fails in CI, the feedback loop is: @@ -35,7 +35,7 @@ The root cause: there is no **Tier 2** — a local, fast, high-fidelity validati |------|------|-----------------|-----| | Pre-commit (Tier 0) | No fixed budget: by what is staged (measured times under Tier 0 below) | Formatting, secrets, lint and drift checks of the staged files | None — works well | | mise build (Tier 1) | 30–90s | Compile, unit tests, CDK synth, docs sync, linting | Wired as a pre-push gate (prek `pre-push` hooks run tests + security); the `mise run build` superset is available on demand | -| Remote CI (Tier 3) | 5–20 min | Full matrix, security, E2E, deploy | Authoritative but slow | +| Remote CI (Tier 3) | 5–20 min | The full build (lint, type checks, tests, synth, docs) and the security scans; the Tier 2a tests as an advisory check | Authoritative but slow. Makes no AWS call: nothing is deployed or verified in a real account | | **Local integration (Tier 2)** | About half a minute for phase 2a, on a laptop | Phase 2a only: how real handler, CLI and agent code behaves against emulated DynamoDB, S3, Secrets Manager, Cognito, STS and CloudWatch Logs | Phase 2a is an advisory check, not a required one; phases 2b–2d do not exist | ### Agentic-first motivation @@ -135,21 +135,9 @@ Progressive build-out: - Documentation mutation check (fail if Starlight mirrors are stale) - The Tier 0 file checks (whitespace, end of file, conflict markers, YAML/JSON syntax) over all tracked files (`mise run check:hygiene`, part of `mise run build`) and shellcheck over every shell script (`mise run check:shell`, also part of `mise run build`): a commit made without the hooks skips Tier 0 -Status: **Implemented** (GitHub Actions). This remains the authoritative gate for merge. +Status: **Implemented** (GitHub Actions), except the items that need an AWS account (see the note below). This remains the authoritative gate for merge. -> **Deployed runtime E2E — Phase 0 landed (issue #236).** `@aws-cdk/integ-tests-alpha` + `integ-runner` provide deploy-then-verify coverage: `mise //cdk:integ` deploys a trimmed Task API stack to a real account, asserts the create-and-persist happy path (task persists at `SUBMITTED`), then tears it down. In CI (`.github/workflows/integ.yml`) it is triggered per-PR via `workflow_run` only when the diff touches `cdk/**` or `agent/**` (docs/cli-only PRs get an immediate green skip), runs behind the reused `deploy` environment's admin-approval gate so it never assumes the deploy role unattended, and posts an `integ-smoke` status that is not required: the ruleset for `main` requires only `build (agentcore)` and `Secrets, deps, and workflow scan`, so the status informs reviewers and does not block merge. Because it is path-filtered and admin-gated it does not slow non-infra PRs. `workflow_dispatch` is retained for manual runs against `main`. Phase 1 (full lifecycle / real agent runs) and Phase 2 (channels) are follow-ups. - -#### Residual risk acceptance — fork PR integ execution - -The deployed E2E gate runs **fork-authored test code** (`cdk/test/integ/**`) against the shared AWS account. This is intentional: a fork `pull_request` job gets no secrets/OIDC, so the `workflow_run` trigger is the only way to give fork PRs the same deploy-verify coverage that branch PRs get. The accepted risk is that fork code executes with the shared `GitHub` deploy role (reused from `deploy.yml`), which is capable of CloudFormation operations in the shared account. - -Mitigations layered against that risk: - -- **Two human gates before fork code runs.** The `resolve` job requires a maintainer-applied `safe-to-test` label on fork PRs, and the `integ` job requires explicit approval of the `deploy` GitHub environment (required reviewers: `coding-agents-admin` / `coding-agents-maintainers`, self-review prevented). The approver MUST review `cdk/test/integ/**` changes before approving. -- **Environment reuse over a dedicated role.** Phase 0 reuses `deploy.yml`'s existing `deploy` environment and `GitHub` deploy role rather than provisioning a separate least-privilege role — the environment and its OIDC trust are already configured, so no account-side IAM change is needed to go live. The tradeoff is that integ (including approved fork code) runs with the full deploy role; the human gates above and forced teardown below are the compensating controls. Scoping a dedicated least-privilege integ role remains an option a maintainer can adopt later if the blast radius is judged too wide. -- **Status-only tokens and forced teardown.** Each job gets minimal `permissions`; the report path only posts commit statuses, and teardown runs `if: always()` with a fail-loud `wait` so a stranded stack surfaces rather than leaking billable resources. - -Residual risk after these mitigations (a malicious fork PR that passes maintainer review and operates strictly within the scoped stacks) is **accepted** for Phase 0. +> **Nothing is deployed to AWS from CI.** No workflow uses an AWS account, so the items of this list that need one (CDK diff against deployed stack, multi-account deployment verification, E2E tests against real AWS services) do not run in CI. The ruleset for `main` requires `build (agentcore)` and `Secrets, deps, and workflow scan`; the `emulator` workflow runs the Tier 2a tests beside them as an advisory check. No automated test of a deployed stack exists: the Phase 0 smoke of deployed runtime E2E (issue #236, `mise //cdk:integ`: a trimmed Task API stack deployed to a real account, asserted and torn down) was removed with the workflow that ran it. A deployed stack is checked by hand only: the live acceptance of the Lambda MicroVM backend (`scripts/microvm-acceptance.sh`) and `bgagent platform doctor`. Deployed runtime E2E, from Phase 0 on, is a follow-up. ### Enforcement model @@ -242,3 +230,4 @@ Escape hatches must be explicit (noted in PR description, not silent). - 2026-11-15 — Phase 2a is implemented, on the AWS Emulator instead of LocalStack, as an advisory check (`mise run test:integration` and the `emulator` workflow). Replaced the estimate that it would eliminate "60%+ of CI-only failures" with what was measured, added the graduation criteria this ADR asks for, and stated that phase 2c needs a real AWS account because the emulator cannot show a missing permission (decision otherwise unchanged). - 2026-11-20 — Tier 0 also runs the type check of cdk, cli and web when one of their TypeScript files is staged (#260). The build runs the same checks and stays the gate (decision unchanged). - 2026-11-21 — Tier 0 also runs shellcheck when a shell script is staged (#278). The build and the security suite run the same check over every shell script (decision unchanged). +- 2026-11-24 — The `deploy` and `integ` workflows were removed as unused; the Tier 2a tests are the integration check that CI runs. CI now makes no AWS call: Tier 3 no longer deploys, compares against a deployed stack or tests in a real account. The manual task `mise //cdk:integ` and its smoke test went with the `integ` workflow: nothing ran it any more, and no run of it in CI had completed since the workflow's call of it was repaired (#1048). Removed the section "Residual risk acceptance — fork PR integ execution": the risk it accepted, fork-authored test code running with the deploy role, ended with the `integ` workflow (decision unchanged). diff --git a/docs/src/content/docs/getting-started/Deployment-guide.md b/docs/src/content/docs/getting-started/Deployment-guide.md index 9d367f843..f4460f077 100644 --- a/docs/src/content/docs/getting-started/Deployment-guide.md +++ b/docs/src/content/docs/getting-started/Deployment-guide.md @@ -27,7 +27,7 @@ Without `compute_types`, legacy `compute_type=ecs` or `compute_type=lambda-micro `networkTopology=inline` is the default. Use `networkTopology=split` for a new environment to put the VPC, subnets, endpoints, flow logs and DNS firewall in `${stackName}-network`. The application stack retains its name, data stores, compute resources and shared Task API. It depends on network exports, so CDK deploys the network first. The complete VPC/subnet/security-group export set stays present across compute-backend changes. Keep the same topology context on subsequent synth, diff and deploy commands. -Every local and pipeline synthesis enforces a **490-resource ceiling per parent or nested template**, including operator configurations outside the census. CDK fails synthesis with the stack name, resource count and ceiling when a template exceeds it. `@aws-cdk/core:stackResourceLimit` accepts a stricter integer from 1 to 490, as either a JSON number or CLI string; it cannot raise the production ceiling. +Every synthesis, local or in the CI build, enforces a **490-resource ceiling per parent or nested template**, including operator configurations outside the census. CDK fails synthesis with the stack name, resource count and ceiling when a template exceeds it. `@aws-cdk/core:stackResourceLimit` accepts a stricter integer from 1 to 490, as either a JSON number or CLI string; it cannot raise the production ceiling. The budget covers complete configurations, including multiple backends, Gateway, Registry, the Linear vault, managed MicroVM images, alert email, a fork Blueprint, explicit three-zone pins and expanded model allowlists. With the approval, maintenance and MicroVM subsystems in nested stacks, every sampled combination fits inline (the widest is all three backends with every option, on two zones with the default model allowlist); split reduces the application template further. The budget guard never changes topology automatically. The [offline census](/sample-autonomous-cloud-coding-agents/developer-guide/repository-preparation#stack-decomposition-and-synthesis-budgets) reports counts for each supported profile. @@ -167,7 +167,7 @@ Before it runs `cdk deploy`, `mise //cdk:deploy` compares the outputs of the `CD `mise //cdk:preflight` runs the same check on its own. It is read-only. It needs the AWS CLI on `PATH` and no permission beyond `cloudformation:DescribeStacks`. Arguments after `--` are those of the deploy (`--profile`, `--region`, `-c compute_types=...`), plus `--json` for CI. -The compute backends the preflight checks are those of the `compute_types` (or `compute_type`) context, from `-c` arguments and `cdk/cdk.json`. A backend that only the `compute` list of a [deployment profile](#profile-file-and-precedence) selects is not checked. A bare `cdk deploy` and the GitHub Actions pipeline do not run the preflight. +The compute backends the preflight checks are those of the `compute_types` (or `compute_type`) context, from `-c` arguments and `cdk/cdk.json`. A backend that only the `compute` list of a [deployment profile](#profile-file-and-precedence) selects is not checked. A bare `cdk deploy` does not run the preflight. | Result | When | What to do | |---|---|---| @@ -238,11 +238,11 @@ The wizard works in this order: - Your confirmation replaces CDK's own IAM approval prompt; the change summary says how many IAM roles and policies are included. - On success it configures the CLI from the stack outputs and prints next steps, in the same command form you launched setup with. A new installation lists storing a GitHub token, creating a user, signing in and onboarding a repository. Any Slack, Linear or Jira feature added by this run lists its own setup command. If the CLI was previously signed in to another stack's user pool, the cached tokens are removed; run `bgagent login` again. On failure it names the failed component and CloudFormation's reason, and keeps your selection so you can rerun. -`--no-deploy` writes the profile without a diff. If it removes a stateful feature from an existing stack, it asks for the same data-loss confirmation, because the next `mise //cdk:deploy` or CI deploy applies the removal with no wizard in the loop. +`--no-deploy` writes the profile without a diff. If it removes a stateful feature from an existing stack, it asks for the same data-loss confirmation, because the next `mise //cdk:deploy` applies the removal with no wizard in the loop. -Commit `abca.deployment.json`. Each additional deployment from the same checkout gets its own `abca.deployment..json`, so deploying one never changes another's features. Synthesis uses only the file matching `-c stackName=…`: the default stack `backgroundagent-dev` uses `abca.deployment.json`, and any other stack without its own file keeps the legacy topology rather than inheriting the default stack's features. +Commit `abca.deployment.json`. Each additional deployment from the same checkout gets its own `abca.deployment..json`, so deploying one never changes another's features. Synthesis uses only the file matching `-c stackName=…`: the default stack `backgroundagent-dev` uses `abca.deployment.json`, and any other stack without its own file keeps the legacy topology rather than inheriting the default stack's features. Every synthesis reads the profile, including `mise //cdk:synth`, `mise //cdk:deploy` and the CI build. -Deployments in one account share only the CDK bootstrap, with one exception: Bedrock model-invocation logging is an account-wide setting, configured by whichever deployment was deployed last. Every synthesis reads it, including `mise //cdk:synth`, `mise //cdk:deploy` and the CI build, so local and pipeline deployments match. +Deployments in one account share only the CDK bootstrap, with one exception: Bedrock model-invocation logging is an account-wide setting, configured by whichever deployment was deployed last. ### Profile file and precedence @@ -281,7 +281,7 @@ CLI commands for an omitted feature (for example `bgagent slack setup`) fail wit ### Regional availability -`contracts/deployment-capabilities.json` records the services each capability needs, the Regions that support it, and the source and date of the last verification. Its `compute` section lists the compute backends in the same way; Lambda MicroVMs is the only Region-limited one. `source` and `lastVerified` describe core and the features only: the Lambda MicroVMs Regions come from the launch list of [ADR-021](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend#regional-availability-enforcement) (2026-06-22). CDK synthesis enforces the catalog for a concrete Region, so a CI or manual deploy fails before CloudFormation runs, not only in the wizard. Environment-agnostic synthesis is not checked. +`contracts/deployment-capabilities.json` records the services each capability needs, the Regions that support it, and the source and date of the last verification. Its `compute` section lists the compute backends in the same way; Lambda MicroVMs is the only Region-limited one. `source` and `lastVerified` describe core and the features only: the Lambda MicroVMs Regions come from the launch list of [ADR-021](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend#regional-availability-enforcement) (2026-06-22). CDK synthesis enforces the catalog for a concrete Region, so a deploy made without the wizard also fails before CloudFormation runs. Environment-agnostic synthesis is not checked. A Region listed in the catalog has the required services; the list says nothing more. It includes `us-gov-west-1` for the core platform, but ABCA's least-privilege bootstrap, which `bgagent setup` installs when the account and Region have no `CDKToolkit` stack, covers the commercial `aws` partition only and cannot deploy ABCA in another one. See [DEPLOYMENT_ROLES.md](/sample-autonomous-cloud-coding-agents/architecture/deployment-roles#using-these-policies). @@ -436,44 +436,19 @@ At public US East (N. Virginia) first-tier list rates verified in August 2026, t ## Reference -## CI/CD pipeline (`deploy.yml`) +## Continuous integration -The repository includes a two-stage CI/CD pipeline: +No workflow of this repository deploys ABCA or uses an AWS account. A deployment is made from a checkout, with your own credentials: run [`bgagent setup`](#choosing-features-with-bgagent-setup), or `mise //cdk:deploy` on an account you have [bootstrapped](#bootstrap-with-least-privilege). -### Stage 1: Build (`build.yml`) +Three workflows check the code of every pull request and merge-queue entry: -Triggers on every pull request and merge-queue entry, and on manual dispatch. Runs `mise run build` (what it covers is listed under [Pull request](/sample-autonomous-cloud-coding-agents/developer-guide/contributing#5-pull-request) in CONTRIBUTING.md) and uploads the synthesized `cdk.out/` together with a `deploy-intent` artifact. The intent file declares whether a deploy should happen and for which compute types. +| Workflow | What it runs | Required to merge | +|----------|--------------|-------------------| +| `build` | `mise run build`; [Pull request](/sample-autonomous-cloud-coding-agents/developer-guide/contributing#5-pull-request) in CONTRIBUTING.md lists what it covers. Its CDK synthesis runs without credentials, and the output is not deployed | Yes | +| `security-pr` | The secret, static-analysis (Semgrep), dependency and workflow scans, and a build of the agent image when a file that defines it changed | Yes | +| `emulator` | The integration tests: ABCA's real handler, CLI and agent code against the AWS Emulator in a container, with no AWS account. [scripts/aws-emulator/README.md](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/blob/main/scripts/aws-emulator/README.md) says where a green run can be trusted | No | -### Stage 2: Deploy (`deploy.yml`) - -Triggers via `workflow_run` when `build.yml` completes successfully. The pipeline: - -1. **Skips fork PRs** — `head_repository.full_name == github.repository` prevents forks from entering the deploy flow. This is a security measure: an untrusted fork could modify `build.yml` to produce a deploy-intent artifact, which would otherwise prompt maintainers for approval unnecessarily. -2. **Downloads `deploy-intent.json`** from the triggering build run. -3. **Resolves targets** — Determines which compute types to deploy: - - `intent: "-"` → no-op (most PRs) - - `intent: "labels"` → reads PR labels against an allowlist - - `intent: ""` → deploys the specified type (e.g., `agentcore`) -4. **Requires approval** — The `deploy` job uses a GitHub Environment with required reviewers. Approvals are logged and the self-review rule prevents unilateral deploys. -5. **Deploys via OIDC** — Assumes an IAM role via GitHub OIDC federation (no long-lived credentials). The role is scoped to the `cdk deploy` action with least-privilege policies per [DEPLOYMENT_ROLES.md](/sample-autonomous-cloud-coding-agents/architecture/deployment-roles). - -### Security controls - -| Control | Purpose | -|---------|---------| -| Fork exclusion (`head_repository` check) | Prevents fork PRs from triggering deploy approval prompts | -| Environment approval | Human gate before any deploy reaches AWS | -| OIDC federation | No stored AWS credentials; tokens are request-scoped | -| Compute type allowlist | Only pre-approved types can be deployed | -| Non-cancellable concurrency | Deploy can't be interrupted mid-flight | - -### For administrators - -- **Enable deploys**: Set the `deploy` Environment in repo settings with required reviewers. -- **Configure OIDC**: Set `AWS_ROLE_TO_ASSUME` secret and `AWS_REGION` variable. -- **Allowlist compute types**: Edit `ALLOWED_COMPUTE_TYPES` in `deploy.yml`. -- **Deploy via PR label**: Add the `deploy:` label to a PR (e.g., `deploy:agentcore`). -- **Delete a leftover integ assertion stack**: An integ run (`integ.yml`) names its assertion stack after the run, `int---assert`. It does not delete a stack named `TaskApiSmokeDefaultTestDeployAssert413BE3D6`, which is the assertion stack of every run whose checkout is from before that name (#400). If one is left, delete it while no integ run is in progress, in the account and Region of those runs, with `aws cloudformation delete-stack --stack-name TaskApiSmokeDefaultTestDeployAssert413BE3D6`. +These checks do not show that a deployment works: only a deployment exercises IAM permissions, CloudFormation and the AgentCore runtime. ## Known deployment issues @@ -518,9 +493,7 @@ STACK_NAME= mise //cdk:preflight:log-delivery -- --check-only **Resolution:** None needed if you deploy with `mise //cdk:deploy`. The preflight is the first command of that task, so it detects the legacy resources on the live stack and applies the one-time migration — deleting exactly those resources, scoped to that stack, in the same account and region as the deploy, because the task forwards its own arguments to it. -**The GitHub Actions pipeline does not migrate automatically.** Its deploy job calls `cdk deploy` directly and so inherits none of that task's steps. What it does do is *report*: the read-only **diff** job runs the preflight with `--check-only` and writes the result into the job summary, so a stack needing migration is visible in the run summary before the approval gate rather than discovered as a rollback afterwards. Migrate it with `STACK_NAME= mise //cdk:deploy`, or the manual sequence below, then re-run the pipeline. - -A bare `cdk deploy` (no mise, no pipeline) does **not** run the preflight. On that path, or after the rollback above, run the check command shown under *Affects* and then follow the manual steps in [Observability — AgentCore log delivery](/sample-autonomous-cloud-coding-agents/architecture/observability#agentcore-log-delivery). +A bare `cdk deploy` (no mise) does **not** run the preflight. On that path, or after the rollback above, run the check command shown under *Affects* and then follow the manual steps in [Observability — AgentCore log delivery](/sample-autonomous-cloud-coding-agents/architecture/observability#agentcore-log-delivery). ### Task list keeps its old order while a new index is built (#51) @@ -563,23 +536,14 @@ In that call, `ModelInvocationLogging` writes the stack's log group and role to | Path | Auto-pinned? | What you must do | |------|--------------|------------------| | Local `cdk deploy` / `mise //cdk:deploy` (credentials resolve at synth) | Yes — for regions in the built-in map | Nothing, unless synth reports an `[AgentCore AZs]` error | -| CI/CD (`build.yml` → `deploy.yml`) | **No** — the assembly is synthesized credential-less | Set the `AGENTCORE_AVAILABILITY_ZONES` repo/environment variable (below) | +| A pre-built assembly (`cdk deploy --app cdk.out`) that was synthesized without credentials | **No** — synth has no account to read the zone mapping from | Set the context override (below) where the assembly is synthesized | | Any region absent from the built-in map | No | Set the context override (below) | **Auto-pin (local deploys).** With a concrete account and region, synth confirms the credentials belong to that account (`sts:GetCallerIdentity`), reads the account's zone name-to-ID mapping (`ec2:DescribeAvailabilityZones`), and pins the VPC to the first two AZ *names* — sorted, so the pin is stable across synths — whose zone IDs are AgentCore-supported. Two zones matches `AgentVpc`'s default `maxAzs`, so enabling this does not widen an already-working topology. If auto-pin is attempted and cannot finish — lookup denied or throttled, credentials pointing at a different account, or fewer than two supported zones — synth **fails** with an `[AgentCore AZs]` error rather than quietly falling back. That is deliberate: a silent fallback produces a template that looks pinned but is not, which is the failure this section exists to prevent. Fix the cause or set the override. -**CI/CD deploys are not auto-pinned.** Auto-pin needs a bound account at synth time and the pipeline has none: `build.yml` synthesizes `cdk.out` without credentials (env-agnostic) and `deploy.yml` deploys that pre-built assembly (`--app cdk/cdk.out`). Two consequences worth being explicit about: - -- Passing `-c 'agentcore:availabilityZones=...'` to `cdk deploy` **has no effect on the pipeline path** — the template is already synthesized by then. Context only matters at synth. -- `cdk/cdk.context.json` is **not** a durable place to set this: it is gitignored, and `build.yml` regenerates the whole file. - -Instead, set the repo (or environment) variable **`AGENTCORE_AVAILABILITY_ZONES`** to a JSON array of zone names. `build.yml`'s "Generate CDK context" step folds it into the context that the uploaded assembly is synthesized with, and an unset variable simply leaves the stack unpinned (synth logs an `[AgentCore AZs]` warning): - -``` -AGENTCORE_AVAILABILITY_ZONES = ["us-east-1b","us-east-1c"] -``` +**An assembly synthesized without credentials is not auto-pinned.** Auto-pin needs a bound account at synth time. A synth without credentials (env-agnostic) has none: it leaves the stack unpinned and logs an `[AgentCore AZs]` warning. That is the case when one step synthesizes `cdk.out` without credentials and a later one deploys it with `cdk deploy --app cdk.out`. Set the override where the assembly is synthesized: passing `-c 'agentcore:availabilityZones=...'` to that `cdk deploy` **has no effect**, because the template is already synthesized by then. **Choosing the values.** @@ -589,7 +553,7 @@ AGENTCORE_AVAILABILITY_ZONES = ["us-east-1b","us-east-1c"] --query 'AvailabilityZones[].[ZoneName,ZoneId]' --output text ``` 2. Pick at least two zone **names** (column 1) whose **zone IDs** (column 2) appear in the AgentCore-supported set for that region. -3. Set the value — the pipeline variable above, or for a local synth either `cdk/cdk.json` `context`: +3. Set the value — either in `cdk/cdk.json` `context`: ```json { "context": { "agentcore:availabilityZones": ["us-east-1b", "us-east-1c"] } } ``` diff --git a/docs/src/content/docs/getting-started/Quick-start.mdx b/docs/src/content/docs/getting-started/Quick-start.mdx index c53c039ec..32b2c491b 100644 --- a/docs/src/content/docs/getting-started/Quick-start.mdx +++ b/docs/src/content/docs/getting-started/Quick-start.mdx @@ -73,7 +73,7 @@ Other guides write the short form `bgagent `. If you prefer it, define > **Note:** `mise run build` includes CDK synthesis, which queries AWS for availability zones. Your active AWS credentials must have at least `ec2:DescribeAvailabilityZones` permission, or the build will fail. If you use named profiles, make sure `AWS_PROFILE` is set before running the build — the CDK CLI does not forward `--profile` to the app process, so an unexported profile can leave synth reading a different account. > -> A local deploy uses that same call to pin the VPC to AgentCore-supported zones, and synth fails with an `[AgentCore AZs]` error if it cannot confirm them. Deploys through the CI/CD pipeline are **not** auto-pinned (the assembly is synthesized without credentials) and need the `AGENTCORE_AVAILABILITY_ZONES` variable instead — see [Known deployment issues](/sample-autonomous-cloud-coding-agents/getting-started/deployment-guide#agentcore-unsupported-availability-zones). +> A local deploy uses that same call to pin the VPC to AgentCore-supported zones, and synth fails with an `[AgentCore AZs]` error if it cannot confirm them — see [Known deployment issues](/sample-autonomous-cloud-coding-agents/getting-started/deployment-guide#agentcore-unsupported-availability-zones). ## Step 2 - Prepare a repository diff --git a/knip.json b/knip.json index 57a166246..fa9539f46 100644 --- a/knip.json +++ b/knip.json @@ -17,7 +17,7 @@ }, "cdk": { "entry": [ - "src/{main,handlers/*}.ts!", "scripts/*.ts", "test/integ/integ.*.ts", + "src/{main,handlers/*}.ts!", "scripts/*.ts", "jest.emulator.config.js", "test/emulator/*.emulator.ts", "test/emulator/trace-api-shim.ts" ], "project": ["src/**/*.ts!", "scripts/**/*.ts", "test/**/*.ts"] diff --git a/scripts/aws-emulator/README.md b/scripts/aws-emulator/README.md index fd5e7bcf3..77cf11bcc 100644 --- a/scripts/aws-emulator/README.md +++ b/scripts/aws-emulator/README.md @@ -2,7 +2,7 @@ This tier (ADR-013 Tier 2a) runs ABCA's real handler, CLI and agent code in the normal test runners, jest and pytest, with no SDK mock: the AWS SDK calls go to an [AWS Emulator](https://github.com/aws/aws-emulator) on loopback. It needs Docker and `curl`, and no AWS account. -It is an advisory check: the [`emulator` workflow](../../.github/workflows/emulator.yml) runs it on every pull request and is not a required check. [ADR-013](../../docs/decisions/ADR-013-tiered-validation-pyramid.md) has the criteria for making it one. It does not replace the real-AWS integ smoke (`mise //cdk:integ`), which stays the authority for IAM, deployment and API Gateway wiring. The investigation behind the tier, with what was measured and what was not verified, is in [docs/research/aws-emulator-local-tests.md](../../docs/research/aws-emulator-local-tests.md). +It is an advisory check: the [`emulator` workflow](../../.github/workflows/emulator.yml) runs it on every pull request and is not a required check. [ADR-013](../../docs/decisions/ADR-013-tiered-validation-pyramid.md) has the criteria for making it one. It does not show that a deployment works: IAM, CloudFormation and API Gateway wiring are exercised only by a deployment of the platform to AWS, and no test in this repository makes one. The investigation behind the tier, with what was measured and what was not verified, is in [docs/research/aws-emulator-local-tests.md](../../docs/research/aws-emulator-local-tests.md). ## Run it diff --git a/yarn.lock b/yarn.lock index 1e5d57304..92081d7bf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -290,14 +290,6 @@ resolved "https://registry.yarnpkg.com/@aws-cdk/aws-bedrock-alpha/-/aws-bedrock-alpha-2.276.0-alpha.0.tgz#2701fed40aa71b74b1dd4beae97be9d4593ca246" integrity sha512-gHN1O99uDLreNuuts+AOfcbFCkrOIQ2Bepiw+TIc+XfhRboIJeSekz15fCneW+Z6zR3VJmGEF7WqvweVWv4VQA== -"@aws-cdk/aws-service-spec@0.1.226": - version "0.1.226" - resolved "https://registry.yarnpkg.com/@aws-cdk/aws-service-spec/-/aws-service-spec-0.1.226.tgz#aa278ab9d3458d64b4fbe033636d73f4d2f5b78c" - integrity sha512-eMDNq9Qsl9yyus/JMBQBK7i0XfIW2QzvHIaFMhiVQrUyboXDbyIw4qSuNwHPY6vbISTyM8aWoP8C0WajjL6DZw== - dependencies: - "@aws-cdk/service-spec-types" "^0.0.292" - "@cdklabs/tskb" "^0.0.4" - "@aws-cdk/cloud-assembly-api@^2.5.0": version "2.5.0" resolved "https://registry.yarnpkg.com/@aws-cdk/cloud-assembly-api/-/cloud-assembly-api-2.5.0.tgz#f63e0059da1ac948d9ab34b2b8c2f582c90c9030" @@ -315,25 +307,6 @@ jsonschema "^1.5.0" semver "^7.8.5" -"@aws-cdk/integ-runner@2.206.1": - version "2.206.1" - resolved "https://registry.yarnpkg.com/@aws-cdk/integ-runner/-/integ-runner-2.206.1.tgz#856ed9b8552ed907a5c7a23b03989a20c417a5be" - integrity sha512-PiPvSb3JDOZvvZDOq+oQu3DBmRMH3EVf/XYTeKL0TEfGyK1QyqjR+7pZTthUQH1SgcUtuY9c2yWxVjlCIfu6xg== - dependencies: - "@aws-cdk/aws-service-spec" "0.1.226" - -"@aws-cdk/integ-tests-alpha@2.276.0-alpha.0": - version "2.276.0-alpha.0" - resolved "https://registry.yarnpkg.com/@aws-cdk/integ-tests-alpha/-/integ-tests-alpha-2.276.0-alpha.0.tgz#021da765800fd6d2eeaa069aa534865db43c8ebb" - integrity sha512-ODPIiv1rGQJEcbRjZMptIFELSYtbAsMBo0aVu3aePEiZiP1WFqTxVeLbEaJsE7+Z1JYygDLD266V+OR0Mubr9w== - -"@aws-cdk/service-spec-types@^0.0.292": - version "0.0.292" - resolved "https://registry.yarnpkg.com/@aws-cdk/service-spec-types/-/service-spec-types-0.0.292.tgz#c09182584618874fe254d64af63827252d1ae776" - integrity sha512-ZFLPDRSqCKPx9wk4wH5HWJ18DRYLsUOXgUJxkvGvSnsUZzFaNwIfrZ2jz/xrXddyGYDEZnt0Zxkc5VfsKjST9Q== - dependencies: - "@cdklabs/tskb" "^0.0.4" - "@aws-crypto/sha256-js@^5.2.0": version "5.2.0" resolved "https://registry.yarnpkg.com/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz#c4fdb773fdbed9a664fc1a95724e206cf3860042" @@ -1358,11 +1331,6 @@ fs-extra "^11.4.1" typescript "^5.9.3" -"@cdklabs/tskb@^0.0.4": - version "0.0.4" - resolved "https://registry.yarnpkg.com/@cdklabs/tskb/-/tskb-0.0.4.tgz#6d7af32427ef947dddcb6f1f1d76d75924e33323" - integrity sha512-NFx1X0l7p5DyHtLLEyNeh1hPN4UN9hTkZkzFs/Mp+kFk7dpdINGmGVpCfRDjJ2DrcNSNENUmT+w8g73TvmBbTw== - "@cedar-policy/cedar-wasm@4.12.0": version "4.12.0" resolved "https://registry.yarnpkg.com/@cedar-policy/cedar-wasm/-/cedar-wasm-4.12.0.tgz#bfcb72df711ffc8d096c5a5fda49cbdcff1350b5" From 51ba9d06302d4b37608f93dc833cf1adee2f78ab Mon Sep 17 00:00:00 2001 From: bgagent Date: Tue, 24 Nov 2026 22:22:52 -0600 Subject: [PATCH 03/11] fix(orchestration): leave a failed child's issue alone on a late write The reconciler runs for every write on the record of a finished task, not only for the write that ended it. For a child that did not succeed, each of those writes moved the child's issue back out of its started state and replaced its reaction with the failed one, also after a person had taken the work over: the preview of a later push put a Linear issue from In Review back to Todo. The stream delivers the new image only, so the write that ended the task cannot be told from a later one by its content. The time between the task's end and the write separates them. The step now runs for a record written within five minutes of the task's finish time and not for a later one. The finish time is completed_at, else updated_at; the write time is the one the stream stamps on the record, so a delivery that comes late, or again, decides as the first one would have. Inside the window the step still runs for every record on purpose: nothing retries a failed call to the tracker, and the orchestrator's ttl stamp, one poll after the terminal write, is that retry. A late write still records the verdict, skips the dependents and refreshes the panel, which is how a preview reaches it. Two comments of the step said more than the code does and are corrected: the revert demotes any issue in a running state, and a reaction is matched by its emoji alone. Closes #1073 --- cdk/src/handlers/orchestration-reconciler.ts | 50 ++++++++++--- .../handlers/orchestration-reconciler.test.ts | 71 +++++++++++++++++++ 2 files changed, 111 insertions(+), 10 deletions(-) diff --git a/cdk/src/handlers/orchestration-reconciler.ts b/cdk/src/handlers/orchestration-reconciler.ts index 43df42216..20ff7f054 100644 --- a/cdk/src/handlers/orchestration-reconciler.ts +++ b/cdk/src/handlers/orchestration-reconciler.ts @@ -92,6 +92,7 @@ import { setStatusCommentId, type OrchestrationChildRow, } from './shared/orchestration-store'; +import { finishTimeMs } from './shared/scoreboard'; import { encodeMarkdownUrl } from './shared/screenshot-url'; import { ORCHESTRATION_CHILD_TASK_INDEX_NAME } from './shared/storage-names'; import { readTaskPrNumber } from './shared/task-pr-number'; @@ -535,8 +536,35 @@ async function reloadIterationScreenshot(taskId?: string): Promise<{ screenshotU } } -/** Apply one terminal child's reconcile plan. */ -async function reconcileTerminalChild(evt: TerminalTaskEvent): Promise { +/** + * How long after its task ended a write on the task record still moves a failed child's + * issue back (step 1b of `reconcileTerminalChild`). A finished task record is written again + * for as long as it lives, and every write arrives here with the terminal status. The stream + * carries the new image only, so the write that ended the task cannot be told from a later + * one by its content: the time between the task's end and the write separates them. After + * the window a person may have taken the issue over, and the surface cannot tell their + * running state from the agent's (#1073). Inside it the step runs for every record on + * purpose. Nothing retries a failed surface call, so the next record is the retry: the + * orchestrator's ttl stamp, one poll after a terminal write it did not make itself (30 s + * by default; `poll_interval_ms` can make it as long as this window), or a redelivery. + */ +const SETTLE_WINDOW_MINUTES = 5; + +/** + * Whether the record was written longer after its task ended than the settle window. The + * stream stamps a record with the time of its write, in seconds, so a delivery that comes + * late, or again, decides as the first one would have. A record without that stamp or + * without a finish time is not late: NaN compares false. + */ +function writtenLongAfterTaskEnded(record: DynamoDBRecord): boolean { + const image = record.dynamodb?.NewImage; + const endedAtMs = finishTimeMs({ completed_at: image?.completed_at?.S, updated_at: image?.updated_at?.S }); + const writtenAtMs = Number(record.dynamodb?.ApproximateCreationDateTime) * 1000; + return writtenAtMs - endedAtMs > SETTLE_WINDOW_MINUTES * 60 * 1000; +} + +/** Apply one terminal child's reconcile plan. `lateWrite`: see {@link writtenLongAfterTaskEnded}. */ +async function reconcileTerminalChild(evt: TerminalTaskEvent, lateWrite: boolean): Promise { const orchestrationId = evt.orchestrationId!; const subIssueId = await resolveSubIssueId(evt.taskId); @@ -640,15 +668,16 @@ async function reconcileTerminalChild(evt: TerminalTaskEvent): Promise { // reads awaiting-review with a PR link — a visible contradiction. The // reconciler holds the authoritative verdict, so when a terminal child did // NOT succeed we pull its issue back out of any bot-set running state. - // `revertState` is tightly guarded per surface (only demotes an issue still - // in a bot-set running state — never a human-advanced done/canceled or a + // `revertState` is tightly guarded per surface (only demotes an issue in a + // running state — never a human-advanced done/canceled or a // human-pulled-back one) and idempotent on replay. The ❌ reaction + the // failure reason on the panel convey "it failed"; a reply re-runs it (the // retry re-drives the state not-started → running). Skip the integration - // node (synthetic id, no real issue), and a stale event (the issue shows - // what a later run did). Best-effort; never throws. + // node (synthetic id, no real issue), a stale event (the issue shows + // what a later run did), and a record that was written long after the task + // ended (see SETTLE_WINDOW_MINUTES). Best-effort; never throws. const settleChannel = channelForMeta(snapshot.meta); - if (settleChannel && !plan.terminalSucceeded && !stale && !isIntegrationNode(subIssueId)) { + if (settleChannel && !plan.terminalSucceeded && !stale && !lateWrite && !isIntegrationNode(subIssueId)) { const channel = settleChannel; const childRef = issueRef(subIssueId, snapshot.meta.credentials_ref); try { @@ -660,8 +689,9 @@ async function reconcileTerminalChild(evt: TerminalTaskEvent): Promise { // (build_passed===false ⇒ failed, absolute), so a child can legitimately end // agent-✅ but graph-failed — leaving a ✅ reaction that contradicts the // failed node (observed in practice: PR opened, agent ✅, build red). - // Replacing the reaction clears only the bot's own status markers and adds - // ❌ — a human's reaction is never touched, and it's idempotent on replay. + // Replacing the reaction clears the status markers and adds ❌. Markers are + // matched by emoji alone, so a person's own reaction with one of them goes + // too; it's idempotent on replay. // This makes the reaction agree with the reverted state + the panel's ❌ // row. (The stale "✅ Task completed" comment is left as history — the // surface won't let us edit another actor's comment; the reaction + state + @@ -1651,7 +1681,7 @@ export async function handler(event: DynamoDBStreamEvent): Promise = {}; if (fields.task_id) img.task_id = { S: fields.task_id }; @@ -196,6 +198,7 @@ function taskRecord(fields: { dynamodb: { NewImage: img as never, ...(fields.sequenceNumber !== undefined && { SequenceNumber: fields.sequenceNumber }), + ...(fields.written_at !== undefined && { ApproximateCreationDateTime: Date.parse(fields.written_at) / 1000 }), }, } as DynamoDBRecord; } @@ -607,6 +610,58 @@ describe('orchestration-reconciler handler', () => { expect(swapIssueReactionMock).toHaveBeenCalledWith(expect.anything(), 'A', 'x'); }); + test('a write made long after the task ended leaves the failed child\'s issue alone: a person may have taken it over (#1073)', async () => { + // Every write on a finished task record arrives here with its terminal status. + revertIssueToNotStartedMock.mockReset().mockResolvedValue(true); + swapIssueReactionMock.mockReset().mockResolvedValue(true); + upsertStatusCommentMock.mockReset().mockResolvedValue('panel-1'); + mockOrchestration({ + subIssueId: 'A', + children: [{ sub_issue_id: 'A', child_status: 'released' }], + }); + const ended = Date.parse('2026-11-24T10:00:00Z'); + const minutesAfterEnd = (minutes: number) => new Date(ended + minutes * 60_000).toISOString(); + /** The record of the task as a write made at that time delivers it, with these times of the task. */ + const write = (writtenAt: string, times: Record = { completed_at: { S: minutesAfterEnd(0) } }) => { + const record = taskRecord({ + task_id: 'TA', + status: 'COMPLETED', + build_passed: false, + orchestration_id: 'orch_1', + written_at: writtenAt, + }); + Object.assign(record.dynamodb!.NewImage!, times); + return { Records: [record] } as never; + }; + /** How often A's issue was moved back, and how often its reaction was replaced. */ + const settled = () => [revertIssueToNotStartedMock, swapIssueReactionMock] + .map((mock) => mock.mock.calls.filter((call) => call[1] === 'A').length); + + await handler(write(minutesAfterEnd(0))); + expect(settled()).toEqual([1, 1]); + + // A write made soon after repeats the step on purpose: the orchestrator's + // ttl stamp is its retry when the surface failed a call. + await handler(write(minutesAfterEnd(4))); + expect(settled()).toEqual([2, 2]); + + // A later one does not, for example the preview of a later push to the branch. + // The end of the task decides, also when the write moves updated_at. + await handler(write(minutesAfterEnd(6), { + completed_at: { S: minutesAfterEnd(0) }, + updated_at: { S: minutesAfterEnd(6) }, + screenshot_url: { S: 'https://cdn.example/later-push.png' }, + })); + expect(settled()).toEqual([2, 2]); + + // A record from before #1048 has no completed_at: its updated_at is the write that ended the task. + await handler(write(minutesAfterEnd(6), { updated_at: { S: minutesAfterEnd(0) } })); + expect(settled()).toEqual([2, 2]); + + // The panel is refreshed every time: a late write is how a preview reaches it. + expect(upsertStatusCommentMock).toHaveBeenCalledTimes(4); + }); + test('a genuinely FAILED child also reverts state + swaps reaction to ❌', async () => { revertIssueToNotStartedMock.mockReset().mockResolvedValue(true); swapIssueReactionMock.mockReset().mockResolvedValue(true); @@ -2367,6 +2422,22 @@ describe('orchestration-reconciler handler — an event of a task that no longer expect(revertIssueToNotStartedMock).not.toHaveBeenCalled(); }); + test('a late write that is the first to reach the row fails the child and skips its dependents: only the issue is left alone', async () => { + const store = orchestrationStore([ + { sub_issue_id: 'A', child_status: 'released', child_task_id: 'TA' }, + { sub_issue_id: 'B', depends_on: ['A'], child_status: 'blocked' }, + ]); + const record = taskRecord({ task_id: 'TA', status: 'FAILED', orchestration_id: 'orch_1', written_at: '2026-11-24T10:06:00Z' }); + Object.assign(record.dynamodb!.NewImage!, { completed_at: { S: '2026-11-24T10:00:00Z' } }); + await handler({ Records: [record] } as never); + + expect(store.status('A')).toBe('failed'); + expect(store.status('B')).toBe('skipped'); + expect(upsertStatusCommentMock).toHaveBeenCalledTimes(1); + expect(revertIssueToNotStartedMock).not.toHaveBeenCalled(); + expect(swapIssueReactionMock).not.toHaveBeenCalledWith(expect.anything(), 'A', 'x'); + }); + test.each([ ['the first delivery', 'released'], ['a redelivery, after the first one died before it skipped the dependents,', 'failed'], From 8c99a7663c5c4365c9160772bf968b2524639898 Mon Sep 17 00:00:00 2001 From: bgagent Date: Tue, 24 Nov 2026 22:23:33 -0600 Subject: [PATCH 04/11] fix(cdk): publish a guardrail version only when the guardrail changes createVersion() of the alpha library names the version resource after an unresolved token (issue 38674 of aws/aws-cdk). aws-cdk-lib starts its token counter at a random number, so the name differed from one synthesis to the next and about nine deploys in ten replaced the version of the input guardrail. Since PR 904 the replaced version is retained, because a retained version of the orchestrator function can still name it. A long-lived stack therefore reached Bedrock's quota of 20 versions per guardrail, which cannot be raised, and deploys failed and rolled back until versions were deleted by hand. A real change of the guardrail, on the other hand, was published only by the same chance. The stack now creates the version itself, under a construct id that ends in a hash of the guardrail's CloudFormation properties (without tags) and of the description. A deploy publishes a version when the guardrail changed and only then, and the version stays retained. The name is computed where the version is created, so synthesis fails when the guardrail is changed after that. The network tests no longer map the guardrail version id between the two topologies. The first deploy with this change publishes one more version, because the logical id changes one last time. A guardrail at its quota has to be cleaned up first: see "Deploys stop once the input guardrail reaches its version quota" in the deployment guide. Old versions are not deleted by this change. Closes #1079 --- cdk/src/stacks/agent.ts | 77 ++++++++++++---- cdk/test/stacks/agent.test.ts | 91 ++++++++++++++++++- cdk/test/stacks/network.test.ts | 20 +--- ...ADR-023-cloudformation-stack-boundaries.md | 7 +- docs/guides/DEPLOYMENT_GUIDE.md | 52 ++++++++++- docs/guides/DEVELOPER_GUIDE.md | 4 +- ...Adr-023-cloudformation-stack-boundaries.md | 7 +- .../developer-guide/Repository-preparation.md | 4 +- .../docs/getting-started/Deployment-guide.md | 52 ++++++++++- 9 files changed, 267 insertions(+), 47 deletions(-) diff --git a/cdk/src/stacks/agent.ts b/cdk/src/stacks/agent.ts index 276100253..90ea1e88d 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -17,9 +17,11 @@ * SOFTWARE. */ +import { createHash } from 'node:crypto'; import * as path from 'path'; import * as bedrock from '@aws-cdk/aws-bedrock-alpha'; import { ArnFormat, AspectPriority, Aspects, Stack, StackProps, NestedStack, RemovalPolicy, CfnOutput, CfnResource, Duration, Fn, Lazy } from 'aws-cdk-lib'; +import { CfnGuardrail, CfnGuardrailVersion } from 'aws-cdk-lib/aws-bedrock'; import * as agentcore from 'aws-cdk-lib/aws-bedrockagentcore'; import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch'; import * as ec2 from 'aws-cdk-lib/aws-ec2'; @@ -98,6 +100,52 @@ import { WEBHOOK_METRIC_NAMESPACE, WEBHOOK_SCREENING_FAILED_METRIC } from '../ha /** Max length of the Bedrock Guardrail name (CloudFormation constraint). */ const GUARDRAIL_NAME_MAX_LENGTH = 50; +/** Hex digits of the configuration hash that end the construct id of a guardrail version. */ +const GUARDRAIL_VERSION_HASH_LENGTH = 16; + +/** + * Publishes a version of the guardrail and returns its number. + * + * The construct id ends in a hash of the guardrail's CloudFormation properties and of + * the description, so a deploy publishes a version when the guardrail changed and only + * then. `createVersion()` of the alpha library names the version after an unresolved + * token (aws/aws-cdk#38674), whose text differs from one synthesis to the next: nearly + * every deploy published a version, until the guardrail reached its version quota (#1079). + * + * The properties are rendered here, not at synthesis: call this once the guardrail is + * fully configured, or synthesis fails. Tags are left out, because a deploy tag does not + * change the guardrail. + */ +export function publishGuardrailVersion(guardrail: bedrock.Guardrail, description: string): string { + const resource = guardrail.node.children.find(child => child instanceof CfnGuardrail)!; + // What CloudFormation will receive, the defaults of the alpha library included. + // The CDK names a Lambda version after the same rendering of its function. + const configuration = (): string => { + const rendered: { Resources: Record }> } + = Stack.of(guardrail).resolve(resource._toCloudFormation()); + const { Tags: _tags, ...properties } = Object.values(rendered.Resources)[0].Properties; + return JSON.stringify([properties, description]); + }; + const published = configuration(); + const hash = createHash('sha256').update(published).digest('hex'); + const version = new CfnGuardrailVersion(guardrail, `Version${hash.slice(0, GUARDRAIL_VERSION_HASH_LENGTH)}`, { + guardrailIdentifier: guardrail.guardrailId, + description, + }); + // The name is fixed now: a later change of the guardrail would reach the draft and no version. + // A property that takes a value from another stack renders differently by then, and fails too. + guardrail.node.addValidation({ + validate: () => configuration() === published ? [] : [ + 'The guardrail does not have the properties its version was named after: it was changed after ' + + 'publishGuardrailVersion(), or one of its properties takes a value from another stack.', + ], + }); + // A retained durable Lambda version also pins GUARDRAIL_VERSION. Preserve that + // immutable dependency when a change of the guardrail publishes a new version. + version.applyRemovalPolicy(RemovalPolicy.RETAIN); + return version.attrVersion; +} + /** AgentCore Runtime session lifecycle ceiling (hours) — the AgentCore maximum. */ const RUNTIME_SESSION_TIMEOUT_HOURS = 8; @@ -248,7 +296,7 @@ export class AgentStack extends Stack { /** Set when deployed with the Linear identity vault; the console then mints tokens through it. */ public readonly linearIdentityVault?: LinearIdentityVault; - // eslint-disable-next-line complexity -- predates the ceiling (123; 108 when it landed); must not grow + // eslint-disable-next-line complexity -- predates the ceiling (120; 108 when it landed); must not grow constructor(scope: Construct, id: string, props: AgentStackProps = {}) { super(scope, id, props); @@ -539,14 +587,11 @@ export class AgentStack extends Stack { ], }); - inputGuardrail.createVersion('Initial version'); - // A retained durable Lambda version also pins GUARDRAIL_VERSION. Preserve - // that immutable dependency across updates, even when CDK creates a new one. - for (const child of inputGuardrail.node.findAll()) { - if (child instanceof CfnResource && child.cfnResourceType === 'AWS::Bedrock::GuardrailVersion') { - child.applyRemovalPolicy(RemovalPolicy.RETAIN); - } - } + // The version every consumer pins: `inputGuardrail.guardrailVersion` is the working + // draft. The guardrail gets its whole configuration in the constructor above: a + // change made to it after this line would reach the draft and no published version, + // and synthesis fails on it. + const inputGuardrailVersion = publishGuardrailVersion(inputGuardrail, 'Initial version'); // --- TaskApi is constructed before the orchestrator (which it needs the // ARN of) and before the Runtime (which it needs the ARN of, for the @@ -618,7 +663,7 @@ export class AgentStack extends Stack { apiKeyTable: apiKeyTable.table, orchestratorFunctionArn: lazyOrchestratorArn, guardrailId: inputGuardrail.guardrailId, - guardrailVersion: inputGuardrail.guardrailVersion, + guardrailVersion: inputGuardrailVersion, ...(agentCoreEnabled && { agentCoreStopSessionRuntimeArn: lazyRuntimeArn }), ...(ecsEnabled && { ecsClusterArn: lazyEcsClusterArn }), traceArtifactsBucket: traceArtifactsBucket.bucket, @@ -1416,7 +1461,7 @@ export class AgentStack extends Stack { githubTokenSecretArn: githubTokenSecret.secretArn, memoryId: agentMemory.memory.memoryId, guardrailId: inputGuardrail.guardrailId, - guardrailVersion: inputGuardrail.guardrailVersion, + guardrailVersion: inputGuardrailVersion, attachmentsBucket: attachmentsBucket.bucket, ...(agentRegistry && { agentRegistryId: agentRegistry.registryId }), // ADR-021 P2: non-secret platform identifiers the orchestrator forwards to @@ -1597,7 +1642,7 @@ export class AgentStack extends Stack { repoTable: repoTable.table, orchestratorFunctionArn: orchestrator.alias.functionArn, guardrailId: inputGuardrail.guardrailId, - guardrailVersion: inputGuardrail.guardrailVersion, + guardrailVersion: inputGuardrailVersion, }); // --- Slack App setup outputs --- @@ -1694,7 +1739,7 @@ export class AgentStack extends Stack { orchestrationTable: orchestrationTable.table, orchestratorFunctionArn: orchestrator.alias.functionArn, guardrailId: inputGuardrail.guardrailId, - guardrailVersion: inputGuardrail.guardrailVersion, + guardrailVersion: inputGuardrailVersion, // Throttle the seed-time root release to the free concurrency // budget so a wide-root epic doesn't over-release roots admission then // hard-fails (an unrecoverable failure — a root has no predecessor for @@ -1737,7 +1782,7 @@ export class AgentStack extends Stack { repoTable.table.grantReadData(orchestrationReconciler.fn); orchestrationReconciler.fn.addEnvironment('REPO_TABLE_NAME', repoTable.table.tableName); orchestrationReconciler.fn.addEnvironment('GUARDRAIL_ID', inputGuardrail.guardrailId); - orchestrationReconciler.fn.addEnvironment('GUARDRAIL_VERSION', inputGuardrail.guardrailVersion); + orchestrationReconciler.fn.addEnvironment('GUARDRAIL_VERSION', inputGuardrailVersion); orchestrationReconciler.fn.addEnvironment( 'ORCHESTRATOR_FUNCTION_ARN', orchestrator.alias.functionArn, @@ -1807,7 +1852,7 @@ export class AgentStack extends Stack { repoTable.table.grantReadData(strandedOrchestrationReconciler.fn); strandedOrchestrationReconciler.fn.addEnvironment('REPO_TABLE_NAME', repoTable.table.tableName); strandedOrchestrationReconciler.fn.addEnvironment('GUARDRAIL_ID', inputGuardrail.guardrailId); - strandedOrchestrationReconciler.fn.addEnvironment('GUARDRAIL_VERSION', inputGuardrail.guardrailVersion); + strandedOrchestrationReconciler.fn.addEnvironment('GUARDRAIL_VERSION', inputGuardrailVersion); strandedOrchestrationReconciler.fn.addToRolePolicy(new iam.PolicyStatement({ actions: ['lambda:InvokeFunction'], resources: [orchestrator.alias.functionArn], @@ -1957,7 +2002,7 @@ export class AgentStack extends Stack { repoTable: repoTable.table, orchestratorFunctionArn: orchestrator.alias.functionArn, guardrailId: inputGuardrail.guardrailId, - guardrailVersion: inputGuardrail.guardrailVersion, + guardrailVersion: inputGuardrailVersion, // Lets the processor fetch, screen, and store Jira media attachments at // task-admission time. Same bucket the orchestrator hydrates from. attachmentsBucket: attachmentsBucket.bucket, diff --git a/cdk/test/stacks/agent.test.ts b/cdk/test/stacks/agent.test.ts index 91f839696..05313fdde 100644 --- a/cdk/test/stacks/agent.test.ts +++ b/cdk/test/stacks/agent.test.ts @@ -18,9 +18,13 @@ */ import * as fs from 'fs'; +import { createHash } from 'node:crypto'; import * as path from 'path'; -import { App, AspectPriority, Aspects, NestedStack } from 'aws-cdk-lib'; +import * as bedrock from '@aws-cdk/aws-bedrock-alpha'; +import { App, AspectPriority, Aspects, NestedStack, Stack } from 'aws-cdk-lib'; import { Match, Template } from 'aws-cdk-lib/assertions'; +import { CfnGuardrail } from 'aws-cdk-lib/aws-bedrock'; +import * as sqs from 'aws-cdk-lib/aws-sqs'; import { BEDROCK_GEO_REGION_CONTEXT_KEY, DEFAULT_BEDROCK_GEO_REGION, @@ -28,7 +32,7 @@ import { } from '../../src/constructs/bedrock-models'; import * as lambdaMicrovmCompute from '../../src/constructs/lambda-microvm-compute'; import { buildAppId, SolutionUaAspect } from '../../src/constructs/solution-ua-aspect'; -import { AgentStack } from '../../src/stacks/agent'; +import { AgentStack, publishGuardrailVersion } from '../../src/stacks/agent'; describe('AgentStack', () => { let template: Template; @@ -556,8 +560,9 @@ describe('AgentStack', () => { * * (The full 25k-line template was also diffed pre/post out-of-band and is * identical modulo CDK's own local synth non-determinism — asset hashes, - * custom-resource timestamps, the InputGuardrail version logical id — which - * differ between two synths of the SAME tree and so cannot be asserted here. + * custom-resource timestamps and, at the time, the InputGuardrail version + * logical id (stable since #1079) — which differ between two synths of the + * SAME tree and so cannot be asserted here. * The Bedrock resources are the change's entire blast radius.) */ test('default-context Bedrock grants are the exact expected set, nothing wider', () => { @@ -1256,6 +1261,84 @@ describe('AgentStack', () => { // operators subscribe Slack / PagerDuty / email themselves. template.resourceCountIs('AWS::SNS::Subscription', 0); }); + + test('every GUARDRAIL_VERSION is the one published version of the input guardrail, which is retained (#1079)', () => { + const versions = template.findResources('AWS::Bedrock::GuardrailVersion'); + expect(Object.values(versions)).toEqual([expect.objectContaining({ DeletionPolicy: 'Retain', UpdateReplacePolicy: 'Retain' })]); + const published = { 'Fn::GetAtt': [Object.keys(versions)[0], 'Version'] }; + // A nested template would name the version by a stack parameter: read the value the root passes. + const pinned = [{ template, parameters: {} as Record }, ...nestedStacks].flatMap(stack => + Object.values(stack.template.findResources('AWS::Lambda::Function')) + .map(fn => fn.Properties.Environment?.Variables?.GUARDRAIL_VERSION) + .filter(value => value !== undefined) + .map(value => stack.parameters[value.Ref] ?? value)); + expect(pinned.length).toBeGreaterThan(0); + // The guardrail's own Version attribute is DRAFT, which follows every edit instead of pinning one. + expect(pinned).toEqual(pinned.map(() => published)); + + // The version is named after the guardrail as CloudFormation receives it. A change made to + // the guardrail after its version was published fails the synthesis; this pins the name itself. + const [guardrail] = Object.values(template.findResources('AWS::Bedrock::Guardrail')); + const { Tags: _tags, ...properties } = guardrail.Properties; + const [[versionId, version]] = Object.entries(versions); + const hash = createHash('sha256').update(JSON.stringify([properties, version.Properties.Description])).digest('hex'); + // The whole id: the guardrail's construct id, the hash, and the eight characters the CDK appends. + expect(versionId).toMatch(new RegExp(`^InputGuardrailVersion${hash.slice(0, 16)}[0-9A-F]{8}$`)); + }); +}); + +describe('publishGuardrailVersion (#1079)', () => { + interface Change { inFront?: boolean; tag?: boolean; inputStrength?: bedrock.ContentFilterStrength; description?: string } + + // TEST-CONVENTION EXEMPTION (cdk/AGENTS.md "synth once in beforeAll"): each case + // compares two syntheses, and the stack holds one guardrail. + /** Logical id of the version published for a guardrail in a new stack. */ + function versionId(change: Change = {}): string { + const stack = new Stack(new App(), 'Stack'); + if (change.inFront) new sqs.Queue(stack, 'InFront'); + const guardrail = new bedrock.Guardrail(stack, 'InputGuardrail', { + guardrailName: 'input', + contentFilters: [{ + type: bedrock.ContentFilterType.PROMPT_ATTACK, + inputStrength: change.inputStrength ?? bedrock.ContentFilterStrength.MEDIUM, + outputStrength: bedrock.ContentFilterStrength.NONE, + }], + }); + // Tags.of() would set the tag at synthesis, after the version got its name: set it on the resource now. + if (change.tag) guardrail.node.children.find(child => child instanceof CfnGuardrail)!.cdkTagManager.setTag('github:sha', 'abc'); + publishGuardrailVersion(guardrail, change.description ?? 'Initial version'); + const ids = Object.keys(Template.fromStack(stack).findResources('AWS::Bedrock::GuardrailVersion')); + expect(ids).toHaveLength(1); + return ids[0]; + } + + // Two syntheses in one process differ in their token numbers, as two deploys do. + test.each<[string, Change]>([ + ['in a second synthesis of the same tree', {}], + ['with a construct in front of the guardrail', { inFront: true }], + ['with a tag on the guardrail', { tag: true }], + ])('names the version the same %s', (_case, change) => { + expect(versionId(change)).toBe(versionId()); + }); + + test.each<[string, Change]>([ + ['the configuration of the guardrail', { inputStrength: bedrock.ContentFilterStrength.HIGH }], + ['the description of the version', { description: 'Second version' }], + ])('names the version anew when %s changes', (_case, change) => { + expect(versionId(change)).not.toBe(versionId()); + }); + + test('fails the synthesis when the guardrail changes after its version was published', () => { + const stack = new Stack(new App(), 'Stack'); + const guardrail = new bedrock.Guardrail(stack, 'InputGuardrail', { guardrailName: 'input' }); + publishGuardrailVersion(guardrail, 'Initial version'); + guardrail.addContentFilter({ + type: bedrock.ContentFilterType.PROMPT_ATTACK, + inputStrength: bedrock.ContentFilterStrength.MEDIUM, + outputStrength: bedrock.ContentFilterStrength.NONE, + }); + expect(() => Template.fromStack(stack)).toThrow('it was changed after publishGuardrailVersion()'); + }); }); /** diff --git a/cdk/test/stacks/network.test.ts b/cdk/test/stacks/network.test.ts index a4b17daf9..16501de2e 100644 --- a/cdk/test/stacks/network.test.ts +++ b/cdk/test/stacks/network.test.ts @@ -291,21 +291,11 @@ describe.each(['agentcore', 'ecs', 'lambda-microvm'] as const)('%s network extra const [beforeVersionId, beforeVersion] = versionOf(inline.application); const [afterVersionId, afterVersion] = versionOf(split.application); expect(withoutMetadata(afterVersion)).toEqual(withoutMetadata(beforeVersion)); - // The existing alpha Guardrail hashes unresolved tokens, so its version ID - // (and the orchestrator version consuming it) can change between syntheses. - // Compare their definitions before mapping only these immutable version IDs. - // The census stability check reports the real churn without normalization. - const guardrailVersion = (template: TemplateJson): [string, TemplateJson] => { - const versions = Object.entries(template.Resources as Record) - .filter(([, resource]) => resource.Type === 'AWS::Bedrock::GuardrailVersion'); - expect(versions).toHaveLength(1); - return versions[0]; - }; - const [beforeGuardrailId, beforeGuardrail] = guardrailVersion(inline.application); - const [afterGuardrailId, afterGuardrail] = guardrailVersion(split.application); - expect(withoutMetadata(afterGuardrail)).toEqual(withoutMetadata(beforeGuardrail)); - const versionIds = new Map([[afterVersionId, beforeVersionId], [afterGuardrailId, beforeGuardrailId]]); - const originalId = (id: string): string => versionIds.get(id) ?? id; + // The ECS orchestrator's environment names the private subnets: by reference + // inline, by import in the split topology. The logical ID of its version hashes + // that, so map this one immutable version ID there. On the other backends, and + // for the guardrail version on every backend, both templates must have the same ID. + const originalId = (id: string): string => compute === 'ecs' && id === afterVersionId ? beforeVersionId : id; function normalize(value: any): any { if (Array.isArray(value)) return value.map(normalize); if (value && typeof value === 'object') { diff --git a/docs/decisions/ADR-023-cloudformation-stack-boundaries.md b/docs/decisions/ADR-023-cloudformation-stack-boundaries.md index 29cd7b5b5..fb29138d7 100644 --- a/docs/decisions/ADR-023-cloudformation-stack-boundaries.md +++ b/docs/decisions/ADR-023-cloudformation-stack-boundaries.md @@ -2,7 +2,7 @@ **Status:** proposed **Date:** 2026-09-21 -**Last-updated:** 2026-11-21 +**Last-updated:** 2026-11-24 **Issue:** [#852](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/852) Per the [ADR lifecycle](./README.md#lifecycle), this decision remains proposed while its implementing PR is in review and becomes accepted when that PR merges. This record does not approve or waive the existing-stack migration criteria in #852. @@ -27,7 +27,7 @@ Live review of an earlier #912 revision found that broad retention blocks failed The 122-profile product covers all single-backend/service/image combinations in both topologies, supplemental alert/fork/consent options, explicit three-AZ pins, expanded model grants, every multi-backend set at default and widest settings, and legacy additive selectors. The expanded-model profiles add synthetic model IDs to the platform defaults, enough for CDK to split the policy of the SessionRole and of each backend's compute role into overflow policies; they do not assert live model availability. The audit exceptions of each of those roles follow its generated overflow policies: the SessionRole's remain scoped to tenant object prefixes and literal model grants, and a compute role's overflow policies carry the exception of its base policy. A profile marked over budget must fail at the production 490-resource ceiling for the application stack; an unrelated error or unexpected success fails the gate. Since the scheduled-maintenance and MicroVM subsystems moved into nested stacks, no sampled profile is over budget. Real CDK metadata is included. The census records per-template measurements and source provenance with bundling and asset staging disabled; it does not measure a deployed stack. -Network tests compare moved logical IDs and service properties, the complete export interface, application data resources and lifecycle policies, shared API routes and permissions, attribution and one-way dependencies. Their comparisons control the clock and account for the existing alpha guardrail and orchestrator version IDs. The independent-process `--check-stability` diagnostic keeps timestamps, IDs and asset hashes intact and reports existing churn; passing budget checks does not imply deterministic synthesis. +Network tests compare moved logical IDs and service properties, the complete export interface, application data resources and lifecycle policies, shared API routes and permissions, attribution and one-way dependencies. Their comparisons control the clock and account for the orchestrator version ID on ECS, which differs between the topologies with the subnet references in the function's environment. The independent-process `--check-stability` diagnostic keeps timestamps, IDs and asset hashes intact and reports existing churn; passing budget checks does not imply deterministic synthesis. `networkReservedAzs` preserves unused address slots when removing trailing AZs. Tests verify that the target application can use the old network, release the removed export, and keep every remaining subnet's properties. The [application-first procedure](../guides/DEPLOYMENT_GUIDE.md#reducing-azs-in-an-existing-split-network) is separate from moving an inline network into another stack. Physical-ID preservation and rollback in AWS still require live verification. @@ -39,7 +39,7 @@ The following remain under #852 and need separate review and releases before a s - **Blueprint downgrade protection:** refuse an unsafe return from managed ownership to the legacy writer even when a context flag is omitted. Prove `max_turns`, `compute_type`, `onboarded_at` and other CLI overrides survive updates and rollback. A green deployment must not hide row replacement or tombstoning. - **Ownership release and re-onboarding:** adoption must have a defined release path. Removing a repository must not block legitimate re-onboarding for the tombstone TTL. Test retries, owner changes and out-of-order callbacks. - **Ledger lifecycle and bootstrap coverage:** establish a bounded cleanup/recovery plan for PITR-enabled ownership tables across mode changes, failures and destroy. Any future `Custom::BlueprintRepoConfig` must be represented in the bootstrap resource-action map and its coverage tests before it ships. -- **Guardrail and image normalization:** review stable version binding and Docker build-context changes separately from network ownership. They are not prerequisites for reporting truthful census differences. +- **Image normalization:** review Docker build-context changes separately from network ownership. They are not prerequisites for reporting truthful census differences. The stable version binding of the guardrail, deferred with them, shipped separately ([#1079](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1079)). - **Populated migration rehearsal:** verify refactor/import eligibility for each moved type and provider, preserve physical IDs and data, test networking and API behavior, and execute rollback. Retention must be installed on source resources before a transfer; an ordinary topology flag change is not a move. The criterion remains open, without an author-only waiver. The [teardown guidance](../guides/DEPLOYMENT_GUIDE.md#teardown-blocked-by-agentcore-network-interfaces) covers the separately observed AgentCore ENI cleanup delay, which also occurs on `main`. @@ -62,3 +62,4 @@ The [teardown guidance](../guides/DEPLOYMENT_GUIDE.md#teardown-blocked-by-agentc ## Changelog - 2026-11-21 — The validation scope also covers the overflow policies of each backend's compute role, which carry the audit exception of the role's base policy (#916). The expanded-model profiles add enough synthetic model IDs for CDK to split the policy of the SessionRole and of each compute role (decision unchanged). +- 2026-11-24 — The version of the input guardrail now has a logical ID that contains a hash of the guardrail's configuration (#1079): the stable version binding that decision 5 left as it was and that the deferred work listed for a separate review. The network tests no longer account for that ID, and account for the orchestrator version ID on ECS only; the deferred item now names the image alone (decision unchanged). diff --git a/docs/guides/DEPLOYMENT_GUIDE.md b/docs/guides/DEPLOYMENT_GUIDE.md index b2af72cb5..8947d261c 100644 --- a/docs/guides/DEPLOYMENT_GUIDE.md +++ b/docs/guides/DEPLOYMENT_GUIDE.md @@ -40,7 +40,7 @@ Replace the compute list as needed and supply image settings for MicroVM. Persis **Existing inline-to-split migration is deferred.** Do not flip `networkTopology` on an existing inline deployment. An ordinary deploy creates a new VPC and removes old resources; identical logical IDs in different stacks do not preserve physical identity. Keep the existing topology until a separately reviewed migration has established resource-type eligibility, source retention and cleanup behavior, an ownership mapping, physical-ID/data preservation, and rollback on a populated disposable deployment. The `cdk refactor --unstable=refactor` criterion in #852 remains open; it is not waived or satisfied by synthesis tests. -This change does not install broad retention, change the Blueprint provider, create an ownership ledger, or replace the guardrail versioning scheme. Those prerequisites belong in separate releases. CloudFormation exports still prevent removing a network used by the application; switching back to `inline` is not an automatic rollback. See [ADR-023's deferred work](../decisions/ADR-023-cloudformation-stack-boundaries.md#deferred-migration-work). +This change does not install broad retention, change the Blueprint provider or create an ownership ledger. Those prerequisites belong in separate releases. The guardrail versioning scheme, once listed with them, was replaced separately ([#1079](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1079)). CloudFormation exports still prevent removing a network used by the application; switching back to `inline` is not an automatic rollback. See [ADR-023's deferred work](../decisions/ADR-023-cloudformation-stack-boundaries.md#deferred-migration-work). Stacks used to test earlier revisions with `blueprintProvisioning=prepare|adopt|managed` or the broad retention aspect require a separate recovery plan before adopting this narrowed version. Returning those stacks directly to the original Blueprint provider can overwrite or soft-delete repository rows. Synthesis rejects the removed `blueprintProvisioning` and `guardrailVersionMigration` context keys instead of silently ignoring them; removing those keys does not make an experimental stack safe to update. Preserve its deployed templates, repository data and ledger inventory; the removed experimental modes are not an upgrade path supported by this release. @@ -521,6 +521,56 @@ The first deploy of a version that sets `InstallLatestAwsSdk` to `false` changes In that call, `ModelInvocationLogging` writes the stack's log group and role to the Bedrock model-invocation logging configuration of the account and Region, which replaces a configuration that another deployment or a manual change put there. `DnsFirewall/FirewallConfig` sets the DNS Firewall of the VPC to fail open. A Blueprint's `RepoConfigCR` writes its repository record, as on every deploy. +### Deploys stop once the input guardrail reaches its version quota (#1079) + +**Affects:** a stack deployed from a version between [#904](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/pull/904) and the fix of [#1079](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1079). Nearly every deploy of such a version published a new version of the input guardrail and kept the one before it, also when the guardrail had not changed. + +**Symptom:** the deploy fails on the guardrail version and the stack rolls back to `UPDATE_ROLLBACK_COMPLETE`. Nearly every later deploy fails in the same way until old versions are deleted. + +``` +CREATE_FAILED AWS::Bedrock::GuardrailVersion InputGuardrail/GuardrailVersion-... +Resource handler returned message: "You have exceeded the service quota limit for ..." +``` + +**Root cause:** the logical ID of the version came from a value that differs from one synthesis to the next, so CloudFormation replaced the version on nearly every deploy. Since #904 it keeps the replaced version, because a retained version of the orchestrator function can still name it. Bedrock allows 20 versions per guardrail, and the quota cannot be raised (*Versions per guardrail* in the [Amazon Bedrock service quotas](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#limits_bedrock)). The stack this was seen on had 19 numbered versions and its `DRAFT`. + +**Resolution:** with the fix, the logical ID contains a hash of the guardrail's configuration. A deploy publishes a version only when that configuration changed, and still keeps the one before it. Two things remain to do by hand: + +- The first deploy with the fix publishes one more version, because the logical ID changes one last time. A guardrail at its quota needs the cleanup below before that deploy. +- The versions that earlier deploys left behind stay, and count against the quota, until they are deleted. So does each version that a later change of the guardrail replaces, and the version of a deploy that publishes one and then rolls back: an execution started during that deploy can still name it. + +Find the guardrail, whose name is `task-input-guardrail-` cut off after 50 characters, and list its versions: + +```bash +aws bedrock list-guardrails \ + --query "guardrails[?name=='task-input-guardrail-'].id" --output text +aws bedrock list-guardrails --guardrail-identifier \ + --query 'guardrails[].[version,createdAt]' --output text +``` + +List the versions that are in use. Each row is a function configuration that names this guardrail in `GUARDRAIL_ID`, with the guardrail version it names in `GUARDRAIL_VERSION`: + +```bash +aws lambda list-functions --function-version ALL \ + --query "Functions[?Environment.Variables.GUARDRAIL_ID==''].[FunctionName,Version,Environment.Variables.GUARDRAIL_VERSION]" \ + --output table +``` + +Keep the guardrail version of the rows whose function version is `$LATEST`: the stack runs on it. The rows with a numbered function version are the published versions of the orchestrator function, which the stack retains as well. A durable execution ends on the function version it started on, so also keep the guardrail version of each published version that still has an unfinished execution. The ARN of an execution names its function version. The loop passes one status per call, as the Lambda API reference requires: + +```bash +for state in RUNNING PAUSING PAUSED; do + aws lambda list-durable-executions-by-function --function-name \ + --statuses "$state" --query 'DurableExecutions[].DurableExecutionArn' +done +``` + +Delete every other numbered version. Always pass `--guardrail-version`: without it, the command deletes the guardrail and all of its versions. + +```bash +aws bedrock delete-guardrail --guardrail-identifier --guardrail-version +``` + ### AgentCore unsupported Availability Zones **Affects:** Fresh deploys in accounts whose default Availability Zones don't line up with the zones AgentCore supports for the region. diff --git a/docs/guides/DEVELOPER_GUIDE.md b/docs/guides/DEVELOPER_GUIDE.md index daf425799..5053ba153 100644 --- a/docs/guides/DEVELOPER_GUIDE.md +++ b/docs/guides/DEVELOPER_GUIDE.md @@ -112,9 +112,9 @@ mise //cdk:census -- --output /tmp/stack-census Use `--list` to see the profiles and `--profile NAME` to select them. The census runs the production app with fixed account/AZ inputs, CDK metadata enabled and bundling/staging disabled. It records template inventories, counts, bytes, dependencies and source provenance. The production app sets CDK's `@aws-cdk/core:stackResourceLimit` before any stack is constructed, so actual operator configurations outside the census also fail above 490. Context overrides may tighten but cannot raise the limit. `--max-resources` can only tighten the census audit ceiling. -`--check-stability` runs each selected profile twice in independent processes and fails on differences. It does not normalize away timestamps, logical IDs or asset hashes. The existing Blueprint callbacks embed synthesis-time timestamps, and the alpha Bedrock guardrail uses token-derived version IDs; unchanged source can therefore fail this optional diagnostic. Deterministic Blueprint provisioning, guardrail versioning and Docker build-context changes are deferred. Passing the budget gate is not a claim of repeatable synthesis or live resource preservation. +`--check-stability` runs each selected profile twice in independent processes and fails on differences. It does not normalize away timestamps, logical IDs or asset hashes. The existing Blueprint callbacks embed synthesis-time timestamps; unchanged source can therefore fail this optional diagnostic. The version of the input guardrail no longer differs between two syntheses: its logical ID contains a hash of the guardrail's configuration ([#1079](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1079)). Deterministic Blueprint provisioning and Docker build-context changes are deferred. Passing the budget gate is not a claim of repeatable synthesis or live resource preservation. -Network tests compare the moved definitions, generated Name tags, endpoint security-group descriptions, exports, application service properties, shared API resources, solution attribution and provenance tags. Comparison tests fix the clock and account for existing immutable guardrail/orchestrator version IDs; the census reports those real differences. `networkReservedAzs` reserves unused address slots so removing a trailing AZ need not shift remaining subnet CIDRs. Follow the [staged AZ reduction procedure](./DEPLOYMENT_GUIDE.md#reducing-azs-in-an-existing-split-network) to release old imports before changing the network. +Network tests compare the moved definitions, generated Name tags, endpoint security-group descriptions, exports, application service properties, shared API resources, solution attribution and provenance tags. Comparison tests fix the clock; the census does not, and reports the Blueprint timestamps. The tests also map one immutable version ID that differs between the topologies: on ECS the orchestrator's environment names the private subnets, by reference inline and by import in the split topology, and the logical ID of its function version hashes that. `networkReservedAzs` reserves unused address slots so removing a trailing AZ need not shift remaining subnet CIDRs. Follow the [staged AZ reduction procedure](./DEPLOYMENT_GUIDE.md#reducing-azs-in-an-existing-split-network) to release old imports before changing the network. Existing inline-to-split migration remains deferred under [#852](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/852). A populated `cdk refactor`/import and rollback rehearsal is still required before a supported migration procedure can be published. Retention and Blueprint ownership handoff must be separately reviewed and released; this change keeps existing removal policies and the existing Blueprint provider. The concrete follow-up requirements are recorded in [ADR-023](../decisions/ADR-023-cloudformation-stack-boundaries.md#deferred-migration-work). See [Network stack topology](./DEPLOYMENT_GUIDE.md#network-stack-topology) for fresh-install guidance and migration limits. diff --git a/docs/src/content/docs/decisions/Adr-023-cloudformation-stack-boundaries.md b/docs/src/content/docs/decisions/Adr-023-cloudformation-stack-boundaries.md index 3e1c7400c..182a8b606 100644 --- a/docs/src/content/docs/decisions/Adr-023-cloudformation-stack-boundaries.md +++ b/docs/src/content/docs/decisions/Adr-023-cloudformation-stack-boundaries.md @@ -4,7 +4,7 @@ title: "ADR-023: Optional network stack and deployment budgets" **Status:** proposed **Date:** 2026-09-21 -**Last-updated:** 2026-11-21 +**Last-updated:** 2026-11-24 **Issue:** [#852](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/852) Per the [ADR lifecycle](/sample-autonomous-cloud-coding-agents/decisions/readme#lifecycle), this decision remains proposed while its implementing PR is in review and becomes accepted when that PR merges. This record does not approve or waive the existing-stack migration criteria in #852. @@ -29,7 +29,7 @@ Live review of an earlier #912 revision found that broad retention blocks failed The 122-profile product covers all single-backend/service/image combinations in both topologies, supplemental alert/fork/consent options, explicit three-AZ pins, expanded model grants, every multi-backend set at default and widest settings, and legacy additive selectors. The expanded-model profiles add synthetic model IDs to the platform defaults, enough for CDK to split the policy of the SessionRole and of each backend's compute role into overflow policies; they do not assert live model availability. The audit exceptions of each of those roles follow its generated overflow policies: the SessionRole's remain scoped to tenant object prefixes and literal model grants, and a compute role's overflow policies carry the exception of its base policy. A profile marked over budget must fail at the production 490-resource ceiling for the application stack; an unrelated error or unexpected success fails the gate. Since the scheduled-maintenance and MicroVM subsystems moved into nested stacks, no sampled profile is over budget. Real CDK metadata is included. The census records per-template measurements and source provenance with bundling and asset staging disabled; it does not measure a deployed stack. -Network tests compare moved logical IDs and service properties, the complete export interface, application data resources and lifecycle policies, shared API routes and permissions, attribution and one-way dependencies. Their comparisons control the clock and account for the existing alpha guardrail and orchestrator version IDs. The independent-process `--check-stability` diagnostic keeps timestamps, IDs and asset hashes intact and reports existing churn; passing budget checks does not imply deterministic synthesis. +Network tests compare moved logical IDs and service properties, the complete export interface, application data resources and lifecycle policies, shared API routes and permissions, attribution and one-way dependencies. Their comparisons control the clock and account for the orchestrator version ID on ECS, which differs between the topologies with the subnet references in the function's environment. The independent-process `--check-stability` diagnostic keeps timestamps, IDs and asset hashes intact and reports existing churn; passing budget checks does not imply deterministic synthesis. `networkReservedAzs` preserves unused address slots when removing trailing AZs. Tests verify that the target application can use the old network, release the removed export, and keep every remaining subnet's properties. The [application-first procedure](/sample-autonomous-cloud-coding-agents/getting-started/deployment-guide#reducing-azs-in-an-existing-split-network) is separate from moving an inline network into another stack. Physical-ID preservation and rollback in AWS still require live verification. @@ -41,7 +41,7 @@ The following remain under #852 and need separate review and releases before a s - **Blueprint downgrade protection:** refuse an unsafe return from managed ownership to the legacy writer even when a context flag is omitted. Prove `max_turns`, `compute_type`, `onboarded_at` and other CLI overrides survive updates and rollback. A green deployment must not hide row replacement or tombstoning. - **Ownership release and re-onboarding:** adoption must have a defined release path. Removing a repository must not block legitimate re-onboarding for the tombstone TTL. Test retries, owner changes and out-of-order callbacks. - **Ledger lifecycle and bootstrap coverage:** establish a bounded cleanup/recovery plan for PITR-enabled ownership tables across mode changes, failures and destroy. Any future `Custom::BlueprintRepoConfig` must be represented in the bootstrap resource-action map and its coverage tests before it ships. -- **Guardrail and image normalization:** review stable version binding and Docker build-context changes separately from network ownership. They are not prerequisites for reporting truthful census differences. +- **Image normalization:** review Docker build-context changes separately from network ownership. They are not prerequisites for reporting truthful census differences. The stable version binding of the guardrail, deferred with them, shipped separately ([#1079](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1079)). - **Populated migration rehearsal:** verify refactor/import eligibility for each moved type and provider, preserve physical IDs and data, test networking and API behavior, and execute rollback. Retention must be installed on source resources before a transfer; an ordinary topology flag change is not a move. The criterion remains open, without an author-only waiver. The [teardown guidance](/sample-autonomous-cloud-coding-agents/getting-started/deployment-guide#teardown-blocked-by-agentcore-network-interfaces) covers the separately observed AgentCore ENI cleanup delay, which also occurs on `main`. @@ -64,3 +64,4 @@ The [teardown guidance](/sample-autonomous-cloud-coding-agents/getting-started/d ## Changelog - 2026-11-21 — The validation scope also covers the overflow policies of each backend's compute role, which carry the audit exception of the role's base policy (#916). The expanded-model profiles add enough synthetic model IDs for CDK to split the policy of the SessionRole and of each compute role (decision unchanged). +- 2026-11-24 — The version of the input guardrail now has a logical ID that contains a hash of the guardrail's configuration (#1079): the stable version binding that decision 5 left as it was and that the deferred work listed for a separate review. The network tests no longer account for that ID, and account for the orchestrator version ID on ECS only; the deferred item now names the image alone (decision unchanged). diff --git a/docs/src/content/docs/developer-guide/Repository-preparation.md b/docs/src/content/docs/developer-guide/Repository-preparation.md index c6d4aadd4..830b7682a 100644 --- a/docs/src/content/docs/developer-guide/Repository-preparation.md +++ b/docs/src/content/docs/developer-guide/Repository-preparation.md @@ -83,9 +83,9 @@ mise //cdk:census -- --output /tmp/stack-census Use `--list` to see the profiles and `--profile NAME` to select them. The census runs the production app with fixed account/AZ inputs, CDK metadata enabled and bundling/staging disabled. It records template inventories, counts, bytes, dependencies and source provenance. The production app sets CDK's `@aws-cdk/core:stackResourceLimit` before any stack is constructed, so actual operator configurations outside the census also fail above 490. Context overrides may tighten but cannot raise the limit. `--max-resources` can only tighten the census audit ceiling. -`--check-stability` runs each selected profile twice in independent processes and fails on differences. It does not normalize away timestamps, logical IDs or asset hashes. The existing Blueprint callbacks embed synthesis-time timestamps, and the alpha Bedrock guardrail uses token-derived version IDs; unchanged source can therefore fail this optional diagnostic. Deterministic Blueprint provisioning, guardrail versioning and Docker build-context changes are deferred. Passing the budget gate is not a claim of repeatable synthesis or live resource preservation. +`--check-stability` runs each selected profile twice in independent processes and fails on differences. It does not normalize away timestamps, logical IDs or asset hashes. The existing Blueprint callbacks embed synthesis-time timestamps; unchanged source can therefore fail this optional diagnostic. The version of the input guardrail no longer differs between two syntheses: its logical ID contains a hash of the guardrail's configuration ([#1079](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1079)). Deterministic Blueprint provisioning and Docker build-context changes are deferred. Passing the budget gate is not a claim of repeatable synthesis or live resource preservation. -Network tests compare the moved definitions, generated Name tags, endpoint security-group descriptions, exports, application service properties, shared API resources, solution attribution and provenance tags. Comparison tests fix the clock and account for existing immutable guardrail/orchestrator version IDs; the census reports those real differences. `networkReservedAzs` reserves unused address slots so removing a trailing AZ need not shift remaining subnet CIDRs. Follow the [staged AZ reduction procedure](/sample-autonomous-cloud-coding-agents/getting-started/deployment-guide#reducing-azs-in-an-existing-split-network) to release old imports before changing the network. +Network tests compare the moved definitions, generated Name tags, endpoint security-group descriptions, exports, application service properties, shared API resources, solution attribution and provenance tags. Comparison tests fix the clock; the census does not, and reports the Blueprint timestamps. The tests also map one immutable version ID that differs between the topologies: on ECS the orchestrator's environment names the private subnets, by reference inline and by import in the split topology, and the logical ID of its function version hashes that. `networkReservedAzs` reserves unused address slots so removing a trailing AZ need not shift remaining subnet CIDRs. Follow the [staged AZ reduction procedure](/sample-autonomous-cloud-coding-agents/getting-started/deployment-guide#reducing-azs-in-an-existing-split-network) to release old imports before changing the network. Existing inline-to-split migration remains deferred under [#852](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/852). A populated `cdk refactor`/import and rollback rehearsal is still required before a supported migration procedure can be published. Retention and Blueprint ownership handoff must be separately reviewed and released; this change keeps existing removal policies and the existing Blueprint provider. The concrete follow-up requirements are recorded in [ADR-023](/sample-autonomous-cloud-coding-agents/decisions/adr-023-cloudformation-stack-boundaries#deferred-migration-work). See [Network stack topology](/sample-autonomous-cloud-coding-agents/getting-started/deployment-guide#network-stack-topology) for fresh-install guidance and migration limits. diff --git a/docs/src/content/docs/getting-started/Deployment-guide.md b/docs/src/content/docs/getting-started/Deployment-guide.md index f4460f077..f1ea908e8 100644 --- a/docs/src/content/docs/getting-started/Deployment-guide.md +++ b/docs/src/content/docs/getting-started/Deployment-guide.md @@ -42,7 +42,7 @@ Replace the compute list as needed and supply image settings for MicroVM. Persis **Existing inline-to-split migration is deferred.** Do not flip `networkTopology` on an existing inline deployment. An ordinary deploy creates a new VPC and removes old resources; identical logical IDs in different stacks do not preserve physical identity. Keep the existing topology until a separately reviewed migration has established resource-type eligibility, source retention and cleanup behavior, an ownership mapping, physical-ID/data preservation, and rollback on a populated disposable deployment. The `cdk refactor --unstable=refactor` criterion in #852 remains open; it is not waived or satisfied by synthesis tests. -This change does not install broad retention, change the Blueprint provider, create an ownership ledger, or replace the guardrail versioning scheme. Those prerequisites belong in separate releases. CloudFormation exports still prevent removing a network used by the application; switching back to `inline` is not an automatic rollback. See [ADR-023's deferred work](/sample-autonomous-cloud-coding-agents/decisions/adr-023-cloudformation-stack-boundaries#deferred-migration-work). +This change does not install broad retention, change the Blueprint provider or create an ownership ledger. Those prerequisites belong in separate releases. The guardrail versioning scheme, once listed with them, was replaced separately ([#1079](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1079)). CloudFormation exports still prevent removing a network used by the application; switching back to `inline` is not an automatic rollback. See [ADR-023's deferred work](/sample-autonomous-cloud-coding-agents/decisions/adr-023-cloudformation-stack-boundaries#deferred-migration-work). Stacks used to test earlier revisions with `blueprintProvisioning=prepare|adopt|managed` or the broad retention aspect require a separate recovery plan before adopting this narrowed version. Returning those stacks directly to the original Blueprint provider can overwrite or soft-delete repository rows. Synthesis rejects the removed `blueprintProvisioning` and `guardrailVersionMigration` context keys instead of silently ignoring them; removing those keys does not make an experimental stack safe to update. Preserve its deployed templates, repository data and ledger inventory; the removed experimental modes are not an upgrade path supported by this release. @@ -523,6 +523,56 @@ The first deploy of a version that sets `InstallLatestAwsSdk` to `false` changes In that call, `ModelInvocationLogging` writes the stack's log group and role to the Bedrock model-invocation logging configuration of the account and Region, which replaces a configuration that another deployment or a manual change put there. `DnsFirewall/FirewallConfig` sets the DNS Firewall of the VPC to fail open. A Blueprint's `RepoConfigCR` writes its repository record, as on every deploy. +### Deploys stop once the input guardrail reaches its version quota (#1079) + +**Affects:** a stack deployed from a version between [#904](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/pull/904) and the fix of [#1079](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1079). Nearly every deploy of such a version published a new version of the input guardrail and kept the one before it, also when the guardrail had not changed. + +**Symptom:** the deploy fails on the guardrail version and the stack rolls back to `UPDATE_ROLLBACK_COMPLETE`. Nearly every later deploy fails in the same way until old versions are deleted. + +``` +CREATE_FAILED AWS::Bedrock::GuardrailVersion InputGuardrail/GuardrailVersion-... +Resource handler returned message: "You have exceeded the service quota limit for ..." +``` + +**Root cause:** the logical ID of the version came from a value that differs from one synthesis to the next, so CloudFormation replaced the version on nearly every deploy. Since #904 it keeps the replaced version, because a retained version of the orchestrator function can still name it. Bedrock allows 20 versions per guardrail, and the quota cannot be raised (*Versions per guardrail* in the [Amazon Bedrock service quotas](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#limits_bedrock)). The stack this was seen on had 19 numbered versions and its `DRAFT`. + +**Resolution:** with the fix, the logical ID contains a hash of the guardrail's configuration. A deploy publishes a version only when that configuration changed, and still keeps the one before it. Two things remain to do by hand: + +- The first deploy with the fix publishes one more version, because the logical ID changes one last time. A guardrail at its quota needs the cleanup below before that deploy. +- The versions that earlier deploys left behind stay, and count against the quota, until they are deleted. So does each version that a later change of the guardrail replaces, and the version of a deploy that publishes one and then rolls back: an execution started during that deploy can still name it. + +Find the guardrail, whose name is `task-input-guardrail-` cut off after 50 characters, and list its versions: + +```bash +aws bedrock list-guardrails \ + --query "guardrails[?name=='task-input-guardrail-'].id" --output text +aws bedrock list-guardrails --guardrail-identifier \ + --query 'guardrails[].[version,createdAt]' --output text +``` + +List the versions that are in use. Each row is a function configuration that names this guardrail in `GUARDRAIL_ID`, with the guardrail version it names in `GUARDRAIL_VERSION`: + +```bash +aws lambda list-functions --function-version ALL \ + --query "Functions[?Environment.Variables.GUARDRAIL_ID==''].[FunctionName,Version,Environment.Variables.GUARDRAIL_VERSION]" \ + --output table +``` + +Keep the guardrail version of the rows whose function version is `$LATEST`: the stack runs on it. The rows with a numbered function version are the published versions of the orchestrator function, which the stack retains as well. A durable execution ends on the function version it started on, so also keep the guardrail version of each published version that still has an unfinished execution. The ARN of an execution names its function version. The loop passes one status per call, as the Lambda API reference requires: + +```bash +for state in RUNNING PAUSING PAUSED; do + aws lambda list-durable-executions-by-function --function-name \ + --statuses "$state" --query 'DurableExecutions[].DurableExecutionArn' +done +``` + +Delete every other numbered version. Always pass `--guardrail-version`: without it, the command deletes the guardrail and all of its versions. + +```bash +aws bedrock delete-guardrail --guardrail-identifier --guardrail-version +``` + ### AgentCore unsupported Availability Zones **Affects:** Fresh deploys in accounts whose default Availability Zones don't line up with the zones AgentCore supports for the region. From e683b40d1fed8f0e1b9f9b86b07bcc592d6da529 Mon Sep 17 00:00:00 2001 From: bgagent Date: Tue, 24 Nov 2026 22:24:16 -0600 Subject: [PATCH 05/11] chore(emulator): upgrade AWS Emulator to 1.0.610 The pin moves from 1.0.523 to 1.0.610, the newest release. The suites were not run on it before this commit: the Docker engine of the machine it was made on did not answer, so the emulator workflow of the pull request is their first run. One assertion is changed ahead of that run. From 1.0.606 the iss claim of a Cognito ID token names a host in the loopback zone, cognito-idp..localhost:, where it named the endpoint. The cli suite expects the new form, as upstream's fix commit and one of its own records give it. With the old value the cli step would fail and the agent suite, the step after it, would not run. The README says what was not done. Nothing in it was probed again, and it names the four statements that upstream's release notes and fix commits say no longer hold as written: the iss claim, the malformed expression forms, an MCP record that matches no schema version, and the operations answered with 501. The package and image sizes are those of the new version; the image size is computed from the package, not measured. --- cli/test/emulator/cognito-sign-in.emulator.ts | 12 ++++++------ scripts/aws-emulator/Dockerfile | 2 +- scripts/aws-emulator/README.md | 4 +++- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/cli/test/emulator/cognito-sign-in.emulator.ts b/cli/test/emulator/cognito-sign-in.emulator.ts index df1102466..3328fd44a 100644 --- a/cli/test/emulator/cognito-sign-in.emulator.ts +++ b/cli/test/emulator/cognito-sign-in.emulator.ts @@ -212,12 +212,12 @@ describe('bgagent sign-in against an AWS Emulator', () => { expect(fs.statSync(credentialsFile()).mode % 0o1000).toBe(0o600); const claims = idTokenClaims(cached!.id_token); expect(claims).toMatchObject({ email, token_use: 'id', aud: loadConfig().client_id }); - // For a pool that a stack creates, the emulator names its own endpoint as - // the issuer, where AWS names - // https://cognito-idp..amazonaws.com/ (upstream: - // aws/aws-emulator issues/things-that-do-not-work/ - // 20261115T035031Z-cognito-identity-cognito-idp-the-cognito-id-token.md). - expect(claims.iss).toBe(`${process.env.AWS_ENDPOINT_URL}/${loadConfig().user_pool_id}`); + // The emulator names an issuer host in the loopback zone, on its own port, + // where AWS names https://cognito-idp..amazonaws.com/ + // (upstream: aws/aws-emulator issues/things-that-do-not-work/ + // 20261124T203931Z-apigateway-cognito-idp-lambda-the-cognito-id-token--r2.md). + const emulatorPort = new URL(String(process.env.AWS_ENDPOINT_URL)).port; + expect(claims.iss).toBe(`https://cognito-idp.${REGION}.localhost:${emulatorPort}/${loadConfig().user_pool_id}`); await expect(getAuthToken()).resolves.toBe(cached!.id_token); saveCredentials({ ...cached!, token_expiry: new Date(0).toISOString() }); diff --git a/scripts/aws-emulator/Dockerfile b/scripts/aws-emulator/Dockerfile index 2d487f15a..da7273b13 100644 --- a/scripts/aws-emulator/Dockerfile +++ b/scripts/aws-emulator/Dockerfile @@ -12,7 +12,7 @@ # from this line, and CI builds this same file. Bump it here and nowhere else. # Use the three-part version from https://github.com/aws/aws-emulator/releases (versions.json lists # a fourth component, e.g. 1.0.385.1, that the package file names do not carry). -ARG AWS_EMULATOR_VERSION=1.0.523 +ARG AWS_EMULATOR_VERSION=1.0.610 # Pinned by digest like every other external image in this repository (see agent/Dockerfile). # The digest is a multi-platform index (linux/amd64 + linux/arm64). To bump: diff --git a/scripts/aws-emulator/README.md b/scripts/aws-emulator/README.md index 77cf11bcc..f39af6360 100644 --- a/scripts/aws-emulator/README.md +++ b/scripts/aws-emulator/README.md @@ -17,7 +17,7 @@ mise run emulator:down ``` - The suites are `cdk/test/emulator/*.emulator.ts`, `cli/test/emulator/*.emulator.ts` and `agent/tests_emulator/`. The unit runs cannot pick them up: the unit `testMatch` does not match `*.emulator.ts`, and the agent's unit run collects `tests/` only. -- The first `emulator:up` builds the image (about 1 GB) from the [Dockerfile](Dockerfile), once per version: it downloads the signed package, about 170 to 190 MB, and verifies it. +- The first `emulator:up` builds the image (about 1.2 to 1.3 GB) from the [Dockerfile](Dockerfile), once per version: it downloads the signed package, about 190 to 215 MB, and verifies it. - Emulated state is in memory and there is no reset call. `emulator:up` always starts a fresh emulator, and `emulator:down` discards everything. - The port is derived from the checkout path, so two worktrees can run the tier at the same time. The header of [emulator.sh](emulator.sh), the wrapper behind these tasks, lists the variables that override the port, the state directory, the version and the container engine. - After a failed `test:integration` the emulator stays up for inspection (`docker logs abca-aws-emulator-`) until `emulator:down` or the next `emulator:up`. Its per-run credentials stay on disk (mode 0600) under the user cache directory, and it is started with an idle timeout of one hour. @@ -82,6 +82,8 @@ Recorded on emulator 1.0.489. Keep this table and the lists above current when t On emulator 1.0.523, DynamoDB `UpdateItem` rejects `REMOVE amount.child` with `ValidationException` when `amount` is a number. On 1.0.489 the same update succeeded and left `amount` unchanged. Both versions allowed `PutItem` to replace an item when its condition compared an attribute with itself. +The pin is 1.0.610. It was moved without the local run of step 1 under [Moving the version pin](#moving-the-version-pin): the suites ran on it for the first time in CI, and nothing in this file was probed again. Upstream's release notes and fix commits after 1.0.523 say that four statements no longer hold as written. None of this was observed here: the `iss` claim of a Cognito token (from 1.0.606 its host is `cognito-idp..localhost:`), the malformed expression forms (from 1.0.578 a comparison of an attribute with itself is refused, and so are doubled parentheses in a key condition, a document path into a key attribute, a map step and a list step on one attribute, and a start key beside a fully pinned key), an MCP record that matches no schema version (refused from 1.0.544), and the operations answered with 501 (`CompleteResourceTokenAuth` and `StopRuntimeSession` are implemented, from 1.0.555 and 1.0.579; `InvokeAgentRuntime` answers 403 or 404 before any 501 from 1.0.579). + ## Keeping the tier away from real AWS The same tests with no endpoint set would call AWS with whatever credentials the shell holds, and product code also makes calls that are not AWS SDK calls. The guard is layered: From 00a310d3253d2da54580e529b253e299cebedf52 Mon Sep 17 00:00:00 2001 From: bgagent Date: Wed, 25 Nov 2026 00:26:25 -0600 Subject: [PATCH 06/11] docs(emulator): record the iss claim the suites showed on 1.0.610 The emulator workflow of the pull request was the first run of the suites on the new pin, and all three passed. The cli suite asserts the iss claim of a Cognito ID token in the form it has since 1.0.606, cognito-idp..localhost:, so that form is observed now. The README's row on the claim has the new form, the note on the pin no longer lists it among the statements nobody observed, and the release history names 1.0.606 beside the two earlier changes of the claim. --- scripts/aws-emulator/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/aws-emulator/README.md b/scripts/aws-emulator/README.md index f39af6360..798660079 100644 --- a/scripts/aws-emulator/README.md +++ b/scripts/aws-emulator/README.md @@ -75,14 +75,14 @@ Recorded on emulator 1.0.489. Keep this table and the lists above current when t | A bucket holds at most 1,000 objects, counting every version and delete marker; a write that adds one more is refused with `ValidationException` | A listing at the default page size never has a second page, so the second page of the upload cleanup loop cannot be reached here | | A force-deleted secret keeps its name blocked for about 0.5 seconds | Remove-then-recreate in one test needs a retry | | `ListSecrets` returns more than 100 results in one page; ECS `RunTask` accepts overrides over 8,192 characters | Two historical ABCA defects would have passed | -| The `iss` claim of a Cognito token names the emulator, `https://127.0.0.1:/` in the tier; AWS issues `https://cognito-idp..amazonaws.com/` | A verifier that derives the issuer from the pool id, as the one in the API's authorizer does, refuses every token the emulator issues | +| The `iss` claim of a Cognito token names the emulator, `https://cognito-idp..localhost:/` in the tier; AWS issues `https://cognito-idp..amazonaws.com/` | A verifier that derives the issuer from the pool id, as the one in the API's authorizer does, refuses every token the emulator issues | | A second Agent Registry record under a name the registry already holds is refused with `ConflictException`, whatever its `recordVersion`; the AWS [user guide](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/registry-concepts.html#registry-concept-record) says the combination of name and `recordVersion` must be unique, so that a name can be reused across versions | ABCA publishes every version of an asset under the same record name, so a second version of an asset cannot be published here. That, and resolving across versions, stay on mocks | | `CreateRegistryRecord` parses every descriptor `data` member as JSON and refuses anything else with `ValidationException`, the skill Markdown in `agentSkillsDefinition.additionalData.skillMd.data` included; the AWS [user guide](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/registry-supported-record-types.html#registry-agentskills-descriptors) gives a Markdown `SKILL.md` as valid content of that member | ABCA publishes a `skill` as a native record with a Markdown `SKILL.md`, so a skill can be published here only with `custom: true`. Native skills, and the read paths for a corrupt `SKILL.md` or a record body that is not JSON, stay on mocks | | An MCP record whose `server.json` matches no MCP schema version (for example one without name, description and version) is accepted; AWS's published test for the emulator expects `ValidationException` | An `mcp_server` publish with an incomplete `discovery` passes here | On emulator 1.0.523, DynamoDB `UpdateItem` rejects `REMOVE amount.child` with `ValidationException` when `amount` is a number. On 1.0.489 the same update succeeded and left `amount` unchanged. Both versions allowed `PutItem` to replace an item when its condition compared an attribute with itself. -The pin is 1.0.610. It was moved without the local run of step 1 under [Moving the version pin](#moving-the-version-pin): the suites ran on it for the first time in CI, and nothing in this file was probed again. Upstream's release notes and fix commits after 1.0.523 say that four statements no longer hold as written. None of this was observed here: the `iss` claim of a Cognito token (from 1.0.606 its host is `cognito-idp..localhost:`), the malformed expression forms (from 1.0.578 a comparison of an attribute with itself is refused, and so are doubled parentheses in a key condition, a document path into a key attribute, a map step and a list step on one attribute, and a start key beside a fully pinned key), an MCP record that matches no schema version (refused from 1.0.544), and the operations answered with 501 (`CompleteResourceTokenAuth` and `StopRuntimeSession` are implemented, from 1.0.555 and 1.0.579; `InvokeAgentRuntime` answers 403 or 404 before any 501 from 1.0.579). +The pin is 1.0.610. It was moved without the local run of step 1 under [Moving the version pin](#moving-the-version-pin): the suites ran on it for the first time in CI, where all three passed, and nothing in this file was probed again. One row was brought up to date from that run: the `iss` claim, whose host changed in 1.0.606 and which the `cli` suite asserts. Upstream's release notes and fix commits after 1.0.523 say that three more statements no longer hold as written, and none of that was observed here: the malformed expression forms (from 1.0.578 a comparison of an attribute with itself is refused, and so are doubled parentheses in a key condition, a document path into a key attribute, a map step and a list step on one attribute, and a start key beside a fully pinned key), an MCP record that matches no schema version (refused from 1.0.544), and the operations answered with 501 (`CompleteResourceTokenAuth` and `StopRuntimeSession` are implemented, from 1.0.555 and 1.0.579; `InvokeAgentRuntime` answers 403 or 404 before any 501 from 1.0.579). ## Keeping the tier away from real AWS @@ -119,4 +119,4 @@ There is one pin, the `ARG AWS_EMULATOR_VERSION` line in the [Dockerfile](Docker The image tag carries the version and a checksum of the Dockerfile, so a change to either is rebuilt. The package is verified against the AWS publishing key, pinned by fingerprint: a key rotation fails the build until the fingerprint is updated from the emulator's user guide. -Pinning is not optional. Upstream ships several releases a day and behavior changes between them: release 1.0.382 changed the `iss` claim of Cognito tokens, which the `cli` suite asserts, and release 1.0.471 changed it back; release 1.0.483 began to refuse a registry record whose descriptor is not JSON, which no suite asserts. Security fixes go into the newest release only. The exposure is small by construction: the emulator is published on host loopback only, holds no real credentials or data, and the CI job has no AWS credential and no repository secret, only the job's read-only `GITHUB_TOKEN`. +Pinning is not optional. Upstream ships several releases a day and behavior changes between them: release 1.0.382 changed the `iss` claim of Cognito tokens, which the `cli` suite asserts, release 1.0.471 changed it back and release 1.0.606 changed it again; release 1.0.483 began to refuse a registry record whose descriptor is not JSON, which no suite asserts. Security fixes go into the newest release only. The exposure is small by construction: the emulator is published on host loopback only, holds no real credentials or data, and the CI job has no AWS credential and no repository secret, only the job's read-only `GITHUB_TOKEN`. From 3ddbe375c8149431c57642783db15f8224520691 Mon Sep 17 00:00:00 2001 From: bgagent Date: Wed, 25 Nov 2026 18:12:40 -0600 Subject: [PATCH 07/11] fix(cli): write a secret file in place when it cannot be replaced Since the write through a temporary file and a rename, a file that can be written but not replaced failed: a credentials.json mounted into a container on its own (the rename onto a mount point answers EBUSY), a file in a directory that takes no new file, `--output /dev/fd/N` on macOS when N is a regular file, a name or a path too long to take the temporary suffix. For credentials.json every token refresh failed there, where the code before #1080 worked. When the temporary file cannot be created or the rename fails with EACCES, EPERM, EROFS, EBUSY, EXDEV, ENOENT or ENAMETOOLONG, the file is now written in place. In a shared directory such as /tmp another user can make the rename fail on purpose, so the write in place is stricter than the old one: an existing file is made owner-only before the content goes in, and only if it is the user's own (root: any file); a file that was missing is created exclusively. For a file written in place the race of #1080 remains, and the comment says so. A symbolic link that leads to a regular file is resolved, and that file is replaced beside its real path: the link stays, and a credentials.json that is a link no longer has the race. Because links are followed on purpose, a link, a FIFO, a socket or a directory found at the path is refused when it belongs to another user (not root, not the owner of its directory) or has a second hard link: `replay --output` takes a path that can be in a directory others write to. A device is written whoever it belongs to: only a privileged user can make one. The entry is examined once and used by its name afterwards. In a directory with the sticky bit only the user, root and the owner of the directory can exchange it in between, and for root also the owner of a file that root writes in place. In a directory without it anyone who may write there can, and the write then follows a planted link. The comment of writeSecretFile says so. The temporary file is opened exclusively and removed only by the call that created it, and an error of the cleanup no longer replaces the first error. A process killed between the write and the rename leaves the temporary file, owner-only: the comments of writeSecretFile and of takePendingConsent say so. knip.json names mkfifo, which a test uses to make a FIFO. Not run: a rename onto a real mount point (no container engine), and anything as root or on Linux before CI. --- cli/src/config.ts | 175 ++++++++++++- cli/src/linear-pending-consent.ts | 7 +- cli/test/commands/replay.test.ts | 33 ++- cli/test/config.test.ts | 415 +++++++++++++++++++++++++++++- knip.json | 1 + 5 files changed, 601 insertions(+), 30 deletions(-) diff --git a/cli/src/config.ts b/cli/src/config.ts index ac64f7129..25160802d 100644 --- a/cli/src/config.ts +++ b/cli/src/config.ts @@ -111,35 +111,182 @@ export function clearCredentials(): void { fs.rmSync(credentialsPath(), { force: true }); } +/** + * What a file system answers when a file cannot be replaced although it may still be + * written. EACCES, EPERM, EROFS: its directory takes no new file, or lets none be renamed + * there. EBUSY, EXDEV: the file is a mount point (a single file mounted into a + * container), or the rename would cross file systems. ENOENT: no file can be created + * beside it, as beside /dev/fd/1 on macOS, which /dev/stdout leads to. ENAMETOOLONG: its + * name or its path is too long to take the suffix of the temporary file. + */ +const CANNOT_REPLACE = new Set(['EACCES', 'EPERM', 'EROFS', 'EBUSY', 'EXDEV', 'ENOENT', 'ENAMETOOLONG']); + +const ROOT_UID = 0; + /** * Write a file that only its owner may read, whether it is new or already there. - * Another bgagent process may be reading it, so the content goes to a temporary file - * that replaces the target in one step: a reader gets the old file or the new one, - * never a truncated one (#1080). + * + * Another bgagent process may be reading the file, so the content goes to a temporary file + * beside it and a rename puts that in place: a reader gets the old file or the new one, + * never a truncated one (#1080). A symbolic link is resolved first, so the file it names + * is the one replaced and the link stays a link. + * + * Three kinds of target are written in place instead: a file that cannot be replaced + * (CANNOT_REPLACE), a device such as /dev/null or a FIFO, and a symbolic link that does + * not resolve to a regular file. For a file written this way the race of #1080 remains: + * a reader can still get it truncated. + * + * The path may be one the user chose in a directory that others can write to, as with + * `replay --output` in /tmp. These rules are applied to what is found at the path before + * anything is written: + * - a symbolic link, a FIFO, a socket or a directory is refused unless it belongs to the + * user, to root or to the owner of its directory; so is one that has a second name, a + * hard link. A device is written whoever it belongs to: only a privileged user can make + * one. Only the entry at the path is held to this, not what a link there leads to + * (refuseEntryOfAnotherUser); + * - a regular file that cannot be replaced is written in place only if it is the user's + * own or the user is root, and it is made owner-only before the content goes in + * (mayWriteInPlace); + * - where nothing was found and the file cannot be put in place by a rename, it is + * created exclusively, so an entry that appeared since is not written through. + * Where there are no user ids (Windows), nothing is refused for its owner or its names, + * and a file that cannot be replaced is written in place whoever it belongs to. On every + * system, an entry that someone put under the temporary name is neither written through + * nor removed (replaceFile). + * + * The entry is looked at first and used afterwards, by its name: a link is resolved then, + * and a write in place, except for the exclusive creation, lands in whatever is under the + * name by then and follows a link that was put there in between. In a directory with the + * sticky bit, as /tmp has, only the owner of an entry, the owner of the directory and + * root can put something else under its name. What is resolved or written in place can + * therefore be exchanged there only by the user, by root or by the owner of the + * directory, with one exception: the file of another user that root writes in place can + * be exchanged by its owner. In a directory that others can write to and that has no + * sticky bit, anyone who may write to it can exchange any entry, the user's own file + * included, and can remove the temporary file, which makes the replacement fail and + * brings on the write in place. + * + * A process killed between the write and the rename leaves the temporary file, + * `...tmp`, beside the file it was to replace: owner-only, holding the + * content that was being written. Nothing removes it later. */ export function writeSecretFile(file: string, content: string): void { - const target = fs.lstatSync(file, { throwIfNoEntry: false }); + let destination = file; + let target = fs.lstatSync(file, { throwIfNoEntry: false }); + if (target && !target.isFile()) refuseEntryOfAnotherUser(file, target); + if (target?.isSymbolicLink()) { + try { + destination = fs.realpathSync(file); + target = fs.lstatSync(destination); + } catch { + // The link leads nowhere, or to a file that has no path: written through it below. + } + } if (!target || target.isFile()) { - // Created exclusively, under a name that cannot be guessed: a path the user chose may - // be in a directory that others can write to, and a link planted there is not followed. - const temp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`; try { - fs.writeFileSync(temp, content, { mode: SECRET_FILE_MODE, flag: 'wx' }); - fs.renameSync(temp, file); - } finally { - fs.rmSync(temp, { force: true }); + replaceFile(destination, content); + } catch (err) { + if (!CANNOT_REPLACE.has((err as NodeJS.ErrnoException).code ?? '')) throw err; + // In place, by the rules above: nothing was there, or it is a file this user may write. + if (!target) { + fs.writeFileSync(destination, content, { mode: SECRET_FILE_MODE, flag: 'wx' }); + } else if (mayWriteInPlace(target)) { + fs.chmodSync(destination, SECRET_FILE_MODE); + fs.writeFileSync(destination, content, { mode: SECRET_FILE_MODE }); + } else { + throw err; + } } return; } - // A device such as /dev/null, a FIFO or a symbolic link is written in place: a rename - // would replace the node or the link itself. writeFileSync only honors `mode` when - // CREATING the file, so chmod what the path resolves to, if that is a regular file. + // A device, a FIFO, or a link that does not resolve to a regular file: a rename would + // replace the node or the link itself. writeFileSync only honors `mode` when CREATING + // the file, so chmod what the path resolves to, if that is a regular file. fs.writeFileSync(file, content, { mode: SECRET_FILE_MODE }); if (fs.statSync(file).isFile()) { fs.chmodSync(file, SECRET_FILE_MODE); } } +/** + * Refuse an entry that is not a regular file if it belongs to another user or has a + * second name. In a directory that others can write to, anyone can put a link there to + * send the content elsewhere or a FIFO to read it, and can put a link in the place of a + * FIFO, a socket or a directory of their own after it was looked at. A device is not + * held to this: only a privileged user can make one, so a device at the path is not + * something that another user put there. Two rules, neither of which applies where + * there are no user ids (Windows): + * - the entry belongs to the user, to root or to the owner of the directory it is in. + * Linux refuses any other link or FIFO itself in a sticky world-writable directory + * where fs.protected_symlinks and fs.protected_fifos are set; this rule holds in every + * directory. + * - the entry has one name only. A second name (a hard link) can be given to an entry of + * someone else's, and its owner then does not tell who put it there: macOS lets a user + * do that with a symbolic link of root's, and Linux does unless fs.protected_hardlinks + * is set. A directory is not held to this: its link count is not a count of names. + * Only the entry at the path itself is examined, not what a link leads to. + */ +function refuseEntryOfAnotherUser(entry: string, stats: fs.Stats): void { + const user = process.geteuid?.(); + if (user === undefined || stats.isCharacterDevice() || stats.isBlockDevice()) return; + const known = stats.uid === user || stats.uid === ROOT_UID || stats.uid === fs.statSync(path.dirname(entry)).uid; + const oneName = stats.nlink <= 1 || stats.isDirectory(); + if (known && oneName) return; + const kind = stats.isSymbolicLink() ? 'symbolic link' : stats.isFIFO() ? 'FIFO' : 'entry'; + const reason = known ? 'has more than one name, so someone else may have put it there' : 'belongs to another user'; + throw new CliError(`Refusing to write to ${entry}: the ${kind} there ${reason}. Remove it, or choose another path.`); +} + +/** + * Whether a regular file that cannot be replaced may be written in place: the user's own, + * and for root any file, because a file mounted into a container often belongs to a user + * of the host. The file of another user is left alone. In a directory with the sticky + * bit, such as /tmp, its owner can put something else under its name at any moment, a + * link for example, and the write would go there; to the user's own file only root and + * the owner of the directory can do that. Root has no such protection: the owner of a + * file that root writes in place can still put a link under its name, and the write + * follows it. Where there are no user ids (Windows), any file. + */ +function mayWriteInPlace(stats: fs.Stats): boolean { + const user = process.geteuid?.(); + return user === undefined || user === ROOT_UID || stats.uid === user; +} + +/** + * Put `content` in the place of `file` in one step. The temporary file is created + * exclusively, under a name that cannot be guessed and with its final mode. After a + * failure it is removed if it can be, and it is this call's own to remove: an entry that + * someone else put under that name makes the open fail, and is neither written through + * nor removed. The error thrown is the first one. An error of what follows it, the close + * after a failed write or the removal, is not reported: if the removal fails, the + * temporary file stays, owner-only. + */ +function replaceFile(file: string, content: string): void { + const temp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`; + const fd = fs.openSync(temp, 'wx', SECRET_FILE_MODE); + try { + try { + fs.writeFileSync(fd, content); + } catch (err) { + try { + fs.closeSync(fd); + } catch { + // The error of the write is the one to report. + } + throw err; + } + fs.closeSync(fd); + fs.renameSync(temp, file); + } catch (err) { + try { + fs.rmSync(temp, { force: true }); + } catch { + // The error of the write, of the close or of the rename is the one to report. + } + throw err; + } +} + /** Save credentials with restricted permissions. */ export function saveCredentials(creds: Credentials): void { ensureConfigDir(); diff --git a/cli/src/linear-pending-consent.ts b/cli/src/linear-pending-consent.ts index 7a0c52a00..145d486de 100644 --- a/cli/src/linear-pending-consent.ts +++ b/cli/src/linear-pending-consent.ts @@ -87,8 +87,11 @@ export function savePendingConsent(pending: PendingConsent): void { /** * Load and CONSUME the pending consent for a slug. The file is deleted whether or - * not it turns out to be usable, so a verifier is never left on disk after one - * attempt and cannot be replayed. + * not it turns out to be usable, so the verifier in it gets one attempt and cannot + * be replayed from it. Only this file is deleted: a process killed in + * `savePendingConsent` between the write and the rename leaves the verifier it was + * saving in a temporary file beside this one, owner-only, and nothing removes that + * copy (see `writeSecretFile`). */ export function takePendingConsent(slug: string): PendingConsent { const p = pendingPath(slug); diff --git a/cli/test/commands/replay.test.ts b/cli/test/commands/replay.test.ts index 6ca172bae..cf1bbb6a6 100644 --- a/cli/test/commands/replay.test.ts +++ b/cli/test/commands/replay.test.ts @@ -17,7 +17,10 @@ * SOFTWARE. */ -import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { + chmodSync, existsSync, lstatSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync, + type PathLike, type Stats, type StatSyncOptions, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { ApiClient } from '../../src/api-client'; @@ -130,6 +133,34 @@ describe('replay command', () => { expect(statSync('/dev/null').mode).toBe(mode); }); + test('--output refuses a symbolic link that another user planted, and writes nothing through it', async () => { + const dir = mkdtempSync(join(tmpdir(), 'replay-test-')); + const link = join(dir, 'bundle.json'); + const elsewhere = join(dir, 'elsewhere.json'); + // A link that leads nowhere does not count as an existing file: no --force is needed. + symlinkSync(elsewhere, link); + // Only root can change the owner of a link, so the test changes what lstat reports: + // an owner who is neither the user, nor root, nor the owner of the directory. + const nodeFs = jest.requireActual('node:fs'); + const lstat = nodeFs.lstatSync; + const stranger = statSync(dir).uid + 1; + const reported = jest.spyOn(nodeFs, 'lstatSync').mockImplementation(((file: PathLike, options?: StatSyncOptions) => { + const stats = lstat(file, options) as Stats | undefined; + if (stats && file === link) stats.uid = stranger; + return stats; + }) as typeof lstatSync); + try { + await expect( + makeReplayCommand().parseAsync(['node', 'test', 'abc', '--output', link]), + ).rejects.toThrow(`Refusing to write to ${link}: the symbolic link there belongs to another user.`); + expect(existsSync(elsewhere)).toBe(false); + expect(errSpy).not.toHaveBeenCalled(); + } finally { + reported.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + }); + test('refuses to overwrite an existing --output file without --force', async () => { const dir = mkdtempSync(join(tmpdir(), 'replay-test-')); const file = join(dir, 'exists.json'); diff --git a/cli/test/config.test.ts b/cli/test/config.test.ts index e80114615..73c1d10cb 100644 --- a/cli/test/config.test.ts +++ b/cli/test/config.test.ts @@ -17,10 +17,11 @@ * SOFTWARE. */ +import { execFileSync } from 'child_process'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { loadConfig, loadCredentials, saveConfig, saveCredentials } from '../src/config'; +import { loadConfig, loadCredentials, saveConfig, saveCredentials, writeSecretFile } from '../src/config'; import { CliError } from '../src/errors'; describe('config', () => { @@ -126,8 +127,42 @@ describe('config', () => { const NEW = { id_token: 'new-id', refresh_token: 'new-refresh', token_expiry: '2026-02-01T00:00:00.000Z' }; // `import * as fs` is a read-only view of the module, here and in config.ts: a spy goes on the module itself. const nodeFs = jest.requireActual('fs'); + const credentials = (): string => path.join(tmpDir, 'credentials.json'); + + /** An error as the file system raises it: the `code` is what the caller of fs goes by. */ + function failure(code: string): NodeJS.ErrnoException { + return Object.assign(new Error(`${code}: simulated`), { code }); + } + + /** + * Make the file system report an owner, or a number of names, for `entry`. Only root can + * really change an owner, and on macOS fs.linkSync gives the second name to the file that + * a symbolic link names, not to the link. + */ + function report(call: 'lstatSync' | 'statSync', entry: string, as: { uid?: number; nlink?: number }): void { + const real = nodeFs[call]; + jest.spyOn(nodeFs, call).mockImplementation(((file: fs.PathLike, options?: fs.StatSyncOptions) => { + const stats = real(file, options) as fs.Stats | undefined; + if (stats && file === entry) Object.assign(stats, as); + return stats; + }) as typeof fs.statSync); + } + + /** Run as the user `uid`, or where there are no user ids, as on Windows. */ + function runAs(uid: number | undefined): void { + process.geteuid = uid === undefined ? undefined : () => uid; + } + const geteuid = process.geteuid; + + const ANOTHER_USER = 'belongs to another user'; + const SECOND_NAME = 'has more than one name, so someone else may have put it there'; + /** What an entry that is not a regular file is refused with. */ + function refusal(entry: string, kind: string, reason: string): CliError { + return new CliError(`Refusing to write to ${entry}: the ${kind} there ${reason}. Remove it, or choose another path.`); + } afterEach(() => { + process.geteuid = geteuid; jest.restoreAllMocks(); }); @@ -154,30 +189,63 @@ describe('config', () => { expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); }); - test('keeps the old file and leaves no temporary file when the replacement fails', () => { + test.each([ + ['an error without a code', new Error('rename failed')], + ['an error that is not about replacing the file', failure('ENOSPC')], + ])('keeps the old file and leaves no temporary file when the replacement fails with %s', (_what, error) => { + saveCredentials(OLD); + jest.spyOn(nodeFs, 'renameSync').mockImplementationOnce(() => { throw error; }); + + expect(() => saveCredentials(NEW)).toThrow(error); + + expect(loadCredentials()).toEqual(OLD); + expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); + }); + + test('reports the failure of the replacement, not that of the cleanup after it', () => { saveCredentials(OLD); jest.spyOn(nodeFs, 'renameSync').mockImplementationOnce(() => { throw new Error('rename failed'); }); + jest.spyOn(nodeFs, 'rmSync').mockImplementationOnce(() => { throw new Error('cleanup failed'); }); expect(() => saveCredentials(NEW)).toThrow('rename failed'); expect(loadCredentials()).toEqual(OLD); + }); + + test('reports the failure of the write, not that of the close after it', () => { + saveCredentials(OLD); + jest.spyOn(nodeFs, 'writeFileSync').mockImplementationOnce(() => { throw new Error('write failed'); }); + const close = fs.closeSync; + const closes = jest.spyOn(nodeFs, 'closeSync').mockImplementationOnce((fd) => { + close(fd); + throw new Error('close failed'); + }); + + expect(() => saveCredentials(NEW)).toThrow('write failed'); + + expect(closes).toHaveBeenCalled(); + expect(loadCredentials()).toEqual(OLD); expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); }); - test('refuses a temporary name that is taken instead of writing through it', () => { + test('refuses a temporary name that is taken, and leaves what is there', () => { // A path the user chose can be in a directory that others may write to: a link - // planted under the temporary name must not send the secret where it points. + // planted under the temporary name must not send the secret where it points, and + // it is not this save's to remove. const victim = path.join(tmpDir, 'victim'); fs.writeFileSync(victim, 'untouched'); - const write = fs.writeFileSync; - jest.spyOn(nodeFs, 'writeFileSync').mockImplementationOnce((file, data, options) => { - fs.symlinkSync(victim, String(file)); - write(file, data, options); + const open = fs.openSync; + let planted = ''; + jest.spyOn(nodeFs, 'openSync').mockImplementationOnce((file, flags, mode) => { + planted = String(file); + fs.symlinkSync(victim, planted); + return open(file, flags, mode); }); expect(() => saveCredentials(NEW)).toThrow('EEXIST'); expect(fs.readFileSync(victim, 'utf-8')).toBe('untouched'); + expect(fs.readlinkSync(planted)).toBe(victim); }); test('gives every save a temporary file of its own, so two can run at once', () => { @@ -197,19 +265,340 @@ describe('config', () => { expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); }); - test('writes through a symbolic link instead of replacing it', () => { - // A dotfiles setup keeps credentials.json elsewhere and links to it. - const link = path.join(tmpDir, 'credentials.json'); + // A file that cannot be replaced is written where it is, as before #1080. EBUSY is what + // the rename answers for credentials.json mounted into a container as a single file. + test.each(['EACCES', 'EPERM', 'EROFS', 'EBUSY', 'EXDEV', 'ENOENT', 'ENAMETOOLONG'])( + 'writes the file in place when the rename fails with %s', + (code) => { + saveCredentials(OLD); + fs.chmodSync(credentials(), 0o644); + jest.spyOn(nodeFs, 'renameSync').mockImplementationOnce(() => { throw failure(code); }); + + saveCredentials(NEW); + + expect(loadCredentials()).toEqual(NEW); + expect(fs.statSync(credentials()).mode % 0o1000).toBe(0o600); + expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); + }, + ); + + test('writes the file in place when the temporary file cannot be created', () => { + saveCredentials(OLD); + jest.spyOn(nodeFs, 'openSync').mockImplementationOnce(() => { throw failure('EACCES'); }); + + saveCredentials(NEW); + + expect(loadCredentials()).toEqual(NEW); + expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); + }); + + test('writes the file in place in a directory that takes no new file', () => { + // No mock: the directory itself refuses the temporary file. It refuses root nothing, + // so for root this only shows that the save works. + saveCredentials(OLD); + fs.chmodSync(credentials(), 0o644); + fs.chmodSync(tmpDir, 0o500); + try { + saveCredentials(NEW); + } finally { + fs.chmodSync(tmpDir, 0o700); + } + + expect(loadCredentials()).toEqual(NEW); + expect(fs.statSync(credentials()).mode % 0o1000).toBe(0o600); + expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); + }); + + // No mock here either. A name of 255 ASCII characters is the longest that most file + // systems take, so the temporary file, whose name is longer by its suffix, cannot be + // created. Where the longer name is taken the file is replaced, and this only shows + // that the save works. + test.each([ + ['writes a file in place', true], + ['creates a file in place', false], + ])('%s whose name is too long to take the suffix of the temporary file', (_how, exists) => { + const file = path.join(tmpDir, `${'n'.repeat(250)}.json`); + if (exists) { + fs.writeFileSync(file, 'old'); + fs.chmodSync(file, 0o644); + } + + writeSecretFile(file, 'new'); + + expect(fs.readFileSync(file, 'utf-8')).toBe('new'); + expect(fs.statSync(file).mode % 0o1000).toBe(0o600); + expect(fs.readdirSync(tmpDir)).toEqual([path.basename(file)]); + }); + + test('makes a file owner-only before it writes the new content in place', () => { + saveCredentials(OLD); + fs.chmodSync(credentials(), 0o644); + jest.spyOn(nodeFs, 'renameSync').mockImplementationOnce(() => { throw failure('EBUSY'); }); + const write = fs.writeFileSync; + const modes: number[] = []; + jest.spyOn(nodeFs, 'writeFileSync').mockImplementation((file, data, options) => { + if (file === credentials()) modes.push(fs.statSync(credentials()).mode % 0o1000); + write(file, data, options); + }); + + saveCredentials(NEW); + + expect(modes).toEqual([0o600]); + }); + + // Whose file is written in place. In /tmp the owner of a file can put a link under its + // name at any moment, so the file of another user is left alone. Root writes any file: + // one mounted into a container often belongs to a user of the host. + test.each([ + ["writes the user's own file in place", { user: 1000, file: 1000 }, NEW], + ['leaves the file of another user alone', { user: 1000, file: 2000 }, OLD], + ['writes the file of another user in place when the user is root', { user: 0, file: 2000 }, NEW], + ['writes the file in place where there are no user ids', { user: undefined, file: 2000 }, NEW], + ])('%s, when the file cannot be replaced', (_rule, ids, expected) => { + saveCredentials(OLD); + runAs(ids.user); + report('lstatSync', credentials(), { uid: ids.file }); + const error = failure('EPERM'); + jest.spyOn(nodeFs, 'renameSync').mockImplementationOnce(() => { throw error; }); + + if (expected === OLD) { + expect(() => saveCredentials(NEW)).toThrow(error); + } else { + saveCredentials(NEW); + } + + expect(loadCredentials()).toEqual(expected); + expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); + }); + + test('creates the file in place when none was there and it cannot be put in place by a rename', () => { + jest.spyOn(nodeFs, 'renameSync').mockImplementationOnce(() => { throw failure('EXDEV'); }); + + saveCredentials(NEW); + + expect(loadCredentials()).toEqual(NEW); + expect(fs.statSync(credentials()).mode % 0o1000).toBe(0o600); + expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); + }); + + test('does not write through an entry that appeared where no file was', () => { + // In a directory with the sticky bit the rename fails with EPERM once someone else + // has put an entry under the name. + const victim = path.join(tmpDir, 'victim'); + fs.writeFileSync(victim, 'untouched'); + jest.spyOn(nodeFs, 'renameSync').mockImplementationOnce((_from, to) => { + fs.symlinkSync(victim, String(to)); + throw failure('EPERM'); + }); + + expect(() => saveCredentials(NEW)).toThrow('EEXIST'); + + expect(fs.readFileSync(victim, 'utf-8')).toBe('untouched'); + expect(fs.readdirSync(tmpDir).sort()).toEqual(['credentials.json', 'victim']); + }); + + test('replaces the file that a symbolic link names, and keeps the link', () => { + // A dotfiles setup keeps credentials.json elsewhere and links to it. Here the link is + // relative and leads to a second one: the file to replace is where they end, which + // the text of the first link does not say. + const elsewhere = path.join(tmpDir, 'dotfiles', 'credentials.json'); + const between = path.join(tmpDir, 'current.json'); + fs.mkdirSync(path.dirname(elsewhere)); + fs.writeFileSync(elsewhere, JSON.stringify(OLD)); + fs.chmodSync(elsewhere, 0o644); + fs.symlinkSync(path.join('dotfiles', 'credentials.json'), between); + fs.symlinkSync('current.json', credentials()); + // On macOS the temporary directory is itself behind a link. + const real = fs.realpathSync(elsewhere); + const rename = fs.renameSync; + const atRename: unknown[] = []; + jest.spyOn(nodeFs, 'renameSync').mockImplementationOnce((from, to) => { + // The new file waits beside the real one while a reader of the link gets the old login. + atRename.push({ read: loadCredentials(), from: path.dirname(String(from)), to }); + rename(from, to); + }); + + saveCredentials(NEW); + + expect(atRename).toEqual([{ read: OLD, from: path.dirname(real), to: real }]); + expect(fs.readlinkSync(credentials())).toBe('current.json'); + expect(fs.readlinkSync(between)).toBe(path.join('dotfiles', 'credentials.json')); + expect(loadCredentials()).toEqual(NEW); + expect(fs.statSync(elsewhere).mode % 0o1000).toBe(0o600); + expect(fs.readdirSync(path.dirname(elsewhere))).toEqual(['credentials.json']); + }); + + test('writes the file that a symbolic link names in place when its directory takes no new file', () => { + // No mock, as above: for root the directory refuses nothing and the file is replaced. + const elsewhere = path.join(tmpDir, 'dotfiles', 'credentials.json'); + fs.mkdirSync(path.dirname(elsewhere)); + fs.writeFileSync(elsewhere, JSON.stringify(OLD)); + fs.chmodSync(elsewhere, 0o644); + fs.symlinkSync(elsewhere, credentials()); + fs.chmodSync(path.dirname(elsewhere), 0o500); + try { + saveCredentials(NEW); + } finally { + fs.chmodSync(path.dirname(elsewhere), 0o700); + } + + expect(fs.readlinkSync(credentials())).toBe(elsewhere); + expect(loadCredentials()).toEqual(NEW); + expect(fs.statSync(elsewhere).mode % 0o1000).toBe(0o600); + expect(fs.readdirSync(path.dirname(elsewhere))).toEqual(['credentials.json']); + }); + + test('writes through a symbolic link that leads nowhere', () => { + const elsewhere = path.join(tmpDir, 'not-there-yet.json'); + fs.symlinkSync(elsewhere, credentials()); + + saveCredentials(NEW); + + expect(fs.readlinkSync(credentials())).toBe(elsewhere); + expect(JSON.parse(fs.readFileSync(elsewhere, 'utf-8'))).toEqual(NEW); + expect(fs.statSync(elsewhere).mode % 0o1000).toBe(0o600); + }); + + test('writes through a symbolic link whose file has no path, and makes that file owner-only', () => { + // On Linux /dev/stdout leads to the file that stdout is, and a file that was deleted + // while open has no path to resolve the link to. const elsewhere = path.join(tmpDir, 'elsewhere.json'); fs.writeFileSync(elsewhere, '{}'); fs.chmodSync(elsewhere, 0o644); - fs.symlinkSync(elsewhere, link); + fs.symlinkSync(elsewhere, credentials()); + jest.spyOn(nodeFs, 'realpathSync').mockImplementationOnce(() => { throw failure('ENOENT'); }); saveCredentials(NEW); - expect(fs.lstatSync(link).isSymbolicLink()).toBe(true); + expect(fs.readlinkSync(credentials())).toBe(elsewhere); expect(JSON.parse(fs.readFileSync(elsewhere, 'utf-8'))).toEqual(NEW); expect(fs.statSync(elsewhere).mode % 0o1000).toBe(0o600); }); + + test('writes through a symbolic link that names a device, and leaves the device as it is', () => { + const device = fs.statSync('/dev/null'); + fs.symlinkSync('/dev/null', credentials()); + + saveCredentials(NEW); + + expect(fs.readlinkSync(credentials())).toBe('/dev/null'); + expect(fs.statSync('/dev/null').isCharacterDevice()).toBe(true); + expect(fs.statSync('/dev/null').mode).toBe(device.mode); + expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); + }); + + test('writes a file that is named by one of its open descriptors, /dev/fd/N', () => { + // What `--output /dev/stdout > file` comes to. On macOS /dev/fd/N is the open file + // itself, and no file can be created beside it: it is written in place, through the + // descriptor. On Linux it is a symbolic link to the file, which is replaced: the + // descriptor then holds the old file, which has no name any more. + const file = path.join(tmpDir, 'bundle.json'); + const fd = fs.openSync(file, 'w', 0o644); + try { + const link = fs.lstatSync(`/dev/fd/${fd}`).isSymbolicLink(); + + writeSecretFile(`/dev/fd/${fd}`, 'new'); + + expect(fs.readFileSync(file, 'utf-8')).toBe('new'); + expect(fs.statSync(file).mode % 0o1000).toBe(0o600); + expect(fs.fstatSync(fd).ino === fs.statSync(file).ino).toBe(!link); + expect(fs.readdirSync(tmpDir)).toEqual(['bundle.json']); + } finally { + fs.closeSync(fd); + } + }); + + // Whose a symbolic link is decides whether it is followed: in a directory that others + // can write to, anyone can put one under the name the user is about to write. With a + // second name, a hard link, someone else can put a link of root's there. + test.each([ + ['follows a symbolic link that the user made', { user: 1000, link: 1000, directory: 2000, names: 1 }, undefined], + ['follows a symbolic link that root made', { user: 1000, link: 0, directory: 2000, names: 1 }, undefined], + ['follows a symbolic link that the owner of its directory made', { user: 1000, link: 2000, directory: 2000, names: 1 }, undefined], + ['refuses a symbolic link that another user made', { user: 1000, link: 3000, directory: 2000, names: 1 }, ANOTHER_USER], + ['refuses a symbolic link that another user made when the user is root', { user: 0, link: 3000, directory: 2000, names: 1 }, ANOTHER_USER], + ["refuses a symbolic link of root's that has a second name", { user: 1000, link: 0, directory: 2000, names: 2 }, SECOND_NAME], + ['follows any symbolic link where there are no user ids', { user: undefined, link: 3000, directory: 2000, names: 2 }, undefined], + ])('%s', (_rule, ids, reason) => { + const elsewhere = path.join(tmpDir, 'elsewhere.json'); + fs.writeFileSync(elsewhere, JSON.stringify(OLD)); + fs.symlinkSync(elsewhere, credentials()); + runAs(ids.user); + report('lstatSync', credentials(), { uid: ids.link, nlink: ids.names }); + report('statSync', tmpDir, { uid: ids.directory }); + + if (reason) { + expect(() => saveCredentials(NEW)).toThrow(refusal(credentials(), 'symbolic link', reason)); + } else { + saveCredentials(NEW); + } + + expect(JSON.parse(fs.readFileSync(elsewhere, 'utf-8'))).toEqual(reason ? OLD : NEW); + expect(fs.readdirSync(tmpDir).sort()).toEqual(['credentials.json', 'elsewhere.json']); + }); + + // Whoever made a FIFO reads what is written to it. The test holds the reading end + // itself, so that a write which is not refused ends instead of waiting for a reader. + test.each([ + ['writes to a FIFO that the user made', { uid: 1000 }, undefined], + ['refuses a FIFO that another user made', { uid: 3000 }, ANOTHER_USER], + ['refuses a FIFO that has a second name', { uid: 1000, nlink: 2 }, SECOND_NAME], + ])('%s', (_rule, reported, reason) => { + execFileSync('mkfifo', [credentials()]); + // eslint-disable-next-line no-bitwise + const reader = fs.openSync(credentials(), fs.constants.O_RDONLY | fs.constants.O_NONBLOCK); + try { + runAs(1000); + report('lstatSync', credentials(), reported); + report('statSync', tmpDir, { uid: 2000 }); + + if (reason) { + expect(() => writeSecretFile(credentials(), 'new')).toThrow(refusal(credentials(), 'FIFO', reason)); + } else { + writeSecretFile(credentials(), 'new'); + } + + const received = Buffer.alloc(8); + expect(received.toString('utf-8', 0, fs.readSync(reader, received))).toBe(reason ? '' : 'new'); + } finally { + fs.closeSync(reader); + } + }); + + // The owner rule holds for a directory and a socket too, not for links and FIFOs + // alone: in a shared directory the owner of such an entry can put a link in its place + // once it was looked at. + test('refuses a directory that belongs to another user', () => { + fs.mkdirSync(credentials()); + runAs(1000); + report('lstatSync', credentials(), { uid: 3000 }); + report('statSync', tmpDir, { uid: 2000 }); + + expect(() => writeSecretFile(credentials(), 'new')).toThrow(refusal(credentials(), 'entry', ANOTHER_USER)); + }); + + test('writes to a device whoever it belongs to and however many names it has', () => { + // Only a privileged user can make a device, so it is not something another user put + // at the path. Its reported owner says little: a user namespace reports an owner + // that it does not map as the overflow user. + const mode = fs.statSync('/dev/null').mode; + runAs(1000); + report('lstatSync', '/dev/null', { uid: 3000, nlink: 2 }); + report('statSync', '/dev', { uid: 2000 }); + + writeSecretFile('/dev/null', 'new'); + + expect(fs.statSync('/dev/null').mode).toBe(mode); + }); + + test('does not take the link count of a directory for a second name', () => { + // Most file systems report more than one for every directory. A directory at the path + // fails as it always did. + fs.mkdirSync(credentials()); + runAs(1000); + report('lstatSync', credentials(), { uid: 1000, nlink: 2 }); + + expect(() => saveCredentials(NEW)).toThrow('EISDIR'); + }); }); }); diff --git a/knip.json b/knip.json index fa9539f46..fe83c8b79 100644 --- a/knip.json +++ b/knip.json @@ -5,6 +5,7 @@ ], "ignoreBinaries": [ "mise", + "mkfifo", "semgrep" ], "ignoreExportsUsedInFile": { From f9c4c73c047d589a9948f92cf3b1c4d5983f0a6e Mon Sep 17 00:00:00 2001 From: bgagent Date: Wed, 25 Nov 2026 18:13:19 -0600 Subject: [PATCH 08/11] fix(orchestration): retry a failed settle once after its window Two gaps of the settle window that this branch added. The finish time of a record without completed_at was its updated_at. A late write that moved updated_at would have passed for the write that ended the task. updated_at is not read any more. A record is judged by its two times only when it carries both; one that lacks completed_at or the stream's stamp is late once the child's row already holds the failed verdict. A settle that failed inside the window was never retried after it, where every later write used to be the retry. A try inside the window that did not land (a call threw, or the reaction call answered false, which is how the Linear adapter reports a tracker that fails) now leaves the task's id on the child's row, in the new optional attribute unsettled_task_id. The first record after the window that finds the mark runs the step once more, however late it was written, and the mark is removed after that try whatever it did: a mark that stayed would repeat the step on every later write, which is #1073. Not covered, and said in the comment of the step: only a later write on the task record triggers that try; it is the last one, so the settle is lost when the tracker is still down then (a warning is logged); a state call that failed alone is not owed, because the adapter answers false both for a failed request and for nothing to move; the try after the window can move back an issue that a person has taken over by then. The mark is read with the rows by a query that is not strongly consistent, and its removal can fail: either can bring one more try after the window, also when nothing is owed. A record that the step leaves out as late is logged, as a warning when it is the record that brought the verdict to the row. Tests pin the boundary: 300 s after the end settles, 301 s does not. A comment in linear-feedback.ts now names this step as the one caller that reads the answer of the reaction swap. --- cdk/src/handlers/orchestration-reconciler.ts | 251 ++++++++--- cdk/src/handlers/shared/linear-feedback.ts | 3 +- .../handlers/shared/orchestration-store.ts | 10 + .../handlers/orchestration-reconciler.test.ts | 422 +++++++++++++++++- 4 files changed, 632 insertions(+), 54 deletions(-) diff --git a/cdk/src/handlers/orchestration-reconciler.ts b/cdk/src/handlers/orchestration-reconciler.ts index 20ff7f054..48c1b568c 100644 --- a/cdk/src/handlers/orchestration-reconciler.ts +++ b/cdk/src/handlers/orchestration-reconciler.ts @@ -92,7 +92,6 @@ import { setStatusCommentId, type OrchestrationChildRow, } from './shared/orchestration-store'; -import { finishTimeMs } from './shared/scoreboard'; import { encodeMarkdownUrl } from './shared/screenshot-url'; import { ORCHESTRATION_CHILD_TASK_INDEX_NAME } from './shared/storage-names'; import { readTaskPrNumber } from './shared/task-pr-number'; @@ -543,28 +542,114 @@ async function reloadIterationScreenshot(taskId?: string): Promise<{ screenshotU * carries the new image only, so the write that ended the task cannot be told from a later * one by its content: the time between the task's end and the write separates them. After * the window a person may have taken the issue over, and the surface cannot tell their - * running state from the agent's (#1073). Inside it the step runs for every record on - * purpose. Nothing retries a failed surface call, so the next record is the retry: the - * orchestrator's ttl stamp, one poll after a terminal write it did not make itself (30 s - * by default; `poll_interval_ms` can make it as long as this window), or a redelivery. + * running state from the agent's (#1073). Inside it the step runs for every record that + * carries both times, on purpose. Nothing retries a failed surface call, so the next + * record is the retry: the orchestrator's ttl stamp, one poll after a terminal write it + * did not make itself (30 s by default; `poll_interval_ms` can make it as long as this + * window), or a redelivery. After the window the next record is the retry only of a try + * that the child's row records as not landed (step 1b). */ const SETTLE_WINDOW_MINUTES = 5; /** - * Whether the record was written longer after its task ended than the settle window. The - * stream stamps a record with the time of its write, in seconds, so a delivery that comes - * late, or again, decides as the first one would have. A record without that stamp or - * without a finish time is not late: NaN compares false. + * The time of a record's write in epoch milliseconds: the stream's stamp, a number of + * seconds, also when it comes as its text. NaN when the record carries none, or anything + * else. */ -function writtenLongAfterTaskEnded(record: DynamoDBRecord): boolean { - const image = record.dynamodb?.NewImage; - const endedAtMs = finishTimeMs({ completed_at: image?.completed_at?.S, updated_at: image?.updated_at?.S }); - const writtenAtMs = Number(record.dynamodb?.ApproximateCreationDateTime) * 1000; +function writeTimeMs(record: DynamoDBRecord): number { + const stamp: unknown = record.dynamodb?.ApproximateCreationDateTime; + if (typeof stamp === 'number') return stamp * 1000; + return typeof stamp === 'string' && /^\d+(\.\d+)?$/.test(stamp) ? Number(stamp) * 1000 : NaN; +} + +/** + * Whether a record comes too late for step 1b of `reconcileTerminalChild`. + * + * A record that carries both times is late when it was written longer after + * `completed_at` than the settle window. The stream stamps a record with the time of its + * write, in seconds, so a delivery that comes late, or again, decides as the first one + * would have. `updated_at` is not read in place of `completed_at`: a later write that + * moved it would pass for the write that ended the task. + * + * A record that lacks either time, or carries one that is not a time, is late once the + * child's row holds the verdict (`verdictOnRow`): it is not the record that brought the + * verdict there. (`finishTimeMs` in shared/scoreboard.ts names the writers that set no + * `completed_at` until #1048; the stream's stamp is not a required member of a record.) + * For such records the step runs for the one that brings the verdict and, when that try + * did not land, for the next one, not for every record of the first five minutes. Their + * issue is therefore not settled when the sweep (`reconcile-stranded-orchestrations.ts`) + * recorded the verdict first, or when the delivery that recorded it died before the step. + */ +function writtenLongAfterTaskEnded(record: DynamoDBRecord, verdictOnRow: boolean): boolean { + const endedAtMs = Date.parse(record.dynamodb?.NewImage?.completed_at?.S ?? ''); + const writtenAtMs = writeTimeMs(record); + if (Number.isNaN(endedAtMs) || Number.isNaN(writtenAtMs)) return verdictOnRow; return writtenAtMs - endedAtMs > SETTLE_WINDOW_MINUTES * 60 * 1000; } -/** Apply one terminal child's reconcile plan. `lateWrite`: see {@link writtenLongAfterTaskEnded}. */ -async function reconcileTerminalChild(evt: TerminalTaskEvent, lateWrite: boolean): Promise { +/** + * Log the record that step 1b of `reconcileTerminalChild` leaves out as late, with its two + * times (null for one the record does not carry, and for a stamp that is not a number of + * seconds). A warning when the record is the one that brought the verdict to the row: its + * task's finish time is long before its write, with a slow clock for example. No earlier + * record settled the issue then: it stays as the agent left it, which can contradict the + * graph. + */ +function logLateRecord( + record: DynamoDBRecord, + ids: { orchestration_id: string; sub_issue_id: string; task_id: string }, + broughtVerdict: boolean, +): void { + const writtenAt = new Date(writeTimeMs(record)); + logger[broughtVerdict ? 'warn' : 'info']('Reconciler left the issue of a failed child alone: a late write on its task record', { + ...ids, + completed_at: record.dynamodb?.NewImage?.completed_at?.S ?? null, + written_at: Number.isNaN(writtenAt.getTime()) ? null : writtenAt.toISOString(), + brought_verdict: broughtVerdict, + }); +} + +/** + * Record on a child's row that the settle of its task is owed (see step 1b of + * `reconcileTerminalChild`), or that it no longer is. + * + * Both writes are conditional. The mark is set only while the row still names the task: + * after a new release the row belongs to another task. It is removed only while it names + * the task. `updated_at` is left alone, as `refreshUnstartedText` leaves it: the sweep and + * the retry's once-only key compare it. Best-effort, never throws. A mark that could not + * be set is the state before the mark existed: no record after the window tries again. + * One that could not be removed stays, and the next late record tries once more. + */ +async function recordUnsettled( + ids: { orchestration_id: string; sub_issue_id: string; task_id: string }, + owed: boolean, +): Promise { + try { + await ddb.send(new UpdateCommand({ + TableName: ORCHESTRATION_TABLE, + Key: { orchestration_id: ids.orchestration_id, sub_issue_id: ids.sub_issue_id }, + UpdateExpression: owed ? 'SET unsettled_task_id = :tid' : 'REMOVE unsettled_task_id', + ConditionExpression: owed ? 'child_task_id = :tid' : 'unsettled_task_id = :tid', + ExpressionAttributeValues: { ':tid': ids.task_id }, + })); + if (owed) { + logger.warn('Settle of a failed child did not land: owed to the next record of its task', ids); + } else { + logger.info('Settle of a failed child is no longer owed', ids); + } + } catch (err) { + if (isConditionalCheckFailed(err)) return; // released again, or the mark is not this task's + logger.warn('Could not record whether the settle of a failed child is owed (non-fatal)', { + ...ids, owed, error: err instanceof Error ? err.message : String(err), + }); + } +} + +/** + * Apply one terminal child's reconcile plan. `record` is the stream record the event was + * read from: step 1b reads its times ({@link writtenLongAfterTaskEnded}). + */ +async function reconcileTerminalChild(evt: TerminalTaskEvent, record: DynamoDBRecord): Promise { const orchestrationId = evt.orchestrationId!; const subIssueId = await resolveSubIssueId(evt.taskId); @@ -673,46 +758,112 @@ async function reconcileTerminalChild(evt: TerminalTaskEvent, lateWrite: boolean // human-pulled-back one) and idempotent on replay. The ❌ reaction + the // failure reason on the panel convey "it failed"; a reply re-runs it (the // retry re-drives the state not-started → running). Skip the integration - // node (synthetic id, no real issue), a stale event (the issue shows - // what a later run did), and a record that was written long after the task - // ended (see SETTLE_WINDOW_MINUTES). Best-effort; never throws. + // node (synthetic id, no real issue) and a stale event (the issue shows + // what a later run did), owed or not. Skip a record that comes too late + // (see `writtenLongAfterTaskEnded`) unless the settle is owed. Best-effort; + // never throws. + // + // Owed: a try that was not late and did not land leaves the task's id on + // the child's row (`unsettled_task_id`, written by `recordUnsettled`), and + // the next record of that task tries again, however late it was written. + // A try did not land when one of its calls threw or the reaction call + // answered false. The Linear adapter does not throw when the tracker fails + // every request or a token cannot be resolved: both calls answer false + // then, and so does the reaction call when a marker stays that it could + // not remove. It answers true when only its read of the reactions failed + // and the failure marker could be added: that try counts as landed, with + // the agent's marker left beside the new one. The answer of the state call + // is not read for this: it is false also when there was nothing to move, + // so a state call that failed alone is not owed. + // + // A late try is the last one, whatever it did: neither a false answer nor + // a throw tells a failure that will pass from one that no retry cures, and + // a mark that stayed would repeat the step on every later write (#1073). + // A warning says so when that try did not land. A try that does not leave + // the settle owed removes the mark that it read. + // + // A late record can still try although nothing is owed, or a second time. + // The mark is read with the rows, before step 1, by a query that is not + // strongly consistent. A mark that was set moments before can be missing + // from them: a try that lands then leaves it on the row, and unless a + // later record inside the window removes it, the first late record tries. + // A mark that was removed moments before can still be in them: that record + // tries once more. So does the next late record after a mark that could + // not be removed (see `recordUnsettled`). + // + // What a late try costs: it repeats both calls, also when one of them had + // landed and when no retry can remove the marker that stayed, and by then + // a person may have taken the issue over: it is moved back out of their + // running state. Nothing triggers a late try but a later write on the task + // record, the preview screenshot of a later push for example: the settle + // of a task that is not written again stays owed. const settleChannel = channelForMeta(snapshot.meta); - if (settleChannel && !plan.terminalSucceeded && !stale && !lateWrite && !isIntegrationNode(subIssueId)) { + if (settleChannel && !plan.terminalSucceeded && !stale && !isIntegrationNode(subIssueId)) { const channel = settleChannel; - const childRef = issueRef(subIssueId, snapshot.meta.credentials_ref); - try { - const reverted = (await channel.revertState?.(childRef)) ?? false; - // Also settle the child's ISSUE reaction to ❌. The agent reacts ✅ on its - // OWN verdict (agent-success + regression-only build gate — a build that was - // already red before the agent isn't counted as the agent's regression, so - // it posts ✅ and "Task completed"). The orchestration gate is stricter - // (build_passed===false ⇒ failed, absolute), so a child can legitimately end - // agent-✅ but graph-failed — leaving a ✅ reaction that contradicts the - // failed node (observed in practice: PR opened, agent ✅, build red). - // Replacing the reaction clears the status markers and adds ❌. Markers are - // matched by emoji alone, so a person's own reaction with one of them goes - // too; it's idempotent on replay. - // This makes the reaction agree with the reverted state + the panel's ❌ - // row. (The stale "✅ Task completed" comment is left as history — the - // surface won't let us edit another actor's comment; the reaction + state + - // panel are the authoritative signals, and a reply re-runs the child.) - const reactionSwapped = (await channel.replaceIssueReaction?.(childRef, 'failed')) ?? false; - if (reverted || reactionSwapped) { - logger.info('Reconciler settled a failed child to match the graph (state + reaction)', { + const ids = { orchestration_id: orchestrationId, sub_issue_id: subIssueId, task_id: evt.taskId }; + // The row as this delivery read it, before step 1 wrote to it. + const rowAsRead = snapshot.children.find((c) => c.sub_issue_id === subIssueId); + const broughtVerdict = rowAsRead?.child_status !== 'failed'; + const owed = rowAsRead?.unsettled_task_id === evt.taskId; + const late = writtenLongAfterTaskEnded(record, !broughtVerdict); + if (late && !owed) { + // No line for a surface that has neither call (Jira): the step does nothing + // there for any record, so a late one is not left out of anything. + if (channel.revertState || channel.replaceIssueReaction) logLateRecord(record, ids, broughtVerdict); + } else { + const childRef = issueRef(subIssueId, snapshot.meta.credentials_ref); + // What the state call answered, null until it has. The try has landed when + // both calls have answered and the reaction call did not answer false. + let reverted: boolean | null = null; + let landed = false; + try { + reverted = (await channel.revertState?.(childRef)) ?? false; + // Also settle the child's ISSUE reaction to ❌. The agent reacts ✅ on its + // OWN verdict (agent-success + regression-only build gate — a build that was + // already red before the agent isn't counted as the agent's regression, so + // it posts ✅ and "Task completed"). The orchestration gate is stricter + // (build_passed===false ⇒ failed, absolute), so a child can legitimately end + // agent-✅ but graph-failed — leaving a ✅ reaction that contradicts the + // failed node (observed in practice: PR opened, agent ✅, build red). + // Replacing the reaction clears the status markers and adds ❌. Markers are + // matched by emoji alone, so the swap also tries to delete a person's own + // reaction with one of them; it's idempotent on replay. + // This makes the reaction agree with the reverted state + the panel's ❌ + // row. (The stale "✅ Task completed" comment is left as history — the + // surface won't let us edit another actor's comment; the reaction + state + + // panel are the authoritative signals, and a reply re-runs the child.) + const reactionSwapped = await channel.replaceIssueReaction?.(childRef, 'failed'); + if (reverted || reactionSwapped) { + logger.info('Reconciler settled a failed child to match the graph (state + reaction)', { + orchestration_id: orchestrationId, + sub_issue_id: subIssueId, + task_status: outcome.status, + build_passed: outcome.build_passed, + state_reverted: reverted, + reaction_swapped: reactionSwapped ?? false, + }); + } + landed = reactionSwapped !== false; + } catch (err) { + logger.warn('Failed to reconcile failed child Linear state/reaction (non-fatal)', { orchestration_id: orchestrationId, sub_issue_id: subIssueId, - task_status: outcome.status, - build_passed: outcome.build_passed, - state_reverted: reverted, - reaction_swapped: reactionSwapped, + error: err instanceof Error ? err.message : String(err), }); } - } catch (err) { - logger.warn('Failed to reconcile failed child Linear state/reaction (non-fatal)', { - orchestration_id: orchestrationId, - sub_issue_id: subIssueId, - error: err instanceof Error ? err.message : String(err), - }); + // Whether this try leaves the settle owed: it did not land, and it was not + // late. A late try was the last one. + let unsettled = false; + if (!landed) { + unsettled = !late; + if (late) { + logger.warn('Settle of a failed child did not land on its last try: its issue can contradict the graph', { + ...ids, + state_reverted: reverted, + }); + } + } + if (unsettled !== owed) await recordUnsettled(ids, unsettled); } } @@ -1681,7 +1832,7 @@ export async function handler(event: DynamoDBStreamEvent): Promise { rollupTaskCostMock.mockReset().mockResolvedValue(false); @@ -162,10 +164,15 @@ function taskRecord(fields: { sequenceNumber?: string; // When the write happened: the stream stamps it on the record, in seconds. written_at?: string; + // The task's own times, as its record carries them. + completed_at?: string; + updated_at?: string; }): DynamoDBRecord { const img: Record = {}; if (fields.task_id) img.task_id = { S: fields.task_id }; if (fields.status) img.status = { S: fields.status }; + if (fields.completed_at) img.completed_at = { S: fields.completed_at }; + if (fields.updated_at) img.updated_at = { S: fields.updated_at }; if (fields.build_passed !== undefined) img.build_passed = { BOOL: fields.build_passed }; if (fields.code_changed !== undefined) img.code_changed = { BOOL: fields.code_changed }; if (fields.answer_text) img.answer_text = { S: fields.answer_text }; @@ -654,8 +661,9 @@ describe('orchestration-reconciler handler', () => { })); expect(settled()).toEqual([2, 2]); - // A record from before #1048 has no completed_at: its updated_at is the write that ended the task. - await handler(write(minutesAfterEnd(6), { updated_at: { S: minutesAfterEnd(0) } })); + // A record without completed_at has no time of its task's end. Once the row holds the + // verdict it is a later write, also when it moved updated_at to its own time. + await handler(write(minutesAfterEnd(6), { updated_at: { S: minutesAfterEnd(6) } })); expect(settled()).toEqual([2, 2]); // The panel is refreshed every time: a late write is how a preview reaches it. @@ -2234,6 +2242,7 @@ function orchestrationStore( child_task_id?: string; child_branch_name?: string; failure_reason?: string; + unsettled_task_id?: string; }>, meta: StoreRow = {}, ) { @@ -2307,6 +2316,9 @@ function orchestrationStore( }; } +/** What the handler logs for a record whose late write leaves a failed child's issue as it is. */ +const LEFT_ALONE_AS_LATE = 'Reconciler left the issue of a failed child alone: a late write on its task record'; + describe('orchestration-reconciler handler — an event of a task that no longer decides its row', () => { // A terminal task record is written again long after its status was set: the // preview screenshot of a later push is stamped on the task that opened the @@ -2436,6 +2448,15 @@ describe('orchestration-reconciler handler — an event of a task that no longer expect(upsertStatusCommentMock).toHaveBeenCalledTimes(1); expect(revertIssueToNotStartedMock).not.toHaveBeenCalled(); expect(swapIssueReactionMock).not.toHaveBeenCalledWith(expect.anything(), 'A', 'x'); + // No earlier record settled the issue, which can now contradict the graph: a warning says so. + expect(loggerMock.warn).toHaveBeenCalledWith(LEFT_ALONE_AS_LATE, { + orchestration_id: 'orch_1', + sub_issue_id: 'A', + task_id: 'TA', + completed_at: '2026-11-24T10:00:00Z', + written_at: '2026-11-24T10:06:00.000Z', + brought_verdict: true, + }); }); test.each([ @@ -2446,7 +2467,16 @@ describe('orchestration-reconciler handler — an event of a task that no longer { sub_issue_id: 'A', child_status: status, child_task_id: 'TA' }, { sub_issue_id: 'B', depends_on: ['A'], child_status: 'blocked' }, ]); - await handler(lateFailure()); + // The write that ended the task. A redelivery is the same record again, with the same times. + await handler({ + Records: [taskRecord({ + task_id: 'TA', + status: 'FAILED', + orchestration_id: 'orch_1', + completed_at: '2026-11-24T10:00:00Z', + written_at: '2026-11-24T10:00:00Z', + })], + } as never); expect(store.status('A')).toBe('failed'); expect(store.status('B')).toBe('skipped'); @@ -2474,6 +2504,392 @@ describe('orchestration-reconciler handler — an event of a task that no longer }); }); +describe('orchestration-reconciler handler — the issue of a failed sub-issue and the time of the write (#1073)', () => { + // The handler moves the issue of a failed child back and replaces its reaction + // for every record of the task that is not late. Late is: written more than + // five minutes after completed_at or, for a record that lacks one of the two + // times, written when the row already held the verdict. A try that was not late + // and did not land is owed to the next record of the task, however late that + // one is. A late try is the last one. + beforeEach(() => { + ddbSend.mockReset(); + createTaskCoreMock.mockReset(); + upsertStatusCommentMock.mockReset().mockResolvedValue('panel-1'); + transitionIssueStateMock.mockReset().mockResolvedValue(true); + revertIssueToNotStartedMock.mockReset().mockResolvedValue(true); + swapIssueReactionMock.mockReset().mockResolvedValue(true); + }); + + const ENDED = '2026-11-24T10:00:00Z'; + const DAY = 24 * 3600; + /** The time that many seconds after the task ended. */ + const after = (seconds: number) => new Date(Date.parse(ENDED) + seconds * 1000).toISOString(); + /** The table with one sub-issue, A, whose task TA ended FAILED. */ + const childA = (row: { child_status: string; unsettled_task_id?: string }, meta: StoreRow = {}) => + orchestrationStore([{ sub_issue_id: 'A', child_task_id: 'TA', ...row }], meta); + /** + * The record of TA as a write made that many seconds after the task ended + * delivers it. ``times``: the times of the task that the record carries. + */ + const write = (seconds: number, times: { completed_at?: string; updated_at?: string } = { completed_at: ENDED }) => ({ + Records: [taskRecord({ task_id: 'TA', status: 'FAILED', orchestration_id: 'orch_1', written_at: after(seconds), ...times })], + }) as never; + /** How often A's issue was moved back, and how often its reaction was replaced. */ + const settled = () => [revertIssueToNotStartedMock, swapIssueReactionMock] + .map((mock) => mock.mock.calls.filter((call) => call[1] === 'A').length); + const isMarkWrite = (cmd: StoreCommand) => String(cmd.input.UpdateExpression).includes('unsettled_task_id'); + /** The writes of the mark that the handler sent, in order. */ + const markWrites = () => ddbSend.mock.calls.map(([cmd]) => cmd as StoreCommand).filter(isMarkWrite).map((cmd) => cmd.input); + /** What the handler logs when it sets the mark, removes it, or fails to write it. */ + const OWED = 'Settle of a failed child did not land: owed to the next record of its task'; + const NO_LONGER_OWED = 'Settle of a failed child is no longer owed'; + const MARK_NOT_WRITTEN = 'Could not record whether the settle of a failed child is owed (non-fatal)'; + /** ... and for a late try that did not land. */ + const LAST_TRY_DID_NOT_LAND = 'Settle of a failed child did not land on its last try: its issue can contradict the graph'; + const IDS = { orchestration_id: 'orch_1', sub_issue_id: 'A', task_id: 'TA' }; + + test('the write that ends the task settles the issue, the next one 30 s later settles it again, one made days later does not', async () => { + const store = childA({ child_status: 'released' }); + // The adapter moves the issue once: a repeat finds nothing to move and answers false. + revertIssueToNotStartedMock.mockResolvedValueOnce(true).mockResolvedValue(false); + + await handler(write(0)); + expect(settled()).toEqual([1, 1]); + // The orchestrator's ttl stamp, one poll later: the retry of a surface call that failed. + await handler(write(30)); + expect(settled()).toEqual([2, 2]); + // The preview screenshot of a later push to the branch. + await handler(write(3 * DAY)); + expect(settled()).toEqual([2, 2]); + + expect(store.status('A')).toBe('failed'); + // Every try landed: nothing is owed, and the row is not written for it. + expect(markWrites()).toEqual([]); + expect(loggerMock.info).toHaveBeenCalledWith(LEFT_ALONE_AS_LATE, { + orchestration_id: 'orch_1', + sub_issue_id: 'A', + task_id: 'TA', + completed_at: ENDED, + written_at: after(3 * DAY), + brought_verdict: false, + }); + expect(loggerMock.warn).not.toHaveBeenCalledWith(LEFT_ALONE_AS_LATE, expect.anything()); + }); + + test.each([ + ['exactly five minutes after the end is not late: the issue is settled', 300, [1, 1]], + // The stream stamps the write in whole seconds. + ['five minutes and one second after the end is late: the issue is left alone', 301, [0, 0]], + ])('a record written %s', async (_name, seconds, expected) => { + childA({ child_status: 'failed' }); + await handler(write(seconds)); + + expect(settled()).toEqual(expected); + }); + + test.each([ + ['no time of its write', undefined], + // The stream writes a number of seconds. Some tools turn it into a date string. + ['a date string for the time of its write', after(0)], + // What a serializer writes for a member that is not there. + ['null for the time of its write', null], + ])('a record with completed_at and %s is judged by the row: it settles the issue when it brings the verdict and leaves it alone once the row holds it', async (_name, stamp) => { + const store = childA({ child_status: 'released' }); + const record = taskRecord({ task_id: 'TA', status: 'FAILED', orchestration_id: 'orch_1', completed_at: ENDED }); + if (stamp !== undefined) Object.assign(record.dynamodb!, { ApproximateCreationDateTime: stamp }); + + await handler({ Records: [record] } as never); + expect(store.status('A')).toBe('failed'); + expect(settled()).toEqual([1, 1]); + + // The same record again. Without both times it cannot be told from a write made days later. + await handler({ Records: [record] } as never); + expect(settled()).toEqual([1, 1]); + expect(loggerMock.info).toHaveBeenCalledWith(LEFT_ALONE_AS_LATE, { ...IDS, completed_at: ENDED, written_at: null, brought_verdict: false }); + }); + + test('a time of its write that comes as text is read as the number of seconds it is', async () => { + // The example record of the Lambda guide on event filtering carries the stamp as "1678831218.0". + childA({ child_status: 'failed' }); + const written = (seconds: number) => { + const record = taskRecord({ task_id: 'TA', status: 'FAILED', orchestration_id: 'orch_1', completed_at: ENDED }); + Object.assign(record.dynamodb!, { ApproximateCreationDateTime: `${Date.parse(after(seconds)) / 1000}.0` }); + return { Records: [record] } as never; + }; + + await handler(written(30)); + expect(settled()).toEqual([1, 1]); + await handler(written(301)); + expect(settled()).toEqual([1, 1]); + }); + + test('a record without completed_at leaves the issue alone once the row holds the verdict, also when its write moved updated_at', async () => { + // Such a record has no time of its task's end. If updated_at were read in its + // place, a write that sets it to its own time would pass for the end of the task. + childA({ child_status: 'failed' }); + await handler(write(3 * DAY, { updated_at: after(3 * DAY) })); + + expect(settled()).toEqual([0, 0]); + expect(loggerMock.info).toHaveBeenCalledWith(LEFT_ALONE_AS_LATE, expect.objectContaining({ + completed_at: null, + written_at: after(3 * DAY), + brought_verdict: false, + })); + }); + + test('a late record that carries neither time is logged with null for both', async () => { + childA({ child_status: 'failed' }); + await handler({ Records: [taskRecord({ task_id: 'TA', status: 'FAILED', orchestration_id: 'orch_1' })] } as never); + + expect(settled()).toEqual([0, 0]); + expect(loggerMock.info).toHaveBeenCalledWith(LEFT_ALONE_AS_LATE, { ...IDS, completed_at: null, written_at: null, brought_verdict: false }); + }); + + test('a completed_at that is not a time counts as none: the row decides, not the time of the write', async () => { + childA({ child_status: 'failed' }); + await handler(write(30, { completed_at: 'not a time' })); + + expect(settled()).toEqual([0, 0]); + }); + + test('a record without completed_at settles the issue when it is the one that brings the verdict to the row', async () => { + const store = childA({ child_status: 'released' }); + await handler(write(3 * DAY, { updated_at: after(3 * DAY) })); + + expect(store.status('A')).toBe('failed'); + expect(settled()).toEqual([1, 1]); + }); + + test('a settle that did not land is owed: the next write settles the issue however late it is, and the one after it leaves the issue alone', async () => { + const store = childA({ child_status: 'released' }); + // The tracker is down. The Linear adapter does not throw then: both calls answer false. + revertIssueToNotStartedMock.mockResolvedValue(false); + swapIssueReactionMock.mockResolvedValue(false); + await handler(write(0)); + await handler(write(30)); + expect(settled()).toEqual([2, 2]); + expect(store.row('A').unsettled_task_id).toBe('TA'); + expect(loggerMock.warn).toHaveBeenCalledWith(OWED, IDS); + + // The tracker is back when the next write comes, long after the window. + revertIssueToNotStartedMock.mockResolvedValue(true); + swapIssueReactionMock.mockResolvedValue(true); + await handler(write(3 * DAY)); + expect(settled()).toEqual([3, 3]); + expect(store.row('A')).not.toHaveProperty('unsettled_task_id'); + expect(loggerMock.info).toHaveBeenCalledWith(NO_LONGER_OWED, IDS); + // That record was tried, and its try landed: neither line of a late record is written for it. + expect(loggerMock.info).not.toHaveBeenCalledWith(LEFT_ALONE_AS_LATE, expect.anything()); + expect(loggerMock.warn).not.toHaveBeenCalledWith(LAST_TRY_DID_NOT_LAND, expect.anything()); + + await handler(write(4 * DAY)); + expect(settled()).toEqual([3, 3]); + + // The mark was set once and removed once, on condition, and nothing else was written with it. + const row = { TableName: 'OrchestrationTable', Key: { orchestration_id: 'orch_1', sub_issue_id: 'A' } }; + expect(markWrites()).toEqual([ + { + ...row, + UpdateExpression: 'SET unsettled_task_id = :tid', + ConditionExpression: 'child_task_id = :tid', + ExpressionAttributeValues: { ':tid': 'TA' }, + }, + { + ...row, + UpdateExpression: 'REMOVE unsettled_task_id', + ConditionExpression: 'unsettled_task_id = :tid', + ExpressionAttributeValues: { ':tid': 'TA' }, + }, + ]); + }); + + test('a try inside the window that lands removes the mark: a later write leaves the issue alone', async () => { + const store = childA({ child_status: 'released' }); + swapIssueReactionMock.mockResolvedValueOnce(false); + await handler(write(0)); + expect(store.row('A').unsettled_task_id).toBe('TA'); + + await handler(write(30)); + expect(store.row('A')).not.toHaveProperty('unsettled_task_id'); + await handler(write(3 * DAY)); + expect(settled()).toEqual([2, 2]); + }); + + test.each([ + ['the tracker is still down', false], + ['a marker stays that cannot be removed', true], + ])('a late try is the last one whatever the surface answers (%s): a warning says that it did not land', async (_name, reverted) => { + const store = childA({ child_status: 'failed', unsettled_task_id: 'TA' }); + // The reaction call answers false in both cases: its answer does not tell them apart. + revertIssueToNotStartedMock.mockResolvedValue(reverted); + swapIssueReactionMock.mockResolvedValue(false); + await handler(write(3 * DAY)); + expect(settled()).toEqual([1, 1]); + expect(store.row('A')).not.toHaveProperty('unsettled_task_id'); + // Without it the last line would be the one that the settle is no longer owed. + expect(loggerMock.warn).toHaveBeenCalledWith(LAST_TRY_DID_NOT_LAND, { ...IDS, state_reverted: reverted }); + + await handler(write(4 * DAY)); + expect(settled()).toEqual([1, 1]); + }); + + test.each([ + // The state call throws: the reaction call is not made. + ['the state call', revertIssueToNotStartedMock, [1, 0], [2, 1]], + // The state is moved back, then the reaction call throws. + ['the reaction call', swapIssueReactionMock, [1, 1], [2, 2]], + ])('a throw of %s inside the window leaves the settle owed, and the next try makes both calls', async (_name, call, first, second) => { + const store = childA({ child_status: 'released' }); + call.mockRejectedValueOnce(new Error('surface unavailable')); + await handler(write(0)); + expect(settled()).toEqual(first); + expect(store.row('A').unsettled_task_id).toBe('TA'); + // A try inside the window is not the last one: no line says that it was. + expect(loggerMock.warn).not.toHaveBeenCalledWith(LAST_TRY_DID_NOT_LAND, expect.anything()); + + await handler(write(3 * DAY)); + expect(settled()).toEqual(second); + expect(store.row('A')).not.toHaveProperty('unsettled_task_id'); + }); + + test.each([ + // What the state call did is not known when it threw: the line says null. + ['the state call', revertIssueToNotStartedMock, [1, 0], null], + ['the reaction call', swapIssueReactionMock, [1, 1], true], + // The state call found nothing to move, then the reaction call threw: the line says false. + ['the reaction call, after a state call that moved nothing,', swapIssueReactionMock, [1, 1], false], + ])('a late try is the last one also when %s throws: the mark is removed, a warning says that it did not land, and the next late write leaves the issue alone', async (_name, call, calls, stateReverted) => { + const store = childA({ child_status: 'failed', unsettled_task_id: 'TA' }); + if (stateReverted === false) revertIssueToNotStartedMock.mockResolvedValue(false); + // On every try: if the mark stayed, every later write would try again. + call.mockRejectedValue(new Error('surface unavailable')); + await handler(write(3 * DAY)); + expect(settled()).toEqual(calls); + expect(store.row('A')).not.toHaveProperty('unsettled_task_id'); + expect(loggerMock.warn).toHaveBeenCalledWith(LAST_TRY_DID_NOT_LAND, { ...IDS, state_reverted: stateReverted }); + + await handler(write(4 * DAY)); + expect(settled()).toEqual(calls); + }); + + test('a mark that names another task is not this task\'s: a late write leaves the issue alone', async () => { + // What an earlier run of the sub-issue left on the row. + const store = childA({ child_status: 'failed', unsettled_task_id: 'T-earlier' }); + await handler(write(3 * DAY)); + + expect(settled()).toEqual([0, 0]); + expect(store.row('A').unsettled_task_id).toBe('T-earlier'); + }); + + test.each([ + ['repaired by a comment', 'succeeded'], + ['skipped again after a retry of its predecessor', 'skipped'], + ])('a settle that is owed is not tried once the sub-issue was %s: the task no longer decides its row', async (_name, status) => { + const store = childA({ child_status: status, unsettled_task_id: 'TA' }); + await handler(write(3 * DAY)); + + expect(settled()).toEqual([0, 0]); + expect(store.row('A').unsettled_task_id).toBe('TA'); + }); + + test('a surface without a reaction on the issue owes nothing', async () => { + // Jira has neither of the two calls: there is no answer that could say "not landed". + childA({ child_status: 'released' }, { channel_source: 'jira' }); + await handler(write(0)); + + expect(markWrites()).toEqual([]); + }); + + test('a surface that has neither call is not logged as left alone: the step does nothing there for any record', async () => { + childA({ child_status: 'released' }, { channel_source: 'jira' }); + // Late and the first to reach the row, then late: on Linear a warning and an info line. + await handler(write(6 * 60)); + await handler(write(3 * DAY)); + + expect(loggerMock.warn).not.toHaveBeenCalledWith(LEFT_ALONE_AS_LATE, expect.anything()); + expect(loggerMock.info).not.toHaveBeenCalledWith(LEFT_ALONE_AS_LATE, expect.anything()); + }); + + test.each<[string, Partial]>([ + ['the state call alone', { revertState: () => Promise.resolve(true) }], + ['the reaction call alone', { replaceIssueReaction: () => Promise.resolve(true) }], + ])('a surface that has %s is logged as left alone, like one that has both', async (_name, calls) => { + // Linear has both calls and Jira neither, and this handler is given no other surface. + // The registry takes any adapter: one with a single call stands in for Jira's here. + const restore = registerChannelFactory('jira', () => ({ + kind: 'another-tracker', + postComment: () => Promise.resolve(null), + upsertComment: () => Promise.resolve({ commentId: 'panel-1' }), + reportFailure: () => Promise.resolve(), + ...calls, + })); + try { + childA({ child_status: 'failed' }, { channel_source: 'jira' }); + await handler(write(3 * DAY)); + } finally { + restore(); + } + + expect(loggerMock.info).toHaveBeenCalledWith(LEFT_ALONE_AS_LATE, expect.objectContaining({ brought_verdict: false })); + }); + + test('a mark that cannot be written is a warning: the record is processed to its end and not reported for retry', async () => { + const store = childA({ child_status: 'released' }); + swapIssueReactionMock.mockResolvedValue(false); + store.before(isMarkWrite, () => { throw new Error('table unavailable'); }); + const record = taskRecord({ + task_id: 'TA', status: 'FAILED', orchestration_id: 'orch_1', sequenceNumber: 'seq-1', completed_at: ENDED, written_at: ENDED, + }); + + await expect(handler({ Records: [record] } as never)).resolves.toEqual({ batchItemFailures: [] }); + + expect(loggerMock.warn).toHaveBeenCalledWith(MARK_NOT_WRITTEN, { ...IDS, owed: true, error: 'table unavailable' }); + expect(store.row('A')).not.toHaveProperty('unsettled_task_id'); + expect(upsertStatusCommentMock).toHaveBeenCalledTimes(1); + }); + + test('a mark that cannot be removed stays: a warning, no retry of the record, and the next late write tries once more', async () => { + const store = childA({ child_status: 'failed', unsettled_task_id: 'TA' }); + store.before(isMarkWrite, () => { throw new Error('table unavailable'); }); + const record = taskRecord({ + task_id: 'TA', status: 'FAILED', orchestration_id: 'orch_1', sequenceNumber: 'seq-1', completed_at: ENDED, written_at: after(3 * DAY), + }); + + await expect(handler({ Records: [record] } as never)).resolves.toEqual({ batchItemFailures: [] }); + + expect(settled()).toEqual([1, 1]); + expect(loggerMock.warn).toHaveBeenCalledWith(MARK_NOT_WRITTEN, { ...IDS, owed: false, error: 'table unavailable' }); + expect(store.row('A').unsettled_task_id).toBe('TA'); + + await handler(write(4 * DAY)); + expect(settled()).toEqual([2, 2]); + expect(store.row('A')).not.toHaveProperty('unsettled_task_id'); + }); + + test('the mark is not set on a row that was released again while the surface was called', async () => { + const store = childA({ child_status: 'released' }); + swapIssueReactionMock.mockResolvedValue(false); + store.before(isMarkWrite, () => Object.assign(store.row('A'), { child_status: 'released', child_task_id: 'T2' })); + await handler(write(0)); + + expect(store.row('A')).not.toHaveProperty('unsettled_task_id'); + // The store refused the write on its condition. That is its answer, not a failure: no line. + expect(loggerMock.warn).not.toHaveBeenCalledWith(OWED, expect.anything()); + expect(loggerMock.warn).not.toHaveBeenCalledWith(MARK_NOT_WRITTEN, expect.anything()); + }); + + test('a mark that has become another task\'s since the row was read is not removed', async () => { + const store = childA({ child_status: 'failed', unsettled_task_id: 'TA' }); + store.before(isMarkWrite, () => Object.assign(store.row('A'), { child_task_id: 'T2', unsettled_task_id: 'T2' })); + await handler(write(3 * DAY)); + + expect(settled()).toEqual([1, 1]); + expect(store.row('A').unsettled_task_id).toBe('T2'); + expect(loggerMock.info).not.toHaveBeenCalledWith(NO_LONGER_OWED, expect.anything()); + expect(loggerMock.warn).not.toHaveBeenCalledWith(MARK_NOT_WRITTEN, expect.anything()); + }); +}); + describe('orchestration-reconciler handler — an iteration on a failed sub-issue', () => { const SETTLED_AT = '2026-01-01T00:00:00.000Z'; beforeEach(() => { From 4be987c9b26addec4ea573a2a2dd6ceef555de1b Mon Sep 17 00:00:00 2001 From: bgagent Date: Wed, 25 Nov 2026 18:14:19 -0600 Subject: [PATCH 09/11] fix(cdk): fail synthesis on a guardrail filter added after its version publishGuardrailVersion() renders the guardrail at the call, and the alpha construct keeps what it rendered. A filter added afterwards was missing from the template without an error (a second denied topic, PII, regex or word filter), and the validation, which compared the same kept rendering, passed. The comment promised that synthesis fails. The validation now also compares the JSON text of what the construct renders from, the seven filter lists, the two tiers and the cross-Region configuration, with what it was at the call. The hash is computed from the same input as before, so the version keeps its name and a stack deployed from the previous commits publishes nothing new. Synthesis fails when the guardrail's rendered properties, or the filters, tiers and cross-Region configuration they are rendered from (compared as JSON text), are no longer what they were when its version was published. What the construct's add methods append between the call and the synthesis always fails it. The comparison is not complete: the doc comment says what it compares, and that a cached Lazy value in a property keeps what it produced at the call. Other ways past it are not closed: they take a cast, a filter class of the caller's own, a rebuilt CfnGuardrail, or a change made while synthesis validates. A test fails when a later version of the alpha library renders from one more member that is a list or is read by a generateCfn method. The deployment guide's entry on the version quota now says to count the versions before the first deploy with the fix. --- cdk/src/stacks/agent.ts | 31 +++- cdk/test/stacks/agent.test.ts | 148 +++++++++++++++++- docs/guides/DEPLOYMENT_GUIDE.md | 2 +- .../docs/getting-started/Deployment-guide.md | 2 +- 4 files changed, 171 insertions(+), 12 deletions(-) diff --git a/cdk/src/stacks/agent.ts b/cdk/src/stacks/agent.ts index 90ea1e88d..328448402 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -112,9 +112,13 @@ const GUARDRAIL_VERSION_HASH_LENGTH = 16; * token (aws/aws-cdk#38674), whose text differs from one synthesis to the next: nearly * every deploy published a version, until the guardrail reached its version quota (#1079). * - * The properties are rendered here, not at synthesis: call this once the guardrail is - * fully configured, or synthesis fails. Tags are left out, because a deploy tag does not - * change the guardrail. + * The properties are rendered here, not at synthesis, and the alpha construct keeps what + * it rendered: a filter added after this call can be missing from the template. A cached + * `Lazy` value in a property keeps what it produces here. Call this once the guardrail is + * fully configured. A validation that this call adds to the guardrail fails the synthesis + * when the rendered properties, or the JSON text of the filters, tiers and cross-Region + * configuration that the construct renders them from, are no longer what they were at this + * call. Tags are left out, because a deploy tag does not change the guardrail. */ export function publishGuardrailVersion(guardrail: bedrock.Guardrail, description: string): string { const resource = guardrail.node.children.find(child => child instanceof CfnGuardrail)!; @@ -126,16 +130,27 @@ export function publishGuardrailVersion(guardrail: bedrock.Guardrail, descriptio const { Tags: _tags, ...properties } = Object.values(rendered.Resources)[0].Properties; return JSON.stringify([properties, description]); }; + // What the alpha construct renders the policies and the cross-Region configuration from. + // It keeps the first rendering of each that is not empty, so once `configuration()` has + // run, a change of these members can be missing from every later rendering, the template + // included. + const sources = (): string => JSON.stringify([ + guardrail.contentFilters, guardrail.deniedTopics, guardrail.piiFilters, guardrail.regexFilters, guardrail.wordFilters, + guardrail.managedWordListFilters, guardrail.contextualGroundingFilters, + guardrail.contentFiltersTierConfig, guardrail.topicsTierConfig, guardrail.crossRegionConfig, + ]); const published = configuration(); + const publishedSources = sources(); const hash = createHash('sha256').update(published).digest('hex'); const version = new CfnGuardrailVersion(guardrail, `Version${hash.slice(0, GUARDRAIL_VERSION_HASH_LENGTH)}`, { guardrailIdentifier: guardrail.guardrailId, description, }); - // The name is fixed now: a later change of the guardrail would reach the draft and no version. - // A property that takes a value from another stack renders differently by then, and fails too. + // The name is fixed now: a later change of the guardrail would reach the draft at most, and + // no version. A property that takes a value from another stack renders differently by then, + // and fails too. guardrail.node.addValidation({ - validate: () => configuration() === published ? [] : [ + validate: () => configuration() === published && sources() === publishedSources ? [] : [ 'The guardrail does not have the properties its version was named after: it was changed after ' + 'publishGuardrailVersion(), or one of its properties takes a value from another stack.', ], @@ -589,8 +604,8 @@ export class AgentStack extends Stack { // The version every consumer pins: `inputGuardrail.guardrailVersion` is the working // draft. The guardrail gets its whole configuration in the constructor above: a - // change made to it after this line would reach the draft and no published version, - // and synthesis fails on it. + // change made to it after this line would reach no published version. The comment + // of publishGuardrailVersion() says which changes fail the synthesis. const inputGuardrailVersion = publishGuardrailVersion(inputGuardrail, 'Initial version'); // --- TaskApi is constructed before the orchestrator (which it needs the diff --git a/cdk/test/stacks/agent.test.ts b/cdk/test/stacks/agent.test.ts index 05313fdde..04ada8982 100644 --- a/cdk/test/stacks/agent.test.ts +++ b/cdk/test/stacks/agent.test.ts @@ -1276,8 +1276,9 @@ describe('AgentStack', () => { // The guardrail's own Version attribute is DRAFT, which follows every edit instead of pinning one. expect(pinned).toEqual(pinned.map(() => published)); - // The version is named after the guardrail as CloudFormation receives it. A change made to - // the guardrail after its version was published fails the synthesis; this pins the name itself. + // The version is named after the guardrail as CloudFormation receives it. The tests of + // publishGuardrailVersion() cover a guardrail that is changed after its version was + // published; this pins the name itself. const [guardrail] = Object.values(template.findResources('AWS::Bedrock::Guardrail')); const { Tags: _tags, ...properties } = guardrail.Properties; const [[versionId, version]] = Object.entries(versions); @@ -1339,6 +1340,149 @@ describe('publishGuardrailVersion (#1079)', () => { }); expect(() => Template.fromStack(stack)).toThrow('it was changed after publishGuardrailVersion()'); }); + + const contentFilter = (type: bedrock.ContentFilterType): bedrock.ContentFilter => ({ + type, + inputStrength: bedrock.ContentFilterStrength.MEDIUM, + outputStrength: bedrock.ContentFilterStrength.NONE, + }); + const topic = (name: string) => bedrock.Topic.custom({ name, definition: `Advice on ${name}.`, examples: [`What should I do about ${name}?`] }); + const piiFilter = (type: bedrock.PIIType): bedrock.PIIFilter => ({ type, action: bedrock.GuardrailAction.BLOCK }); + const regexFilter = (name: string): bedrock.RegexFilter => ({ name, pattern: `${name}-[0-9]+`, action: bedrock.GuardrailAction.BLOCK }); + const groundingFilter = (type: bedrock.ContextualGroundingFilterType): bedrock.ContextualGroundingFilter => ({ type, threshold: 0.5 }); + const guardrailProfile = (geography: string) => `arn:aws:bedrock:us-east-1:123456789012:guardrail-profile/${geography}.guardrail.v1:0`; + + // The alpha construct keeps its first rendering of a policy that is not empty, and the + // function renders the guardrail at the call. Of the changes below, only the first two + // still show in the rendered properties after that: the function finds the others in the + // members that the construct renders those properties from. + test.each<[string, Omit, (guardrail: bedrock.Guardrail) => unknown]>([ + [ + 'has a property of its resource overridden', + {}, + guardrail => guardrail.node.children.find(child => child instanceof CfnGuardrail)!.addPropertyOverride('BlockedInputMessaging', 'No.'), + ], + [ + 'gets a second content filter', + { contentFilters: [contentFilter(bedrock.ContentFilterType.PROMPT_ATTACK)] }, + guardrail => guardrail.addContentFilter(contentFilter(bedrock.ContentFilterType.HATE)), + ], + [ + 'gets a second denied topic', + { deniedTopics: [topic('investments')] }, + guardrail => guardrail.addDeniedTopicFilter(topic('medication')), + ], + [ + 'gets a second PII filter', + { piiFilters: [piiFilter(bedrock.GeneralPIIType.ADDRESS)] }, + guardrail => guardrail.addPIIFilter(piiFilter(bedrock.GeneralPIIType.EMAIL)), + ], + [ + 'gets a second regex filter', + { regexFilters: [regexFilter('ticket')] }, + guardrail => guardrail.addRegexFilter(regexFilter('invoice')), + ], + [ + 'gets a second word filter', + { wordFilters: [{ text: 'first' }] }, + guardrail => guardrail.addWordFilter({ text: 'second' }), + ], + [ + // The library has one managed word list, and accepts it twice. + 'gets a second managed word list', + { managedWordListFilters: [{ type: bedrock.ManagedWordFilterType.PROFANITY }] }, + guardrail => guardrail.addManagedWordListFilter({ type: bedrock.ManagedWordFilterType.PROFANITY }), + ], + [ + 'gets a second contextual grounding filter', + { contextualGroundingFilters: [groundingFilter(bedrock.ContextualGroundingFilterType.GROUNDING)] }, + guardrail => guardrail.addContextualGroundingFilter(groundingFilter(bedrock.ContextualGroundingFilterType.RELEVANCE)), + ], + // Words and managed word lists share a policy, as regex and PII filters do. Once the + // policy is rendered, the empty list of the pair is kept as well. + [ + 'gets its first word filter beside a managed word list', + { managedWordListFilters: [{ type: bedrock.ManagedWordFilterType.PROFANITY }] }, + guardrail => guardrail.addWordFilter({ text: 'first' }), + ], + [ + 'gets its first managed word list beside a word filter', + { wordFilters: [{ text: 'first' }] }, + guardrail => guardrail.addManagedWordListFilter({ type: bedrock.ManagedWordFilterType.PROFANITY }), + ], + [ + 'gets its first regex filter beside a PII filter', + { piiFilters: [piiFilter(bedrock.GeneralPIIType.ADDRESS)] }, + guardrail => guardrail.addRegexFilter(regexFilter('ticket')), + ], + [ + 'gets its first PII filter beside a regex filter', + { regexFilters: [regexFilter('ticket')] }, + guardrail => guardrail.addPIIFilter(piiFilter(bedrock.GeneralPIIType.ADDRESS)), + ], + // No method of the construct makes the changes below: they are written to the object + // that the caller passed in, or to a member that TypeScript declares readonly. + [ + 'has one of its filters changed in place', + { wordFilters: [{ text: 'first' }] }, + guardrail => Object.assign(guardrail.wordFilters[0], { text: 'other' }), + ], + [ + 'has the type of its PII filter changed in place', + { piiFilters: [piiFilter(bedrock.GeneralPIIType.ADDRESS)] }, + guardrail => Object.assign(guardrail.piiFilters[0], { type: bedrock.GeneralPIIType.EMAIL }), + ], + [ + 'has its cross-Region profile changed in place', + { crossRegionConfig: { guardrailProfileArn: guardrailProfile('us') } }, + guardrail => Object.assign(guardrail.crossRegionConfig!, { guardrailProfileArn: guardrailProfile('eu') }), + ], + [ + 'has its list of content filters replaced', + { contentFilters: [contentFilter(bedrock.ContentFilterType.PROMPT_ATTACK)] }, + guardrail => Object.assign(guardrail, { contentFilters: [contentFilter(bedrock.ContentFilterType.HATE)] }), + ], + [ + 'has the tier of its content filters changed', + { contentFilters: [contentFilter(bedrock.ContentFilterType.PROMPT_ATTACK)] }, + guardrail => Object.assign(guardrail, { contentFiltersTierConfig: bedrock.TierConfig.STANDARD }), + ], + [ + 'has the tier of its denied topics changed', + { deniedTopics: [topic('investments')] }, + guardrail => Object.assign(guardrail, { topicsTierConfig: bedrock.TierConfig.STANDARD }), + ], + ])('fails the synthesis when the guardrail %s after its version was published', (_case, configured, change) => { + const stack = new Stack(new App(), 'Stack'); + const guardrail = new bedrock.Guardrail(stack, 'InputGuardrail', { guardrailName: 'input', ...configured }); + publishGuardrailVersion(guardrail, 'Initial version'); + change(guardrail); + expect(() => Template.fromStack(stack)).toThrow('it was changed after publishGuardrailVersion()'); + }); + + // The function compares the ten members that the alpha library renders the guardrail's + // properties from. A later version of the library that renders from one more can keep its + // first rendering of that one as well, and no test above would fail. This one fails when + // the new member is a list, or is read by a `generateCfn...` method as these ten are: name + // it in `sources` of the function, give it a row in the table above, and add it here. + test('knows the members that the alpha construct renders the properties from', () => { + const guardrail = new bedrock.Guardrail(new Stack(new App(), 'Stack'), 'InputGuardrail', { guardrailName: 'input' }); + const members = new Set(); + // What its `generateCfn...` methods read. The exported class is the one that its decorator + // returns, so the methods are further up. In their text, `this.generateCfn...` is a call + // of another of them, and no member. + for (let proto = Object.getPrototypeOf(guardrail); proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) { + for (const method of Object.getOwnPropertyNames(proto).filter(name => name.startsWith('generateCfn'))) { + for (const [, member] of String(proto[method]).matchAll(/\bthis\.(?!generateCfn)(\w+)/g)) members.add(member); + } + } + // And every list that the construct holds, whichever way a later version renders it. + for (const [member, value] of Object.entries(guardrail)) if (Array.isArray(value)) members.add(member); + expect([...members].sort()).toEqual([ + 'contentFilters', 'contentFiltersTierConfig', 'contextualGroundingFilters', 'crossRegionConfig', 'deniedTopics', + 'managedWordListFilters', 'piiFilters', 'regexFilters', 'topicsTierConfig', 'wordFilters', + ]); + }); }); /** diff --git a/docs/guides/DEPLOYMENT_GUIDE.md b/docs/guides/DEPLOYMENT_GUIDE.md index 8947d261c..76dddc7ce 100644 --- a/docs/guides/DEPLOYMENT_GUIDE.md +++ b/docs/guides/DEPLOYMENT_GUIDE.md @@ -523,7 +523,7 @@ In that call, `ModelInvocationLogging` writes the stack's log group and role to ### Deploys stop once the input guardrail reaches its version quota (#1079) -**Affects:** a stack deployed from a version between [#904](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/pull/904) and the fix of [#1079](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1079). Nearly every deploy of such a version published a new version of the input guardrail and kept the one before it, also when the guardrail had not changed. +**Affects:** a stack deployed from a version between [#904](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/pull/904) and the fix of [#1079](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1079). Nearly every deploy of such a version published a new version of the input guardrail and kept the one before it, also when the guardrail had not changed. Before the first deploy with the fix, count the guardrail's versions with the first two commands under **Resolution**: that deploy publishes one more version, and on a guardrail that is already at its quota it fails and the stack rolls back. **Symptom:** the deploy fails on the guardrail version and the stack rolls back to `UPDATE_ROLLBACK_COMPLETE`. Nearly every later deploy fails in the same way until old versions are deleted. diff --git a/docs/src/content/docs/getting-started/Deployment-guide.md b/docs/src/content/docs/getting-started/Deployment-guide.md index f1ea908e8..f2cfccf26 100644 --- a/docs/src/content/docs/getting-started/Deployment-guide.md +++ b/docs/src/content/docs/getting-started/Deployment-guide.md @@ -525,7 +525,7 @@ In that call, `ModelInvocationLogging` writes the stack's log group and role to ### Deploys stop once the input guardrail reaches its version quota (#1079) -**Affects:** a stack deployed from a version between [#904](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/pull/904) and the fix of [#1079](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1079). Nearly every deploy of such a version published a new version of the input guardrail and kept the one before it, also when the guardrail had not changed. +**Affects:** a stack deployed from a version between [#904](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/pull/904) and the fix of [#1079](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1079). Nearly every deploy of such a version published a new version of the input guardrail and kept the one before it, also when the guardrail had not changed. Before the first deploy with the fix, count the guardrail's versions with the first two commands under **Resolution**: that deploy publishes one more version, and on a guardrail that is already at its quota it fails and the stack rolls back. **Symptom:** the deploy fails on the guardrail version and the stack rolls back to `UPDATE_ROLLBACK_COMPLETE`. Nearly every later deploy fails in the same way until old versions are deleted. From c3e69bba51fefd7db2d79e032e88c75986a60689 Mon Sep 17 00:00:00 2001 From: bgagent Date: Wed, 25 Nov 2026 18:15:33 -0600 Subject: [PATCH 10/11] chore: mark what the workflow removal and the pin move left stale setup.ts: the hint after `--no-deploy` and two comments named a CI deploy. No workflow deploys since deploy.yml was removed, so the hint says "every deploy of this stack", and a test pins it. scripts/aws-emulator/README.md: the three statements that upstream's fix commits contradict are marked "Not probed again on 1.0.610" where they stand, with what upstream says changed and from which release. None of the three was observed on 1.0.610: no container engine was available. docs/research/aws-emulator-local-tests.md: a dated note in the status line says that what the document tells about deploy.yml, integ.yml, `mise //cdk:integ` and the integ smoke describes the earlier state, and six passages carry a marker that points to it. The other mentions stay as the record of 2026-11-15 that they are. .gitignore: the two lines for the integ runner's output are back. A checkout that ran the integ test may still have those directories, about 100 MB by the comment these lines had, and without the lines `git add .` would stage them. --- .gitignore | 9 +++++++++ cli/src/commands/setup.ts | 6 +++--- cli/test/commands/setup.test.ts | 1 + docs/research/aws-emulator-local-tests.md | 14 +++++++------- scripts/aws-emulator/README.md | 8 ++++---- 5 files changed, 24 insertions(+), 14 deletions(-) diff --git a/.gitignore b/.gitignore index 01f8cee21..2d7b33b43 100644 --- a/.gitignore +++ b/.gitignore @@ -67,6 +67,15 @@ cdk.out/ cdk.context.json /assets/ +# Output of the integ runner, which #1084 removed together with the integ test. +# Nothing writes these two directories any more. A checkout that ran the test +# may still have them: the snapshot holds a copy of every Lambda handler asset, +# about 100 MB. These lines keep `git add .` from staging them there, and +# `rm -rf cdk/test/integ` removes them. Only the runner's own directory names +# are ignored, so that a new file in cdk/test/integ still shows up. +/cdk/test/integ/*.snapshot/ +/cdk/test/integ/cdk-integ.out.*/ + # ────────────────────────────────────────────── # Build outputs (compiled TS → JS) # ────────────────────────────────────────────── diff --git a/cli/src/commands/setup.ts b/cli/src/commands/setup.ts index 1f1326e51..e58e348b6 100644 --- a/cli/src/commands/setup.ts +++ b/cli/src/commands/setup.ts @@ -738,7 +738,7 @@ export async function runSetup(opts: SetupOptions, deps: SetupDeps): Promise CAPABILITY_CATALOG.features[feature].stateful); if (stateful.length > 0) { ui.line(); @@ -748,7 +748,7 @@ export async function runSetup(opts: SetupOptions, deps: SetupDeps): Promise { await setup({ features: 'none', deploy: false }, deps({ interactive: false })); expect(profileOnDisk()).toEqual(MINIMAL_DEPLOYMENT_FEATURES); expect(runs).toEqual([]); + expect(text()).toContain('Commit it so every deploy of this stack uses the same features.'); }); test('--no-deploy that removes stateful features needs --accept-data-loss', async () => { diff --git a/docs/research/aws-emulator-local-tests.md b/docs/research/aws-emulator-local-tests.md index 1767bcd5d..2d864286c 100644 --- a/docs/research/aws-emulator-local-tests.md +++ b/docs/research/aws-emulator-local-tests.md @@ -1,6 +1,6 @@ # AWS Emulator for local and CI tests -**Status:** adopted as an advisory check. This is the investigation as it was handed over on 2026-11-15: unless a sentence says otherwise, it describes the proof of concept (then uncommitted, in a worktree of this branch) and `main` (`c8fcdb08`) as they stood that day. What was decided and done afterwards is in [Outcome](#outcome). The rules for tests in the tier and the list of known differences from AWS are maintained in [`scripts/aws-emulator/README.md`](../../scripts/aws-emulator/README.md), not here. +**Status:** adopted as an advisory check. This is the investigation as it was handed over on 2026-11-15: unless a sentence says otherwise, it describes the proof of concept (then uncommitted, in a worktree of this branch) and `main` (`c8fcdb08`) as they stood that day. What was decided and done afterwards is in [Outcome](#outcome). Pull request #1084 (2026-11-25) removed `deploy.yml`, `integ.yml`, the `mise //cdk:integ` task and the test that task ran (`cdk/test/integ/`): what this document says about them, about the real-AWS integ smoke and about its `integ-smoke` check describes the earlier state. The rules for tests in the tier and the list of known differences from AWS are maintained in [`scripts/aws-emulator/README.md`](../../scripts/aws-emulator/README.md), not here. **Date:** 2026-11-15 **Emulator version examined:** 1.0.385 (`aws/aws-emulator`, commit `813af48`) @@ -41,7 +41,7 @@ The main things that pull request adds to the proof of concept described in the | A session role that cannot be assumed does not abort the task | Fixed: the role is assumed when the session is first built, so the task stops before any work. The price is that an STS failure at task start that outlasts the SDK's retries now fails the task. When the role can never be assumed the user still reads "Agent session lost", because the agent has no credentials to record the reason | | The trajectory writer never retries stream creation | Fixed | | #51: list order and the empty filtered page | Fixed: a new index `UserCreatedAtIndex` on the task table, read until the page is full. The next deployment creates and backfills the index; on an existing stack the handler asks DynamoDB for the status of the new index and reads the old one, in its old order, until that status is `ACTIVE` (see "Known deployment issues" in the deployment guide) | -| `integ.yml` is blocked by its own concurrency group | Fixed on `main`: #1035 moved the group from the workflow to the `integ` job, and #1047 keyed it by pull request, so that runs of different pull requests no longer cancel each other (#1046). `integ.yml` and ADR-013 now also say that `integ-smoke` is not a required check. Whether `integ-smoke` becomes required is a ruleset setting and is open | +| `integ.yml` is blocked by its own concurrency group | Fixed on `main`: #1035 moved the group from the workflow to the `integ` job, and #1047 keyed it by pull request, so that runs of different pull requests no longer cancel each other (#1046). `integ.yml` and ADR-013 now also say that `integ-smoke` is not a required check. Whether `integ-smoke` becomes required is a ruleset setting and is open. (#1084 has since removed `integ.yml` and the check with it: see the note at the top) | | `upgrade-main` has failed since 2026-08-19 | Not a defect of a tracked file: the token in the repository secret `AUTOMATION_GITHUB_TOKEN` stopped being accepted. Open; it needs a new token | | The Slack cancel button writes less than `cancel-task` | Fixed: it writes `completed_at` and `status_created_at` | | `task_cancelled` is recorded twice | Left: both writers are needed and every consumer tolerates the repeat | @@ -57,7 +57,7 @@ Found while fixing, and not listed further down: | The confirm-uploads Lambda never receives the per-user cap, and admits against a fallback of 3 where the stack sets 10 | Fixed. Until open PR #1009, a confirmed attachment task still holds two seats, so the limit met on that path stays below the cap | | The presign-failure path of `create-task` fails a task without `completed_at`, a matching `status_created_at` or a `ttl` | Fixed | | `bgagent ops concurrency` prints a default limit of 3 where the stack deploys 10, and six documents said 3 or "3-5" | Fixed. The user guide and the API contract also said that a task over the limit fails; since #441 it is queued, and they now say so. Four more documents named the event that #441 removed (`admission_rejected`), and two examples showed a task failed at the limit; they are corrected too | -| The `integ` job's command has been unrunnable since #567: it passes `cdk deploy` arguments to `integ-runner`, which exits 1 | Fixed: the job runs `mise //cdk:integ` with nothing after it, and a unit test fails when the workflow passes the task an argument. The job has not run with the fix: it needs the `deploy` approval, and until this merges an approved run still uses `main`'s copy of the workflow | +| The `integ` job's command has been unrunnable since #567: it passes `cdk deploy` arguments to `integ-runner`, which exits 1 | Fixed: the job runs `mise //cdk:integ` with nothing after it, and a unit test fails when the workflow passes the task an argument. The job has not run with the fix: it needs the `deploy` approval, and until this merges an approved run still uses `main`'s copy of the workflow. (#1084 has since removed the job, the task and that unit test: see the note at the top) | | `auto-approve` cannot approve the pull requests `upgrade-main` opens, because one token does both | Open | | `upgrade-main.yml` reports a patch that `git apply` refuses as "Empty patch. Skipping.", and the run ends green | Open | | `GET /v1/pending` lists an approval request whose window has passed until DynamoDB deletes the row | Fixed (#1043): the list leaves the request out and reads on past such rows | @@ -263,7 +263,7 @@ If #1035 merges first, each slice of the rollout carries its own `knip.json` ent ### CI -A separate workflow, not a job in `build.yml`: `deploy.yml` and `integ.yml` start from `workflow_run` on `build` and need its conclusion to be `success`, so an advisory failure there would stop both. The workflow in [Appendix A](#appendix-a-workflow) uses no secret and `contents: read` only, so it runs unchanged for fork pull requests. It adds no finding to the repository's own `zizmor` gate and passes `actionlint`. +A separate workflow, not a job in `build.yml`: `deploy.yml` and `integ.yml` start from `workflow_run` on `build` and need its conclusion to be `success`, so an advisory failure there would stop both. (#1084 has since removed both; the header of `emulator.yml` gives the reason that holds now.) The workflow in [Appendix A](#appendix-a-workflow) uses no secret and `contents: read` only, so it runs unchanged for fork pull requests. It adds no finding to the repository's own `zizmor` gate and passes `actionlint`. It has not run on GitHub, and the three suites have run on macOS only. On Linux, an earlier version of the wrapper was exercised as an unprivileged user against a Linux Docker daemon on arm64 (`up` with the image copied in, a signed STS call through `run`, `down`), and the `linux/amd64` image was built and started under emulation on a Mac. Still to run on Linux: the image build through `emulator.sh up`, the wrapper as it is now, and jest and pytest under the loopback guards. The first run on a GitHub-hosted runner covers all of these. @@ -286,7 +286,7 @@ Pinning is not optional. The user guide says passing fidelity tests do not regre | Hand-written DynamoDB fakes | Replace later, after measuring what they contribute to the coverage thresholds | | Issue #61 | `agent/tests_emulator/test_trace_round_trip.py` meets its end-to-end and under-10-seconds criteria. Its opt-in marker criterion is met differently (a separate directory and run, not a marker) and its README criterion is not met | | ADR-013 | Replace the LocalStack wording with the emulator; replace the "60%+" sentence with the measured statement in [What it is worth](#what-it-is-worth); add the graduation criteria below; state that Tier 2c (the ephemeral stack deploy, which the ADR expects to catch IAM gaps) stays on real AWS | -| Real-AWS integ smoke | Keep as the authority for IAM, deployment and API Gateway wiring, and unblock it; the emulator tier does not stand in for it | +| Real-AWS integ smoke | Keep as the authority for IAM, deployment and API Gateway wiring, and unblock it; the emulator tier does not stand in for it. (Not what happened: #1084 removed it, see the note at the top. No test in the repository deploys to AWS now) | ## Deploying to the emulator @@ -378,14 +378,14 @@ Decided on 2026-11-15 (see [Outcome](#outcome)): 1 (yes), 2 (a red check that is 4. Do known-defect witnesses (`test.failing`) ship, or only passing tests? A `test.failing` passes on any throw, so each has to be run once as a plain test; the alternative is a test that asserts today's wrong value and fails when it is fixed. The repository already ships one such witness (`cdk/test/integration/orchestration-e2e.test.ts:402-412`). 5. Keep the five agent tests that expect an emulator-evaluated denial, knowing they can break with an emulator release? 6. Directory names: `test/emulator` and `tests_emulator` (what the tests need) or `integration` (what ADR-013 and issue #61 call the tier). `cdk/test/integration` already holds fake-backed tests that run in the unit tier. -7. `integ.yml`: unblock it (open #400 proposes relaxing the same concurrency group), and should `integ-smoke` be a required check? `integ.yml` and ADR-013 call it required; the ruleset does not list it. +7. `integ.yml`: unblock it (open #400 proposes relaxing the same concurrency group), and should `integ-smoke` be a required check? `integ.yml` and ADR-013 call it required; the ruleset does not list it. (Settled another way: #1084 removed `integ.yml`, see the note at the top.) 8. Which of the defects marked "None" to file, and in what order. The #51 fix and the status writers are one design, and the approval-sweep fix has to land in whichever writer is current when #1013 merges. 9. The issues the tier needs before any branch (ADR-003): one per slice. #61 is open and not labeled `approved`. 10. Which upstream reports to file (Appendix B). ## Appendix A: workflow -`.github/workflows/emulator.yml`. The committed file is this block, byte for byte. +`.github/workflows/emulator.yml`. The committed file is this block, byte for byte. (No longer: an action pin has moved since, and #1084 replaced the last paragraph of the header comment, the one that names `deploy.yml` and `integ.yml`, when it removed those two workflows.) ```yaml name: emulator diff --git a/scripts/aws-emulator/README.md b/scripts/aws-emulator/README.md index 798660079..ee0083e47 100644 --- a/scripts/aws-emulator/README.md +++ b/scripts/aws-emulator/README.md @@ -56,7 +56,7 @@ The agent suite contains tests that expect a denial: cross-tenant calls refused Some operations ABCA calls do not work on the emulator and stay on mocks: -- Answered with 501 `NotImplemented`: `InvokeAgentRuntime`, `StopRuntimeSession`, `RetrieveMemoryRecords`, `GetResourceOauth2Token`, `CompleteResourceTokenAuth` and `UpdateRegistry`. ABCA catches the error from `StopRuntimeSession`, `RetrieveMemoryRecords` and `GetResourceOauth2Token` and continues, so a test of those paths is green while exercising only the fallback (rule 6). +- Answered with 501 `NotImplemented`: `InvokeAgentRuntime`, `StopRuntimeSession`, `RetrieveMemoryRecords`, `GetResourceOauth2Token`, `CompleteResourceTokenAuth` and `UpdateRegistry`. ABCA catches the error from `StopRuntimeSession`, `RetrieveMemoryRecords` and `GetResourceOauth2Token` and continues, so a test of those paths is green while exercising only the fallback (rule 6). **Not probed again on 1.0.610:** upstream's fix commits say that `CompleteResourceTokenAuth` is implemented from 1.0.555 and `StopRuntimeSession` from 1.0.579, and that from 1.0.579 `InvokeAgentRuntime` refuses a caller without permission (403) or a runtime that does not exist (404) before it answers 501. - `ApplyGuardrail` needs a test-side HTTP/1.1 request handler: the bedrock-runtime client negotiates HTTP/2 and the emulator offers only HTTP/1.1. - `CreateEvent` is answered with 201 and the event is stored, but the JavaScript SDK the repository installs (3.1166.0) cannot read the answer: `eventTimestamp` arrives as a number with nine fraction digits and the client throws `TypeError`. `writeMinimalEpisode` catches it, logs an error and returns `false`, so a test of that path sees a failed write of an event that exists (rule 6). boto3 reads the same answer. @@ -70,7 +70,7 @@ Recorded on emulator 1.0.489. Keep this table and the lists above current when t | A `Query` on an index that `UpdateTable` is still creating is answered; AWS does not allow it until the index is `ACTIVE`. The emulator does report the index as `CREATING`, for about 3 seconds | Code that queries an index before it is `ACTIVE` passes here and fails on AWS. Code that asks for the index status first, as the task list does, can be tested | | Index reads always reflect the preceding write, and a transaction is never cancelled with `TransactionConflict` | A read-after-write through a GSI can never miss here, and the retry for a conflicting transaction cannot be reached | | Throttling and partial batches occur only at the limits the emulator models, which are AWS's documented ones: a provisioned table past its units, one partition key written past 1,000 write units in a second (three puts of about 390 KB), a `BatchGetItem` past 16 MB | ABCA's on-demand tables with ordinary rows do not reach them. A test with large rows on one key can be throttled, and those branches can be exercised on purpose | -| About ten malformed expression forms are accepted, and a condition comparing an attribute with itself lets the write through | A typo of that kind passes here and is refused by AWS | +| About ten malformed expression forms are accepted, and a condition comparing an attribute with itself lets the write through. **Not probed again on 1.0.610:** upstream's fix commit says that from 1.0.578 a comparison of an attribute with itself is refused, and so are doubled parentheses in a key condition, a document path into a key attribute, a map step and a list step on one attribute, and a start key beside a fully pinned key | A typo of that kind passes here and is refused by AWS | | Presigned POST: the policy and the signature are not enforced the way S3 enforces them | A test that the bucket refuses an upload outside the policy cannot be written here | | A bucket holds at most 1,000 objects, counting every version and delete marker; a write that adds one more is refused with `ValidationException` | A listing at the default page size never has a second page, so the second page of the upload cleanup loop cannot be reached here | | A force-deleted secret keeps its name blocked for about 0.5 seconds | Remove-then-recreate in one test needs a retry | @@ -78,11 +78,11 @@ Recorded on emulator 1.0.489. Keep this table and the lists above current when t | The `iss` claim of a Cognito token names the emulator, `https://cognito-idp..localhost:/` in the tier; AWS issues `https://cognito-idp..amazonaws.com/` | A verifier that derives the issuer from the pool id, as the one in the API's authorizer does, refuses every token the emulator issues | | A second Agent Registry record under a name the registry already holds is refused with `ConflictException`, whatever its `recordVersion`; the AWS [user guide](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/registry-concepts.html#registry-concept-record) says the combination of name and `recordVersion` must be unique, so that a name can be reused across versions | ABCA publishes every version of an asset under the same record name, so a second version of an asset cannot be published here. That, and resolving across versions, stay on mocks | | `CreateRegistryRecord` parses every descriptor `data` member as JSON and refuses anything else with `ValidationException`, the skill Markdown in `agentSkillsDefinition.additionalData.skillMd.data` included; the AWS [user guide](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/registry-supported-record-types.html#registry-agentskills-descriptors) gives a Markdown `SKILL.md` as valid content of that member | ABCA publishes a `skill` as a native record with a Markdown `SKILL.md`, so a skill can be published here only with `custom: true`. Native skills, and the read paths for a corrupt `SKILL.md` or a record body that is not JSON, stay on mocks | -| An MCP record whose `server.json` matches no MCP schema version (for example one without name, description and version) is accepted; AWS's published test for the emulator expects `ValidationException` | An `mcp_server` publish with an incomplete `discovery` passes here | +| An MCP record whose `server.json` matches no MCP schema version (for example one without name, description and version) is accepted; AWS's published test for the emulator expects `ValidationException`. **Not probed again on 1.0.610:** upstream's fix commit says that from 1.0.544 such a record is refused | An `mcp_server` publish with an incomplete `discovery` passes here | On emulator 1.0.523, DynamoDB `UpdateItem` rejects `REMOVE amount.child` with `ValidationException` when `amount` is a number. On 1.0.489 the same update succeeded and left `amount` unchanged. Both versions allowed `PutItem` to replace an item when its condition compared an attribute with itself. -The pin is 1.0.610. It was moved without the local run of step 1 under [Moving the version pin](#moving-the-version-pin): the suites ran on it for the first time in CI, where all three passed, and nothing in this file was probed again. One row was brought up to date from that run: the `iss` claim, whose host changed in 1.0.606 and which the `cli` suite asserts. Upstream's release notes and fix commits after 1.0.523 say that three more statements no longer hold as written, and none of that was observed here: the malformed expression forms (from 1.0.578 a comparison of an attribute with itself is refused, and so are doubled parentheses in a key condition, a document path into a key attribute, a map step and a list step on one attribute, and a start key beside a fully pinned key), an MCP record that matches no schema version (refused from 1.0.544), and the operations answered with 501 (`CompleteResourceTokenAuth` and `StopRuntimeSession` are implemented, from 1.0.555 and 1.0.579; `InvokeAgentRuntime` answers 403 or 404 before any 501 from 1.0.579). +The pin is 1.0.610. It was moved without the local run of step 1 under [Moving the version pin](#moving-the-version-pin): the suites ran on it for the first time in CI, where all three passed, and nothing in this file was probed again. One row was brought up to date from that run: the `iss` claim, whose host changed in 1.0.606 and which the `cli` suite asserts. Upstream's release notes and fix commits after 1.0.523 say that three more statements no longer hold as written, and none of that was observed here: the malformed expression forms, an MCP record that matches no schema version, and the operations answered with 501. Each is marked "Not probed again on 1.0.610" where it stands, with what upstream says changed and from which release. ## Keeping the tier away from real AWS From a03d77848340b897584b650c29e254043da7ca46 Mon Sep 17 00:00:00 2001 From: bgagent Date: Wed, 25 Nov 2026 18:16:18 -0600 Subject: [PATCH 11/11] ci: drop the actions permission of the build job The job asked for `actions: write`, "upload-artifact when self-mutation is detected". The pinned upload-artifact takes no token: it uploads, and deletes for `overwrite`, through the results service with the run's own runtime token. upgrade-main.yml runs the same step under `contents: read`. --- .github/workflows/build.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b8bca9fa2..5bb8dd9bb 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -32,7 +32,6 @@ concurrency: jobs: build: permissions: - actions: write # upload-artifact when self-mutation is detected contents: read # A hung build must not hold a runner for the 360-minute default. The longest # of 194 recorded jobs took 27 minutes (on one jest worker), and the merge